inode.c 291 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867
  1. /*
  2. * Copyright (C) 2007 Oracle. All rights reserved.
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public
  6. * License v2 as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. * General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public
  14. * License along with this program; if not, write to the
  15. * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  16. * Boston, MA 021110-1307, USA.
  17. */
  18. #include <linux/kernel.h>
  19. #include <linux/bio.h>
  20. #include <linux/buffer_head.h>
  21. #include <linux/file.h>
  22. #include <linux/fs.h>
  23. #include <linux/pagemap.h>
  24. #include <linux/highmem.h>
  25. #include <linux/time.h>
  26. #include <linux/init.h>
  27. #include <linux/string.h>
  28. #include <linux/backing-dev.h>
  29. #include <linux/mpage.h>
  30. #include <linux/swap.h>
  31. #include <linux/writeback.h>
  32. #include <linux/compat.h>
  33. #include <linux/bit_spinlock.h>
  34. #include <linux/xattr.h>
  35. #include <linux/posix_acl.h>
  36. #include <linux/falloc.h>
  37. #include <linux/slab.h>
  38. #include <linux/ratelimit.h>
  39. #include <linux/mount.h>
  40. #include <linux/btrfs.h>
  41. #include <linux/blkdev.h>
  42. #include <linux/posix_acl_xattr.h>
  43. #include <linux/uio.h>
  44. #include <linux/magic.h>
  45. #include "ctree.h"
  46. #include "disk-io.h"
  47. #include "transaction.h"
  48. #include "btrfs_inode.h"
  49. #include "print-tree.h"
  50. #include "ordered-data.h"
  51. #include "xattr.h"
  52. #include "tree-log.h"
  53. #include "volumes.h"
  54. #include "compression.h"
  55. #include "locking.h"
  56. #include "free-space-cache.h"
  57. #include "inode-map.h"
  58. #include "backref.h"
  59. #include "hash.h"
  60. #include "props.h"
  61. #include "qgroup.h"
  62. #include "dedupe.h"
  63. struct btrfs_iget_args {
  64. struct btrfs_key *location;
  65. struct btrfs_root *root;
  66. };
  67. struct btrfs_dio_data {
  68. u64 reserve;
  69. u64 unsubmitted_oe_range_start;
  70. u64 unsubmitted_oe_range_end;
  71. int overwrite;
  72. };
  73. static const struct inode_operations btrfs_dir_inode_operations;
  74. static const struct inode_operations btrfs_symlink_inode_operations;
  75. static const struct inode_operations btrfs_dir_ro_inode_operations;
  76. static const struct inode_operations btrfs_special_inode_operations;
  77. static const struct inode_operations btrfs_file_inode_operations;
  78. static const struct address_space_operations btrfs_aops;
  79. static const struct address_space_operations btrfs_symlink_aops;
  80. static const struct file_operations btrfs_dir_file_operations;
  81. static const struct extent_io_ops btrfs_extent_io_ops;
  82. static struct kmem_cache *btrfs_inode_cachep;
  83. struct kmem_cache *btrfs_trans_handle_cachep;
  84. struct kmem_cache *btrfs_path_cachep;
  85. struct kmem_cache *btrfs_free_space_cachep;
  86. #define S_SHIFT 12
  87. static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
  88. [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
  89. [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
  90. [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
  91. [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
  92. [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
  93. [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
  94. [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
  95. };
  96. static int btrfs_setsize(struct inode *inode, struct iattr *attr);
  97. static int btrfs_truncate(struct inode *inode);
  98. static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
  99. static noinline int cow_file_range(struct inode *inode,
  100. struct page *locked_page,
  101. u64 start, u64 end, u64 delalloc_end,
  102. int *page_started, unsigned long *nr_written,
  103. int unlock, struct btrfs_dedupe_hash *hash);
  104. static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
  105. u64 orig_start, u64 block_start,
  106. u64 block_len, u64 orig_block_len,
  107. u64 ram_bytes, int compress_type,
  108. int type);
  109. static void __endio_write_update_ordered(struct inode *inode,
  110. const u64 offset, const u64 bytes,
  111. const bool uptodate);
  112. /*
  113. * Cleanup all submitted ordered extents in specified range to handle errors
  114. * from the fill_dellaloc() callback.
  115. *
  116. * NOTE: caller must ensure that when an error happens, it can not call
  117. * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
  118. * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
  119. * to be released, which we want to happen only when finishing the ordered
  120. * extent (btrfs_finish_ordered_io()). Also note that the caller of the
  121. * fill_delalloc() callback already does proper cleanup for the first page of
  122. * the range, that is, it invokes the callback writepage_end_io_hook() for the
  123. * range of the first page.
  124. */
  125. static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
  126. const u64 offset,
  127. const u64 bytes)
  128. {
  129. unsigned long index = offset >> PAGE_SHIFT;
  130. unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
  131. struct page *page;
  132. while (index <= end_index) {
  133. page = find_get_page(inode->i_mapping, index);
  134. index++;
  135. if (!page)
  136. continue;
  137. ClearPagePrivate2(page);
  138. put_page(page);
  139. }
  140. return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
  141. bytes - PAGE_SIZE, false);
  142. }
  143. static int btrfs_dirty_inode(struct inode *inode);
  144. #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
  145. void btrfs_test_inode_set_ops(struct inode *inode)
  146. {
  147. BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
  148. }
  149. #endif
  150. static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
  151. struct inode *inode, struct inode *dir,
  152. const struct qstr *qstr)
  153. {
  154. int err;
  155. err = btrfs_init_acl(trans, inode, dir);
  156. if (!err)
  157. err = btrfs_xattr_security_init(trans, inode, dir, qstr);
  158. return err;
  159. }
  160. /*
  161. * this does all the hard work for inserting an inline extent into
  162. * the btree. The caller should have done a btrfs_drop_extents so that
  163. * no overlapping inline items exist in the btree
  164. */
  165. static int insert_inline_extent(struct btrfs_trans_handle *trans,
  166. struct btrfs_path *path, int extent_inserted,
  167. struct btrfs_root *root, struct inode *inode,
  168. u64 start, size_t size, size_t compressed_size,
  169. int compress_type,
  170. struct page **compressed_pages)
  171. {
  172. struct extent_buffer *leaf;
  173. struct page *page = NULL;
  174. char *kaddr;
  175. unsigned long ptr;
  176. struct btrfs_file_extent_item *ei;
  177. int ret;
  178. size_t cur_size = size;
  179. unsigned long offset;
  180. if (compressed_size && compressed_pages)
  181. cur_size = compressed_size;
  182. inode_add_bytes(inode, size);
  183. if (!extent_inserted) {
  184. struct btrfs_key key;
  185. size_t datasize;
  186. key.objectid = btrfs_ino(BTRFS_I(inode));
  187. key.offset = start;
  188. key.type = BTRFS_EXTENT_DATA_KEY;
  189. datasize = btrfs_file_extent_calc_inline_size(cur_size);
  190. path->leave_spinning = 1;
  191. ret = btrfs_insert_empty_item(trans, root, path, &key,
  192. datasize);
  193. if (ret)
  194. goto fail;
  195. }
  196. leaf = path->nodes[0];
  197. ei = btrfs_item_ptr(leaf, path->slots[0],
  198. struct btrfs_file_extent_item);
  199. btrfs_set_file_extent_generation(leaf, ei, trans->transid);
  200. btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
  201. btrfs_set_file_extent_encryption(leaf, ei, 0);
  202. btrfs_set_file_extent_other_encoding(leaf, ei, 0);
  203. btrfs_set_file_extent_ram_bytes(leaf, ei, size);
  204. ptr = btrfs_file_extent_inline_start(ei);
  205. if (compress_type != BTRFS_COMPRESS_NONE) {
  206. struct page *cpage;
  207. int i = 0;
  208. while (compressed_size > 0) {
  209. cpage = compressed_pages[i];
  210. cur_size = min_t(unsigned long, compressed_size,
  211. PAGE_SIZE);
  212. kaddr = kmap_atomic(cpage);
  213. write_extent_buffer(leaf, kaddr, ptr, cur_size);
  214. kunmap_atomic(kaddr);
  215. i++;
  216. ptr += cur_size;
  217. compressed_size -= cur_size;
  218. }
  219. btrfs_set_file_extent_compression(leaf, ei,
  220. compress_type);
  221. } else {
  222. page = find_get_page(inode->i_mapping,
  223. start >> PAGE_SHIFT);
  224. btrfs_set_file_extent_compression(leaf, ei, 0);
  225. kaddr = kmap_atomic(page);
  226. offset = start & (PAGE_SIZE - 1);
  227. write_extent_buffer(leaf, kaddr + offset, ptr, size);
  228. kunmap_atomic(kaddr);
  229. put_page(page);
  230. }
  231. btrfs_mark_buffer_dirty(leaf);
  232. btrfs_release_path(path);
  233. /*
  234. * we're an inline extent, so nobody can
  235. * extend the file past i_size without locking
  236. * a page we already have locked.
  237. *
  238. * We must do any isize and inode updates
  239. * before we unlock the pages. Otherwise we
  240. * could end up racing with unlink.
  241. */
  242. BTRFS_I(inode)->disk_i_size = inode->i_size;
  243. ret = btrfs_update_inode(trans, root, inode);
  244. fail:
  245. return ret;
  246. }
  247. /*
  248. * conditionally insert an inline extent into the file. This
  249. * does the checks required to make sure the data is small enough
  250. * to fit as an inline extent.
  251. */
  252. static noinline int cow_file_range_inline(struct btrfs_root *root,
  253. struct inode *inode, u64 start,
  254. u64 end, size_t compressed_size,
  255. int compress_type,
  256. struct page **compressed_pages)
  257. {
  258. struct btrfs_fs_info *fs_info = root->fs_info;
  259. struct btrfs_trans_handle *trans;
  260. u64 isize = i_size_read(inode);
  261. u64 actual_end = min(end + 1, isize);
  262. u64 inline_len = actual_end - start;
  263. u64 aligned_end = ALIGN(end, fs_info->sectorsize);
  264. u64 data_len = inline_len;
  265. int ret;
  266. struct btrfs_path *path;
  267. int extent_inserted = 0;
  268. u32 extent_item_size;
  269. if (compressed_size)
  270. data_len = compressed_size;
  271. if (start > 0 ||
  272. actual_end > fs_info->sectorsize ||
  273. data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
  274. (!compressed_size &&
  275. (actual_end & (fs_info->sectorsize - 1)) == 0) ||
  276. end + 1 < isize ||
  277. data_len > fs_info->max_inline) {
  278. return 1;
  279. }
  280. path = btrfs_alloc_path();
  281. if (!path)
  282. return -ENOMEM;
  283. trans = btrfs_join_transaction(root);
  284. if (IS_ERR(trans)) {
  285. btrfs_free_path(path);
  286. return PTR_ERR(trans);
  287. }
  288. trans->block_rsv = &BTRFS_I(inode)->block_rsv;
  289. if (compressed_size && compressed_pages)
  290. extent_item_size = btrfs_file_extent_calc_inline_size(
  291. compressed_size);
  292. else
  293. extent_item_size = btrfs_file_extent_calc_inline_size(
  294. inline_len);
  295. ret = __btrfs_drop_extents(trans, root, inode, path,
  296. start, aligned_end, NULL,
  297. 1, 1, extent_item_size, &extent_inserted);
  298. if (ret) {
  299. btrfs_abort_transaction(trans, ret);
  300. goto out;
  301. }
  302. if (isize > actual_end)
  303. inline_len = min_t(u64, isize, actual_end);
  304. ret = insert_inline_extent(trans, path, extent_inserted,
  305. root, inode, start,
  306. inline_len, compressed_size,
  307. compress_type, compressed_pages);
  308. if (ret && ret != -ENOSPC) {
  309. btrfs_abort_transaction(trans, ret);
  310. goto out;
  311. } else if (ret == -ENOSPC) {
  312. ret = 1;
  313. goto out;
  314. }
  315. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
  316. btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
  317. out:
  318. /*
  319. * Don't forget to free the reserved space, as for inlined extent
  320. * it won't count as data extent, free them directly here.
  321. * And at reserve time, it's always aligned to page size, so
  322. * just free one page here.
  323. */
  324. btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
  325. btrfs_free_path(path);
  326. btrfs_end_transaction(trans);
  327. return ret;
  328. }
  329. struct async_extent {
  330. u64 start;
  331. u64 ram_size;
  332. u64 compressed_size;
  333. struct page **pages;
  334. unsigned long nr_pages;
  335. int compress_type;
  336. struct list_head list;
  337. };
  338. struct async_cow {
  339. struct inode *inode;
  340. struct btrfs_root *root;
  341. struct page *locked_page;
  342. u64 start;
  343. u64 end;
  344. unsigned int write_flags;
  345. struct list_head extents;
  346. struct btrfs_work work;
  347. };
  348. static noinline int add_async_extent(struct async_cow *cow,
  349. u64 start, u64 ram_size,
  350. u64 compressed_size,
  351. struct page **pages,
  352. unsigned long nr_pages,
  353. int compress_type)
  354. {
  355. struct async_extent *async_extent;
  356. async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
  357. BUG_ON(!async_extent); /* -ENOMEM */
  358. async_extent->start = start;
  359. async_extent->ram_size = ram_size;
  360. async_extent->compressed_size = compressed_size;
  361. async_extent->pages = pages;
  362. async_extent->nr_pages = nr_pages;
  363. async_extent->compress_type = compress_type;
  364. list_add_tail(&async_extent->list, &cow->extents);
  365. return 0;
  366. }
  367. static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
  368. {
  369. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  370. /* force compress */
  371. if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
  372. return 1;
  373. /* defrag ioctl */
  374. if (BTRFS_I(inode)->defrag_compress)
  375. return 1;
  376. /* bad compression ratios */
  377. if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
  378. return 0;
  379. if (btrfs_test_opt(fs_info, COMPRESS) ||
  380. BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
  381. BTRFS_I(inode)->prop_compress)
  382. return btrfs_compress_heuristic(inode, start, end);
  383. return 0;
  384. }
  385. static inline void inode_should_defrag(struct btrfs_inode *inode,
  386. u64 start, u64 end, u64 num_bytes, u64 small_write)
  387. {
  388. /* If this is a small write inside eof, kick off a defrag */
  389. if (num_bytes < small_write &&
  390. (start > 0 || end + 1 < inode->disk_i_size))
  391. btrfs_add_inode_defrag(NULL, inode);
  392. }
  393. /*
  394. * we create compressed extents in two phases. The first
  395. * phase compresses a range of pages that have already been
  396. * locked (both pages and state bits are locked).
  397. *
  398. * This is done inside an ordered work queue, and the compression
  399. * is spread across many cpus. The actual IO submission is step
  400. * two, and the ordered work queue takes care of making sure that
  401. * happens in the same order things were put onto the queue by
  402. * writepages and friends.
  403. *
  404. * If this code finds it can't get good compression, it puts an
  405. * entry onto the work queue to write the uncompressed bytes. This
  406. * makes sure that both compressed inodes and uncompressed inodes
  407. * are written in the same order that the flusher thread sent them
  408. * down.
  409. */
  410. static noinline void compress_file_range(struct inode *inode,
  411. struct page *locked_page,
  412. u64 start, u64 end,
  413. struct async_cow *async_cow,
  414. int *num_added)
  415. {
  416. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  417. struct btrfs_root *root = BTRFS_I(inode)->root;
  418. u64 blocksize = fs_info->sectorsize;
  419. u64 actual_end;
  420. u64 isize = i_size_read(inode);
  421. int ret = 0;
  422. struct page **pages = NULL;
  423. unsigned long nr_pages;
  424. unsigned long total_compressed = 0;
  425. unsigned long total_in = 0;
  426. int i;
  427. int will_compress;
  428. int compress_type = fs_info->compress_type;
  429. int redirty = 0;
  430. inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
  431. SZ_16K);
  432. actual_end = min_t(u64, isize, end + 1);
  433. again:
  434. will_compress = 0;
  435. nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
  436. BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
  437. nr_pages = min_t(unsigned long, nr_pages,
  438. BTRFS_MAX_COMPRESSED / PAGE_SIZE);
  439. /*
  440. * we don't want to send crud past the end of i_size through
  441. * compression, that's just a waste of CPU time. So, if the
  442. * end of the file is before the start of our current
  443. * requested range of bytes, we bail out to the uncompressed
  444. * cleanup code that can deal with all of this.
  445. *
  446. * It isn't really the fastest way to fix things, but this is a
  447. * very uncommon corner.
  448. */
  449. if (actual_end <= start)
  450. goto cleanup_and_bail_uncompressed;
  451. total_compressed = actual_end - start;
  452. /*
  453. * skip compression for a small file range(<=blocksize) that
  454. * isn't an inline extent, since it doesn't save disk space at all.
  455. */
  456. if (total_compressed <= blocksize &&
  457. (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
  458. goto cleanup_and_bail_uncompressed;
  459. total_compressed = min_t(unsigned long, total_compressed,
  460. BTRFS_MAX_UNCOMPRESSED);
  461. total_in = 0;
  462. ret = 0;
  463. /*
  464. * we do compression for mount -o compress and when the
  465. * inode has not been flagged as nocompress. This flag can
  466. * change at any time if we discover bad compression ratios.
  467. */
  468. if (inode_need_compress(inode, start, end)) {
  469. WARN_ON(pages);
  470. pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
  471. if (!pages) {
  472. /* just bail out to the uncompressed code */
  473. goto cont;
  474. }
  475. if (BTRFS_I(inode)->defrag_compress)
  476. compress_type = BTRFS_I(inode)->defrag_compress;
  477. else if (BTRFS_I(inode)->prop_compress)
  478. compress_type = BTRFS_I(inode)->prop_compress;
  479. /*
  480. * we need to call clear_page_dirty_for_io on each
  481. * page in the range. Otherwise applications with the file
  482. * mmap'd can wander in and change the page contents while
  483. * we are compressing them.
  484. *
  485. * If the compression fails for any reason, we set the pages
  486. * dirty again later on.
  487. */
  488. extent_range_clear_dirty_for_io(inode, start, end);
  489. redirty = 1;
  490. /* Compression level is applied here and only here */
  491. ret = btrfs_compress_pages(
  492. compress_type | (fs_info->compress_level << 4),
  493. inode->i_mapping, start,
  494. pages,
  495. &nr_pages,
  496. &total_in,
  497. &total_compressed);
  498. if (!ret) {
  499. unsigned long offset = total_compressed &
  500. (PAGE_SIZE - 1);
  501. struct page *page = pages[nr_pages - 1];
  502. char *kaddr;
  503. /* zero the tail end of the last page, we might be
  504. * sending it down to disk
  505. */
  506. if (offset) {
  507. kaddr = kmap_atomic(page);
  508. memset(kaddr + offset, 0,
  509. PAGE_SIZE - offset);
  510. kunmap_atomic(kaddr);
  511. }
  512. will_compress = 1;
  513. }
  514. }
  515. cont:
  516. if (start == 0) {
  517. /* lets try to make an inline extent */
  518. if (ret || total_in < actual_end) {
  519. /* we didn't compress the entire range, try
  520. * to make an uncompressed inline extent.
  521. */
  522. ret = cow_file_range_inline(root, inode, start, end,
  523. 0, BTRFS_COMPRESS_NONE, NULL);
  524. } else {
  525. /* try making a compressed inline extent */
  526. ret = cow_file_range_inline(root, inode, start, end,
  527. total_compressed,
  528. compress_type, pages);
  529. }
  530. if (ret <= 0) {
  531. unsigned long clear_flags = EXTENT_DELALLOC |
  532. EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
  533. EXTENT_DO_ACCOUNTING;
  534. unsigned long page_error_op;
  535. page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
  536. /*
  537. * inline extent creation worked or returned error,
  538. * we don't need to create any more async work items.
  539. * Unlock and free up our temp pages.
  540. *
  541. * We use DO_ACCOUNTING here because we need the
  542. * delalloc_release_metadata to be done _after_ we drop
  543. * our outstanding extent for clearing delalloc for this
  544. * range.
  545. */
  546. extent_clear_unlock_delalloc(inode, start, end, end,
  547. NULL, clear_flags,
  548. PAGE_UNLOCK |
  549. PAGE_CLEAR_DIRTY |
  550. PAGE_SET_WRITEBACK |
  551. page_error_op |
  552. PAGE_END_WRITEBACK);
  553. goto free_pages_out;
  554. }
  555. }
  556. if (will_compress) {
  557. /*
  558. * we aren't doing an inline extent round the compressed size
  559. * up to a block size boundary so the allocator does sane
  560. * things
  561. */
  562. total_compressed = ALIGN(total_compressed, blocksize);
  563. /*
  564. * one last check to make sure the compression is really a
  565. * win, compare the page count read with the blocks on disk,
  566. * compression must free at least one sector size
  567. */
  568. total_in = ALIGN(total_in, PAGE_SIZE);
  569. if (total_compressed + blocksize <= total_in) {
  570. *num_added += 1;
  571. /*
  572. * The async work queues will take care of doing actual
  573. * allocation on disk for these compressed pages, and
  574. * will submit them to the elevator.
  575. */
  576. add_async_extent(async_cow, start, total_in,
  577. total_compressed, pages, nr_pages,
  578. compress_type);
  579. if (start + total_in < end) {
  580. start += total_in;
  581. pages = NULL;
  582. cond_resched();
  583. goto again;
  584. }
  585. return;
  586. }
  587. }
  588. if (pages) {
  589. /*
  590. * the compression code ran but failed to make things smaller,
  591. * free any pages it allocated and our page pointer array
  592. */
  593. for (i = 0; i < nr_pages; i++) {
  594. WARN_ON(pages[i]->mapping);
  595. put_page(pages[i]);
  596. }
  597. kfree(pages);
  598. pages = NULL;
  599. total_compressed = 0;
  600. nr_pages = 0;
  601. /* flag the file so we don't compress in the future */
  602. if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
  603. !(BTRFS_I(inode)->prop_compress)) {
  604. BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
  605. }
  606. }
  607. cleanup_and_bail_uncompressed:
  608. /*
  609. * No compression, but we still need to write the pages in the file
  610. * we've been given so far. redirty the locked page if it corresponds
  611. * to our extent and set things up for the async work queue to run
  612. * cow_file_range to do the normal delalloc dance.
  613. */
  614. if (page_offset(locked_page) >= start &&
  615. page_offset(locked_page) <= end)
  616. __set_page_dirty_nobuffers(locked_page);
  617. /* unlocked later on in the async handlers */
  618. if (redirty)
  619. extent_range_redirty_for_io(inode, start, end);
  620. add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
  621. BTRFS_COMPRESS_NONE);
  622. *num_added += 1;
  623. return;
  624. free_pages_out:
  625. for (i = 0; i < nr_pages; i++) {
  626. WARN_ON(pages[i]->mapping);
  627. put_page(pages[i]);
  628. }
  629. kfree(pages);
  630. }
  631. static void free_async_extent_pages(struct async_extent *async_extent)
  632. {
  633. int i;
  634. if (!async_extent->pages)
  635. return;
  636. for (i = 0; i < async_extent->nr_pages; i++) {
  637. WARN_ON(async_extent->pages[i]->mapping);
  638. put_page(async_extent->pages[i]);
  639. }
  640. kfree(async_extent->pages);
  641. async_extent->nr_pages = 0;
  642. async_extent->pages = NULL;
  643. }
  644. /*
  645. * phase two of compressed writeback. This is the ordered portion
  646. * of the code, which only gets called in the order the work was
  647. * queued. We walk all the async extents created by compress_file_range
  648. * and send them down to the disk.
  649. */
  650. static noinline void submit_compressed_extents(struct inode *inode,
  651. struct async_cow *async_cow)
  652. {
  653. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  654. struct async_extent *async_extent;
  655. u64 alloc_hint = 0;
  656. struct btrfs_key ins;
  657. struct extent_map *em;
  658. struct btrfs_root *root = BTRFS_I(inode)->root;
  659. struct extent_io_tree *io_tree;
  660. int ret = 0;
  661. again:
  662. while (!list_empty(&async_cow->extents)) {
  663. async_extent = list_entry(async_cow->extents.next,
  664. struct async_extent, list);
  665. list_del(&async_extent->list);
  666. io_tree = &BTRFS_I(inode)->io_tree;
  667. retry:
  668. /* did the compression code fall back to uncompressed IO? */
  669. if (!async_extent->pages) {
  670. int page_started = 0;
  671. unsigned long nr_written = 0;
  672. lock_extent(io_tree, async_extent->start,
  673. async_extent->start +
  674. async_extent->ram_size - 1);
  675. /* allocate blocks */
  676. ret = cow_file_range(inode, async_cow->locked_page,
  677. async_extent->start,
  678. async_extent->start +
  679. async_extent->ram_size - 1,
  680. async_extent->start +
  681. async_extent->ram_size - 1,
  682. &page_started, &nr_written, 0,
  683. NULL);
  684. /* JDM XXX */
  685. /*
  686. * if page_started, cow_file_range inserted an
  687. * inline extent and took care of all the unlocking
  688. * and IO for us. Otherwise, we need to submit
  689. * all those pages down to the drive.
  690. */
  691. if (!page_started && !ret)
  692. extent_write_locked_range(io_tree,
  693. inode, async_extent->start,
  694. async_extent->start +
  695. async_extent->ram_size - 1,
  696. btrfs_get_extent,
  697. WB_SYNC_ALL);
  698. else if (ret)
  699. unlock_page(async_cow->locked_page);
  700. kfree(async_extent);
  701. cond_resched();
  702. continue;
  703. }
  704. lock_extent(io_tree, async_extent->start,
  705. async_extent->start + async_extent->ram_size - 1);
  706. ret = btrfs_reserve_extent(root, async_extent->ram_size,
  707. async_extent->compressed_size,
  708. async_extent->compressed_size,
  709. 0, alloc_hint, &ins, 1, 1);
  710. if (ret) {
  711. free_async_extent_pages(async_extent);
  712. if (ret == -ENOSPC) {
  713. unlock_extent(io_tree, async_extent->start,
  714. async_extent->start +
  715. async_extent->ram_size - 1);
  716. /*
  717. * we need to redirty the pages if we decide to
  718. * fallback to uncompressed IO, otherwise we
  719. * will not submit these pages down to lower
  720. * layers.
  721. */
  722. extent_range_redirty_for_io(inode,
  723. async_extent->start,
  724. async_extent->start +
  725. async_extent->ram_size - 1);
  726. goto retry;
  727. }
  728. goto out_free;
  729. }
  730. /*
  731. * here we're doing allocation and writeback of the
  732. * compressed pages
  733. */
  734. em = create_io_em(inode, async_extent->start,
  735. async_extent->ram_size, /* len */
  736. async_extent->start, /* orig_start */
  737. ins.objectid, /* block_start */
  738. ins.offset, /* block_len */
  739. ins.offset, /* orig_block_len */
  740. async_extent->ram_size, /* ram_bytes */
  741. async_extent->compress_type,
  742. BTRFS_ORDERED_COMPRESSED);
  743. if (IS_ERR(em))
  744. /* ret value is not necessary due to void function */
  745. goto out_free_reserve;
  746. free_extent_map(em);
  747. ret = btrfs_add_ordered_extent_compress(inode,
  748. async_extent->start,
  749. ins.objectid,
  750. async_extent->ram_size,
  751. ins.offset,
  752. BTRFS_ORDERED_COMPRESSED,
  753. async_extent->compress_type);
  754. if (ret) {
  755. btrfs_drop_extent_cache(BTRFS_I(inode),
  756. async_extent->start,
  757. async_extent->start +
  758. async_extent->ram_size - 1, 0);
  759. goto out_free_reserve;
  760. }
  761. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  762. /*
  763. * clear dirty, set writeback and unlock the pages.
  764. */
  765. extent_clear_unlock_delalloc(inode, async_extent->start,
  766. async_extent->start +
  767. async_extent->ram_size - 1,
  768. async_extent->start +
  769. async_extent->ram_size - 1,
  770. NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
  771. PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
  772. PAGE_SET_WRITEBACK);
  773. if (btrfs_submit_compressed_write(inode,
  774. async_extent->start,
  775. async_extent->ram_size,
  776. ins.objectid,
  777. ins.offset, async_extent->pages,
  778. async_extent->nr_pages,
  779. async_cow->write_flags)) {
  780. struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
  781. struct page *p = async_extent->pages[0];
  782. const u64 start = async_extent->start;
  783. const u64 end = start + async_extent->ram_size - 1;
  784. p->mapping = inode->i_mapping;
  785. tree->ops->writepage_end_io_hook(p, start, end,
  786. NULL, 0);
  787. p->mapping = NULL;
  788. extent_clear_unlock_delalloc(inode, start, end, end,
  789. NULL, 0,
  790. PAGE_END_WRITEBACK |
  791. PAGE_SET_ERROR);
  792. free_async_extent_pages(async_extent);
  793. }
  794. alloc_hint = ins.objectid + ins.offset;
  795. kfree(async_extent);
  796. cond_resched();
  797. }
  798. return;
  799. out_free_reserve:
  800. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  801. btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
  802. out_free:
  803. extent_clear_unlock_delalloc(inode, async_extent->start,
  804. async_extent->start +
  805. async_extent->ram_size - 1,
  806. async_extent->start +
  807. async_extent->ram_size - 1,
  808. NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
  809. EXTENT_DELALLOC_NEW |
  810. EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
  811. PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
  812. PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
  813. PAGE_SET_ERROR);
  814. free_async_extent_pages(async_extent);
  815. kfree(async_extent);
  816. goto again;
  817. }
  818. static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
  819. u64 num_bytes)
  820. {
  821. struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
  822. struct extent_map *em;
  823. u64 alloc_hint = 0;
  824. read_lock(&em_tree->lock);
  825. em = search_extent_mapping(em_tree, start, num_bytes);
  826. if (em) {
  827. /*
  828. * if block start isn't an actual block number then find the
  829. * first block in this inode and use that as a hint. If that
  830. * block is also bogus then just don't worry about it.
  831. */
  832. if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
  833. free_extent_map(em);
  834. em = search_extent_mapping(em_tree, 0, 0);
  835. if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
  836. alloc_hint = em->block_start;
  837. if (em)
  838. free_extent_map(em);
  839. } else {
  840. alloc_hint = em->block_start;
  841. free_extent_map(em);
  842. }
  843. }
  844. read_unlock(&em_tree->lock);
  845. return alloc_hint;
  846. }
  847. /*
  848. * when extent_io.c finds a delayed allocation range in the file,
  849. * the call backs end up in this code. The basic idea is to
  850. * allocate extents on disk for the range, and create ordered data structs
  851. * in ram to track those extents.
  852. *
  853. * locked_page is the page that writepage had locked already. We use
  854. * it to make sure we don't do extra locks or unlocks.
  855. *
  856. * *page_started is set to one if we unlock locked_page and do everything
  857. * required to start IO on it. It may be clean and already done with
  858. * IO when we return.
  859. */
  860. static noinline int cow_file_range(struct inode *inode,
  861. struct page *locked_page,
  862. u64 start, u64 end, u64 delalloc_end,
  863. int *page_started, unsigned long *nr_written,
  864. int unlock, struct btrfs_dedupe_hash *hash)
  865. {
  866. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  867. struct btrfs_root *root = BTRFS_I(inode)->root;
  868. u64 alloc_hint = 0;
  869. u64 num_bytes;
  870. unsigned long ram_size;
  871. u64 disk_num_bytes;
  872. u64 cur_alloc_size = 0;
  873. u64 blocksize = fs_info->sectorsize;
  874. struct btrfs_key ins;
  875. struct extent_map *em;
  876. unsigned clear_bits;
  877. unsigned long page_ops;
  878. bool extent_reserved = false;
  879. int ret = 0;
  880. if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
  881. WARN_ON_ONCE(1);
  882. ret = -EINVAL;
  883. goto out_unlock;
  884. }
  885. num_bytes = ALIGN(end - start + 1, blocksize);
  886. num_bytes = max(blocksize, num_bytes);
  887. disk_num_bytes = num_bytes;
  888. inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
  889. if (start == 0) {
  890. /* lets try to make an inline extent */
  891. ret = cow_file_range_inline(root, inode, start, end, 0,
  892. BTRFS_COMPRESS_NONE, NULL);
  893. if (ret == 0) {
  894. /*
  895. * We use DO_ACCOUNTING here because we need the
  896. * delalloc_release_metadata to be run _after_ we drop
  897. * our outstanding extent for clearing delalloc for this
  898. * range.
  899. */
  900. extent_clear_unlock_delalloc(inode, start, end,
  901. delalloc_end, NULL,
  902. EXTENT_LOCKED | EXTENT_DELALLOC |
  903. EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
  904. EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
  905. PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
  906. PAGE_END_WRITEBACK);
  907. *nr_written = *nr_written +
  908. (end - start + PAGE_SIZE) / PAGE_SIZE;
  909. *page_started = 1;
  910. goto out;
  911. } else if (ret < 0) {
  912. goto out_unlock;
  913. }
  914. }
  915. BUG_ON(disk_num_bytes >
  916. btrfs_super_total_bytes(fs_info->super_copy));
  917. alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
  918. btrfs_drop_extent_cache(BTRFS_I(inode), start,
  919. start + num_bytes - 1, 0);
  920. while (disk_num_bytes > 0) {
  921. cur_alloc_size = disk_num_bytes;
  922. ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
  923. fs_info->sectorsize, 0, alloc_hint,
  924. &ins, 1, 1);
  925. if (ret < 0)
  926. goto out_unlock;
  927. cur_alloc_size = ins.offset;
  928. extent_reserved = true;
  929. ram_size = ins.offset;
  930. em = create_io_em(inode, start, ins.offset, /* len */
  931. start, /* orig_start */
  932. ins.objectid, /* block_start */
  933. ins.offset, /* block_len */
  934. ins.offset, /* orig_block_len */
  935. ram_size, /* ram_bytes */
  936. BTRFS_COMPRESS_NONE, /* compress_type */
  937. BTRFS_ORDERED_REGULAR /* type */);
  938. if (IS_ERR(em))
  939. goto out_reserve;
  940. free_extent_map(em);
  941. ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
  942. ram_size, cur_alloc_size, 0);
  943. if (ret)
  944. goto out_drop_extent_cache;
  945. if (root->root_key.objectid ==
  946. BTRFS_DATA_RELOC_TREE_OBJECTID) {
  947. ret = btrfs_reloc_clone_csums(inode, start,
  948. cur_alloc_size);
  949. /*
  950. * Only drop cache here, and process as normal.
  951. *
  952. * We must not allow extent_clear_unlock_delalloc()
  953. * at out_unlock label to free meta of this ordered
  954. * extent, as its meta should be freed by
  955. * btrfs_finish_ordered_io().
  956. *
  957. * So we must continue until @start is increased to
  958. * skip current ordered extent.
  959. */
  960. if (ret)
  961. btrfs_drop_extent_cache(BTRFS_I(inode), start,
  962. start + ram_size - 1, 0);
  963. }
  964. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  965. /* we're not doing compressed IO, don't unlock the first
  966. * page (which the caller expects to stay locked), don't
  967. * clear any dirty bits and don't set any writeback bits
  968. *
  969. * Do set the Private2 bit so we know this page was properly
  970. * setup for writepage
  971. */
  972. page_ops = unlock ? PAGE_UNLOCK : 0;
  973. page_ops |= PAGE_SET_PRIVATE2;
  974. extent_clear_unlock_delalloc(inode, start,
  975. start + ram_size - 1,
  976. delalloc_end, locked_page,
  977. EXTENT_LOCKED | EXTENT_DELALLOC,
  978. page_ops);
  979. if (disk_num_bytes < cur_alloc_size)
  980. disk_num_bytes = 0;
  981. else
  982. disk_num_bytes -= cur_alloc_size;
  983. num_bytes -= cur_alloc_size;
  984. alloc_hint = ins.objectid + ins.offset;
  985. start += cur_alloc_size;
  986. extent_reserved = false;
  987. /*
  988. * btrfs_reloc_clone_csums() error, since start is increased
  989. * extent_clear_unlock_delalloc() at out_unlock label won't
  990. * free metadata of current ordered extent, we're OK to exit.
  991. */
  992. if (ret)
  993. goto out_unlock;
  994. }
  995. out:
  996. return ret;
  997. out_drop_extent_cache:
  998. btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
  999. out_reserve:
  1000. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  1001. btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
  1002. out_unlock:
  1003. clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
  1004. EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
  1005. page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
  1006. PAGE_END_WRITEBACK;
  1007. /*
  1008. * If we reserved an extent for our delalloc range (or a subrange) and
  1009. * failed to create the respective ordered extent, then it means that
  1010. * when we reserved the extent we decremented the extent's size from
  1011. * the data space_info's bytes_may_use counter and incremented the
  1012. * space_info's bytes_reserved counter by the same amount. We must make
  1013. * sure extent_clear_unlock_delalloc() does not try to decrement again
  1014. * the data space_info's bytes_may_use counter, therefore we do not pass
  1015. * it the flag EXTENT_CLEAR_DATA_RESV.
  1016. */
  1017. if (extent_reserved) {
  1018. extent_clear_unlock_delalloc(inode, start,
  1019. start + cur_alloc_size,
  1020. start + cur_alloc_size,
  1021. locked_page,
  1022. clear_bits,
  1023. page_ops);
  1024. start += cur_alloc_size;
  1025. if (start >= end)
  1026. goto out;
  1027. }
  1028. extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
  1029. locked_page,
  1030. clear_bits | EXTENT_CLEAR_DATA_RESV,
  1031. page_ops);
  1032. goto out;
  1033. }
  1034. /*
  1035. * work queue call back to started compression on a file and pages
  1036. */
  1037. static noinline void async_cow_start(struct btrfs_work *work)
  1038. {
  1039. struct async_cow *async_cow;
  1040. int num_added = 0;
  1041. async_cow = container_of(work, struct async_cow, work);
  1042. compress_file_range(async_cow->inode, async_cow->locked_page,
  1043. async_cow->start, async_cow->end, async_cow,
  1044. &num_added);
  1045. if (num_added == 0) {
  1046. btrfs_add_delayed_iput(async_cow->inode);
  1047. async_cow->inode = NULL;
  1048. }
  1049. }
  1050. /*
  1051. * work queue call back to submit previously compressed pages
  1052. */
  1053. static noinline void async_cow_submit(struct btrfs_work *work)
  1054. {
  1055. struct btrfs_fs_info *fs_info;
  1056. struct async_cow *async_cow;
  1057. struct btrfs_root *root;
  1058. unsigned long nr_pages;
  1059. async_cow = container_of(work, struct async_cow, work);
  1060. root = async_cow->root;
  1061. fs_info = root->fs_info;
  1062. nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
  1063. PAGE_SHIFT;
  1064. /*
  1065. * atomic_sub_return implies a barrier for waitqueue_active
  1066. */
  1067. if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
  1068. 5 * SZ_1M &&
  1069. waitqueue_active(&fs_info->async_submit_wait))
  1070. wake_up(&fs_info->async_submit_wait);
  1071. if (async_cow->inode)
  1072. submit_compressed_extents(async_cow->inode, async_cow);
  1073. }
  1074. static noinline void async_cow_free(struct btrfs_work *work)
  1075. {
  1076. struct async_cow *async_cow;
  1077. async_cow = container_of(work, struct async_cow, work);
  1078. if (async_cow->inode)
  1079. btrfs_add_delayed_iput(async_cow->inode);
  1080. kfree(async_cow);
  1081. }
  1082. static int cow_file_range_async(struct inode *inode, struct page *locked_page,
  1083. u64 start, u64 end, int *page_started,
  1084. unsigned long *nr_written,
  1085. unsigned int write_flags)
  1086. {
  1087. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  1088. struct async_cow *async_cow;
  1089. struct btrfs_root *root = BTRFS_I(inode)->root;
  1090. unsigned long nr_pages;
  1091. u64 cur_end;
  1092. clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
  1093. 1, 0, NULL);
  1094. while (start < end) {
  1095. async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
  1096. BUG_ON(!async_cow); /* -ENOMEM */
  1097. async_cow->inode = igrab(inode);
  1098. async_cow->root = root;
  1099. async_cow->locked_page = locked_page;
  1100. async_cow->start = start;
  1101. async_cow->write_flags = write_flags;
  1102. if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
  1103. !btrfs_test_opt(fs_info, FORCE_COMPRESS))
  1104. cur_end = end;
  1105. else
  1106. cur_end = min(end, start + SZ_512K - 1);
  1107. async_cow->end = cur_end;
  1108. INIT_LIST_HEAD(&async_cow->extents);
  1109. btrfs_init_work(&async_cow->work,
  1110. btrfs_delalloc_helper,
  1111. async_cow_start, async_cow_submit,
  1112. async_cow_free);
  1113. nr_pages = (cur_end - start + PAGE_SIZE) >>
  1114. PAGE_SHIFT;
  1115. atomic_add(nr_pages, &fs_info->async_delalloc_pages);
  1116. btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
  1117. *nr_written += nr_pages;
  1118. start = cur_end + 1;
  1119. }
  1120. *page_started = 1;
  1121. return 0;
  1122. }
  1123. static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
  1124. u64 bytenr, u64 num_bytes)
  1125. {
  1126. int ret;
  1127. struct btrfs_ordered_sum *sums;
  1128. LIST_HEAD(list);
  1129. ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
  1130. bytenr + num_bytes - 1, &list, 0);
  1131. if (ret == 0 && list_empty(&list))
  1132. return 0;
  1133. while (!list_empty(&list)) {
  1134. sums = list_entry(list.next, struct btrfs_ordered_sum, list);
  1135. list_del(&sums->list);
  1136. kfree(sums);
  1137. }
  1138. return 1;
  1139. }
  1140. /*
  1141. * when nowcow writeback call back. This checks for snapshots or COW copies
  1142. * of the extents that exist in the file, and COWs the file as required.
  1143. *
  1144. * If no cow copies or snapshots exist, we write directly to the existing
  1145. * blocks on disk
  1146. */
  1147. static noinline int run_delalloc_nocow(struct inode *inode,
  1148. struct page *locked_page,
  1149. u64 start, u64 end, int *page_started, int force,
  1150. unsigned long *nr_written)
  1151. {
  1152. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  1153. struct btrfs_root *root = BTRFS_I(inode)->root;
  1154. struct extent_buffer *leaf;
  1155. struct btrfs_path *path;
  1156. struct btrfs_file_extent_item *fi;
  1157. struct btrfs_key found_key;
  1158. struct extent_map *em;
  1159. u64 cow_start;
  1160. u64 cur_offset;
  1161. u64 extent_end;
  1162. u64 extent_offset;
  1163. u64 disk_bytenr;
  1164. u64 num_bytes;
  1165. u64 disk_num_bytes;
  1166. u64 ram_bytes;
  1167. int extent_type;
  1168. int ret, err;
  1169. int type;
  1170. int nocow;
  1171. int check_prev = 1;
  1172. bool nolock;
  1173. u64 ino = btrfs_ino(BTRFS_I(inode));
  1174. path = btrfs_alloc_path();
  1175. if (!path) {
  1176. extent_clear_unlock_delalloc(inode, start, end, end,
  1177. locked_page,
  1178. EXTENT_LOCKED | EXTENT_DELALLOC |
  1179. EXTENT_DO_ACCOUNTING |
  1180. EXTENT_DEFRAG, PAGE_UNLOCK |
  1181. PAGE_CLEAR_DIRTY |
  1182. PAGE_SET_WRITEBACK |
  1183. PAGE_END_WRITEBACK);
  1184. return -ENOMEM;
  1185. }
  1186. nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
  1187. cow_start = (u64)-1;
  1188. cur_offset = start;
  1189. while (1) {
  1190. ret = btrfs_lookup_file_extent(NULL, root, path, ino,
  1191. cur_offset, 0);
  1192. if (ret < 0)
  1193. goto error;
  1194. if (ret > 0 && path->slots[0] > 0 && check_prev) {
  1195. leaf = path->nodes[0];
  1196. btrfs_item_key_to_cpu(leaf, &found_key,
  1197. path->slots[0] - 1);
  1198. if (found_key.objectid == ino &&
  1199. found_key.type == BTRFS_EXTENT_DATA_KEY)
  1200. path->slots[0]--;
  1201. }
  1202. check_prev = 0;
  1203. next_slot:
  1204. leaf = path->nodes[0];
  1205. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  1206. ret = btrfs_next_leaf(root, path);
  1207. if (ret < 0)
  1208. goto error;
  1209. if (ret > 0)
  1210. break;
  1211. leaf = path->nodes[0];
  1212. }
  1213. nocow = 0;
  1214. disk_bytenr = 0;
  1215. num_bytes = 0;
  1216. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  1217. if (found_key.objectid > ino)
  1218. break;
  1219. if (WARN_ON_ONCE(found_key.objectid < ino) ||
  1220. found_key.type < BTRFS_EXTENT_DATA_KEY) {
  1221. path->slots[0]++;
  1222. goto next_slot;
  1223. }
  1224. if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
  1225. found_key.offset > end)
  1226. break;
  1227. if (found_key.offset > cur_offset) {
  1228. extent_end = found_key.offset;
  1229. extent_type = 0;
  1230. goto out_check;
  1231. }
  1232. fi = btrfs_item_ptr(leaf, path->slots[0],
  1233. struct btrfs_file_extent_item);
  1234. extent_type = btrfs_file_extent_type(leaf, fi);
  1235. ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
  1236. if (extent_type == BTRFS_FILE_EXTENT_REG ||
  1237. extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  1238. disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  1239. extent_offset = btrfs_file_extent_offset(leaf, fi);
  1240. extent_end = found_key.offset +
  1241. btrfs_file_extent_num_bytes(leaf, fi);
  1242. disk_num_bytes =
  1243. btrfs_file_extent_disk_num_bytes(leaf, fi);
  1244. if (extent_end <= start) {
  1245. path->slots[0]++;
  1246. goto next_slot;
  1247. }
  1248. if (disk_bytenr == 0)
  1249. goto out_check;
  1250. if (btrfs_file_extent_compression(leaf, fi) ||
  1251. btrfs_file_extent_encryption(leaf, fi) ||
  1252. btrfs_file_extent_other_encoding(leaf, fi))
  1253. goto out_check;
  1254. if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
  1255. goto out_check;
  1256. if (btrfs_extent_readonly(fs_info, disk_bytenr))
  1257. goto out_check;
  1258. if (btrfs_cross_ref_exist(root, ino,
  1259. found_key.offset -
  1260. extent_offset, disk_bytenr))
  1261. goto out_check;
  1262. disk_bytenr += extent_offset;
  1263. disk_bytenr += cur_offset - found_key.offset;
  1264. num_bytes = min(end + 1, extent_end) - cur_offset;
  1265. /*
  1266. * if there are pending snapshots for this root,
  1267. * we fall into common COW way.
  1268. */
  1269. if (!nolock) {
  1270. err = btrfs_start_write_no_snapshotting(root);
  1271. if (!err)
  1272. goto out_check;
  1273. }
  1274. /*
  1275. * force cow if csum exists in the range.
  1276. * this ensure that csum for a given extent are
  1277. * either valid or do not exist.
  1278. */
  1279. if (csum_exist_in_range(fs_info, disk_bytenr,
  1280. num_bytes)) {
  1281. if (!nolock)
  1282. btrfs_end_write_no_snapshotting(root);
  1283. goto out_check;
  1284. }
  1285. if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
  1286. if (!nolock)
  1287. btrfs_end_write_no_snapshotting(root);
  1288. goto out_check;
  1289. }
  1290. nocow = 1;
  1291. } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  1292. extent_end = found_key.offset +
  1293. btrfs_file_extent_inline_len(leaf,
  1294. path->slots[0], fi);
  1295. extent_end = ALIGN(extent_end,
  1296. fs_info->sectorsize);
  1297. } else {
  1298. BUG_ON(1);
  1299. }
  1300. out_check:
  1301. if (extent_end <= start) {
  1302. path->slots[0]++;
  1303. if (!nolock && nocow)
  1304. btrfs_end_write_no_snapshotting(root);
  1305. if (nocow)
  1306. btrfs_dec_nocow_writers(fs_info, disk_bytenr);
  1307. goto next_slot;
  1308. }
  1309. if (!nocow) {
  1310. if (cow_start == (u64)-1)
  1311. cow_start = cur_offset;
  1312. cur_offset = extent_end;
  1313. if (cur_offset > end)
  1314. break;
  1315. path->slots[0]++;
  1316. goto next_slot;
  1317. }
  1318. btrfs_release_path(path);
  1319. if (cow_start != (u64)-1) {
  1320. ret = cow_file_range(inode, locked_page,
  1321. cow_start, found_key.offset - 1,
  1322. end, page_started, nr_written, 1,
  1323. NULL);
  1324. if (ret) {
  1325. if (!nolock && nocow)
  1326. btrfs_end_write_no_snapshotting(root);
  1327. if (nocow)
  1328. btrfs_dec_nocow_writers(fs_info,
  1329. disk_bytenr);
  1330. goto error;
  1331. }
  1332. cow_start = (u64)-1;
  1333. }
  1334. if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  1335. u64 orig_start = found_key.offset - extent_offset;
  1336. em = create_io_em(inode, cur_offset, num_bytes,
  1337. orig_start,
  1338. disk_bytenr, /* block_start */
  1339. num_bytes, /* block_len */
  1340. disk_num_bytes, /* orig_block_len */
  1341. ram_bytes, BTRFS_COMPRESS_NONE,
  1342. BTRFS_ORDERED_PREALLOC);
  1343. if (IS_ERR(em)) {
  1344. if (!nolock && nocow)
  1345. btrfs_end_write_no_snapshotting(root);
  1346. if (nocow)
  1347. btrfs_dec_nocow_writers(fs_info,
  1348. disk_bytenr);
  1349. ret = PTR_ERR(em);
  1350. goto error;
  1351. }
  1352. free_extent_map(em);
  1353. }
  1354. if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  1355. type = BTRFS_ORDERED_PREALLOC;
  1356. } else {
  1357. type = BTRFS_ORDERED_NOCOW;
  1358. }
  1359. ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
  1360. num_bytes, num_bytes, type);
  1361. if (nocow)
  1362. btrfs_dec_nocow_writers(fs_info, disk_bytenr);
  1363. BUG_ON(ret); /* -ENOMEM */
  1364. if (root->root_key.objectid ==
  1365. BTRFS_DATA_RELOC_TREE_OBJECTID)
  1366. /*
  1367. * Error handled later, as we must prevent
  1368. * extent_clear_unlock_delalloc() in error handler
  1369. * from freeing metadata of created ordered extent.
  1370. */
  1371. ret = btrfs_reloc_clone_csums(inode, cur_offset,
  1372. num_bytes);
  1373. extent_clear_unlock_delalloc(inode, cur_offset,
  1374. cur_offset + num_bytes - 1, end,
  1375. locked_page, EXTENT_LOCKED |
  1376. EXTENT_DELALLOC |
  1377. EXTENT_CLEAR_DATA_RESV,
  1378. PAGE_UNLOCK | PAGE_SET_PRIVATE2);
  1379. if (!nolock && nocow)
  1380. btrfs_end_write_no_snapshotting(root);
  1381. cur_offset = extent_end;
  1382. /*
  1383. * btrfs_reloc_clone_csums() error, now we're OK to call error
  1384. * handler, as metadata for created ordered extent will only
  1385. * be freed by btrfs_finish_ordered_io().
  1386. */
  1387. if (ret)
  1388. goto error;
  1389. if (cur_offset > end)
  1390. break;
  1391. }
  1392. btrfs_release_path(path);
  1393. if (cur_offset <= end && cow_start == (u64)-1) {
  1394. cow_start = cur_offset;
  1395. cur_offset = end;
  1396. }
  1397. if (cow_start != (u64)-1) {
  1398. ret = cow_file_range(inode, locked_page, cow_start, end, end,
  1399. page_started, nr_written, 1, NULL);
  1400. if (ret)
  1401. goto error;
  1402. }
  1403. error:
  1404. if (ret && cur_offset < end)
  1405. extent_clear_unlock_delalloc(inode, cur_offset, end, end,
  1406. locked_page, EXTENT_LOCKED |
  1407. EXTENT_DELALLOC | EXTENT_DEFRAG |
  1408. EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
  1409. PAGE_CLEAR_DIRTY |
  1410. PAGE_SET_WRITEBACK |
  1411. PAGE_END_WRITEBACK);
  1412. btrfs_free_path(path);
  1413. return ret;
  1414. }
  1415. static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
  1416. {
  1417. if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
  1418. !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
  1419. return 0;
  1420. /*
  1421. * @defrag_bytes is a hint value, no spinlock held here,
  1422. * if is not zero, it means the file is defragging.
  1423. * Force cow if given extent needs to be defragged.
  1424. */
  1425. if (BTRFS_I(inode)->defrag_bytes &&
  1426. test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
  1427. EXTENT_DEFRAG, 0, NULL))
  1428. return 1;
  1429. return 0;
  1430. }
  1431. /*
  1432. * extent_io.c call back to do delayed allocation processing
  1433. */
  1434. static int run_delalloc_range(void *private_data, struct page *locked_page,
  1435. u64 start, u64 end, int *page_started,
  1436. unsigned long *nr_written,
  1437. struct writeback_control *wbc)
  1438. {
  1439. struct inode *inode = private_data;
  1440. int ret;
  1441. int force_cow = need_force_cow(inode, start, end);
  1442. unsigned int write_flags = wbc_to_write_flags(wbc);
  1443. if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
  1444. ret = run_delalloc_nocow(inode, locked_page, start, end,
  1445. page_started, 1, nr_written);
  1446. } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
  1447. ret = run_delalloc_nocow(inode, locked_page, start, end,
  1448. page_started, 0, nr_written);
  1449. } else if (!inode_need_compress(inode, start, end)) {
  1450. ret = cow_file_range(inode, locked_page, start, end, end,
  1451. page_started, nr_written, 1, NULL);
  1452. } else {
  1453. set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
  1454. &BTRFS_I(inode)->runtime_flags);
  1455. ret = cow_file_range_async(inode, locked_page, start, end,
  1456. page_started, nr_written,
  1457. write_flags);
  1458. }
  1459. if (ret)
  1460. btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
  1461. return ret;
  1462. }
  1463. static void btrfs_split_extent_hook(void *private_data,
  1464. struct extent_state *orig, u64 split)
  1465. {
  1466. struct inode *inode = private_data;
  1467. u64 size;
  1468. /* not delalloc, ignore it */
  1469. if (!(orig->state & EXTENT_DELALLOC))
  1470. return;
  1471. size = orig->end - orig->start + 1;
  1472. if (size > BTRFS_MAX_EXTENT_SIZE) {
  1473. u32 num_extents;
  1474. u64 new_size;
  1475. /*
  1476. * See the explanation in btrfs_merge_extent_hook, the same
  1477. * applies here, just in reverse.
  1478. */
  1479. new_size = orig->end - split + 1;
  1480. num_extents = count_max_extents(new_size);
  1481. new_size = split - orig->start;
  1482. num_extents += count_max_extents(new_size);
  1483. if (count_max_extents(size) >= num_extents)
  1484. return;
  1485. }
  1486. spin_lock(&BTRFS_I(inode)->lock);
  1487. btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
  1488. spin_unlock(&BTRFS_I(inode)->lock);
  1489. }
  1490. /*
  1491. * extent_io.c merge_extent_hook, used to track merged delayed allocation
  1492. * extents so we can keep track of new extents that are just merged onto old
  1493. * extents, such as when we are doing sequential writes, so we can properly
  1494. * account for the metadata space we'll need.
  1495. */
  1496. static void btrfs_merge_extent_hook(void *private_data,
  1497. struct extent_state *new,
  1498. struct extent_state *other)
  1499. {
  1500. struct inode *inode = private_data;
  1501. u64 new_size, old_size;
  1502. u32 num_extents;
  1503. /* not delalloc, ignore it */
  1504. if (!(other->state & EXTENT_DELALLOC))
  1505. return;
  1506. if (new->start > other->start)
  1507. new_size = new->end - other->start + 1;
  1508. else
  1509. new_size = other->end - new->start + 1;
  1510. /* we're not bigger than the max, unreserve the space and go */
  1511. if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
  1512. spin_lock(&BTRFS_I(inode)->lock);
  1513. btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
  1514. spin_unlock(&BTRFS_I(inode)->lock);
  1515. return;
  1516. }
  1517. /*
  1518. * We have to add up either side to figure out how many extents were
  1519. * accounted for before we merged into one big extent. If the number of
  1520. * extents we accounted for is <= the amount we need for the new range
  1521. * then we can return, otherwise drop. Think of it like this
  1522. *
  1523. * [ 4k][MAX_SIZE]
  1524. *
  1525. * So we've grown the extent by a MAX_SIZE extent, this would mean we
  1526. * need 2 outstanding extents, on one side we have 1 and the other side
  1527. * we have 1 so they are == and we can return. But in this case
  1528. *
  1529. * [MAX_SIZE+4k][MAX_SIZE+4k]
  1530. *
  1531. * Each range on their own accounts for 2 extents, but merged together
  1532. * they are only 3 extents worth of accounting, so we need to drop in
  1533. * this case.
  1534. */
  1535. old_size = other->end - other->start + 1;
  1536. num_extents = count_max_extents(old_size);
  1537. old_size = new->end - new->start + 1;
  1538. num_extents += count_max_extents(old_size);
  1539. if (count_max_extents(new_size) >= num_extents)
  1540. return;
  1541. spin_lock(&BTRFS_I(inode)->lock);
  1542. btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
  1543. spin_unlock(&BTRFS_I(inode)->lock);
  1544. }
  1545. static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
  1546. struct inode *inode)
  1547. {
  1548. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  1549. spin_lock(&root->delalloc_lock);
  1550. if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
  1551. list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
  1552. &root->delalloc_inodes);
  1553. set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
  1554. &BTRFS_I(inode)->runtime_flags);
  1555. root->nr_delalloc_inodes++;
  1556. if (root->nr_delalloc_inodes == 1) {
  1557. spin_lock(&fs_info->delalloc_root_lock);
  1558. BUG_ON(!list_empty(&root->delalloc_root));
  1559. list_add_tail(&root->delalloc_root,
  1560. &fs_info->delalloc_roots);
  1561. spin_unlock(&fs_info->delalloc_root_lock);
  1562. }
  1563. }
  1564. spin_unlock(&root->delalloc_lock);
  1565. }
  1566. static void btrfs_del_delalloc_inode(struct btrfs_root *root,
  1567. struct btrfs_inode *inode)
  1568. {
  1569. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  1570. spin_lock(&root->delalloc_lock);
  1571. if (!list_empty(&inode->delalloc_inodes)) {
  1572. list_del_init(&inode->delalloc_inodes);
  1573. clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
  1574. &inode->runtime_flags);
  1575. root->nr_delalloc_inodes--;
  1576. if (!root->nr_delalloc_inodes) {
  1577. spin_lock(&fs_info->delalloc_root_lock);
  1578. BUG_ON(list_empty(&root->delalloc_root));
  1579. list_del_init(&root->delalloc_root);
  1580. spin_unlock(&fs_info->delalloc_root_lock);
  1581. }
  1582. }
  1583. spin_unlock(&root->delalloc_lock);
  1584. }
  1585. /*
  1586. * extent_io.c set_bit_hook, used to track delayed allocation
  1587. * bytes in this file, and to maintain the list of inodes that
  1588. * have pending delalloc work to be done.
  1589. */
  1590. static void btrfs_set_bit_hook(void *private_data,
  1591. struct extent_state *state, unsigned *bits)
  1592. {
  1593. struct inode *inode = private_data;
  1594. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  1595. if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
  1596. WARN_ON(1);
  1597. /*
  1598. * set_bit and clear bit hooks normally require _irqsave/restore
  1599. * but in this case, we are only testing for the DELALLOC
  1600. * bit, which is only set or cleared with irqs on
  1601. */
  1602. if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
  1603. struct btrfs_root *root = BTRFS_I(inode)->root;
  1604. u64 len = state->end + 1 - state->start;
  1605. u32 num_extents = count_max_extents(len);
  1606. bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
  1607. spin_lock(&BTRFS_I(inode)->lock);
  1608. btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
  1609. spin_unlock(&BTRFS_I(inode)->lock);
  1610. /* For sanity tests */
  1611. if (btrfs_is_testing(fs_info))
  1612. return;
  1613. percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
  1614. fs_info->delalloc_batch);
  1615. spin_lock(&BTRFS_I(inode)->lock);
  1616. BTRFS_I(inode)->delalloc_bytes += len;
  1617. if (*bits & EXTENT_DEFRAG)
  1618. BTRFS_I(inode)->defrag_bytes += len;
  1619. if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
  1620. &BTRFS_I(inode)->runtime_flags))
  1621. btrfs_add_delalloc_inodes(root, inode);
  1622. spin_unlock(&BTRFS_I(inode)->lock);
  1623. }
  1624. if (!(state->state & EXTENT_DELALLOC_NEW) &&
  1625. (*bits & EXTENT_DELALLOC_NEW)) {
  1626. spin_lock(&BTRFS_I(inode)->lock);
  1627. BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
  1628. state->start;
  1629. spin_unlock(&BTRFS_I(inode)->lock);
  1630. }
  1631. }
  1632. /*
  1633. * extent_io.c clear_bit_hook, see set_bit_hook for why
  1634. */
  1635. static void btrfs_clear_bit_hook(void *private_data,
  1636. struct extent_state *state,
  1637. unsigned *bits)
  1638. {
  1639. struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
  1640. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  1641. u64 len = state->end + 1 - state->start;
  1642. u32 num_extents = count_max_extents(len);
  1643. if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
  1644. spin_lock(&inode->lock);
  1645. inode->defrag_bytes -= len;
  1646. spin_unlock(&inode->lock);
  1647. }
  1648. /*
  1649. * set_bit and clear bit hooks normally require _irqsave/restore
  1650. * but in this case, we are only testing for the DELALLOC
  1651. * bit, which is only set or cleared with irqs on
  1652. */
  1653. if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
  1654. struct btrfs_root *root = inode->root;
  1655. bool do_list = !btrfs_is_free_space_inode(inode);
  1656. spin_lock(&inode->lock);
  1657. btrfs_mod_outstanding_extents(inode, -num_extents);
  1658. spin_unlock(&inode->lock);
  1659. /*
  1660. * We don't reserve metadata space for space cache inodes so we
  1661. * don't need to call dellalloc_release_metadata if there is an
  1662. * error.
  1663. */
  1664. if (*bits & EXTENT_CLEAR_META_RESV &&
  1665. root != fs_info->tree_root)
  1666. btrfs_delalloc_release_metadata(inode, len);
  1667. /* For sanity tests. */
  1668. if (btrfs_is_testing(fs_info))
  1669. return;
  1670. if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
  1671. do_list && !(state->state & EXTENT_NORESERVE) &&
  1672. (*bits & EXTENT_CLEAR_DATA_RESV))
  1673. btrfs_free_reserved_data_space_noquota(
  1674. &inode->vfs_inode,
  1675. state->start, len);
  1676. percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
  1677. fs_info->delalloc_batch);
  1678. spin_lock(&inode->lock);
  1679. inode->delalloc_bytes -= len;
  1680. if (do_list && inode->delalloc_bytes == 0 &&
  1681. test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
  1682. &inode->runtime_flags))
  1683. btrfs_del_delalloc_inode(root, inode);
  1684. spin_unlock(&inode->lock);
  1685. }
  1686. if ((state->state & EXTENT_DELALLOC_NEW) &&
  1687. (*bits & EXTENT_DELALLOC_NEW)) {
  1688. spin_lock(&inode->lock);
  1689. ASSERT(inode->new_delalloc_bytes >= len);
  1690. inode->new_delalloc_bytes -= len;
  1691. spin_unlock(&inode->lock);
  1692. }
  1693. }
  1694. /*
  1695. * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
  1696. * we don't create bios that span stripes or chunks
  1697. *
  1698. * return 1 if page cannot be merged to bio
  1699. * return 0 if page can be merged to bio
  1700. * return error otherwise
  1701. */
  1702. int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
  1703. size_t size, struct bio *bio,
  1704. unsigned long bio_flags)
  1705. {
  1706. struct inode *inode = page->mapping->host;
  1707. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  1708. u64 logical = (u64)bio->bi_iter.bi_sector << 9;
  1709. u64 length = 0;
  1710. u64 map_length;
  1711. int ret;
  1712. if (bio_flags & EXTENT_BIO_COMPRESSED)
  1713. return 0;
  1714. length = bio->bi_iter.bi_size;
  1715. map_length = length;
  1716. ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
  1717. NULL, 0);
  1718. if (ret < 0)
  1719. return ret;
  1720. if (map_length < length + size)
  1721. return 1;
  1722. return 0;
  1723. }
  1724. /*
  1725. * in order to insert checksums into the metadata in large chunks,
  1726. * we wait until bio submission time. All the pages in the bio are
  1727. * checksummed and sums are attached onto the ordered extent record.
  1728. *
  1729. * At IO completion time the cums attached on the ordered extent record
  1730. * are inserted into the btree
  1731. */
  1732. static blk_status_t __btrfs_submit_bio_start(void *private_data, struct bio *bio,
  1733. int mirror_num, unsigned long bio_flags,
  1734. u64 bio_offset)
  1735. {
  1736. struct inode *inode = private_data;
  1737. blk_status_t ret = 0;
  1738. ret = btrfs_csum_one_bio(inode, bio, 0, 0);
  1739. BUG_ON(ret); /* -ENOMEM */
  1740. return 0;
  1741. }
  1742. /*
  1743. * in order to insert checksums into the metadata in large chunks,
  1744. * we wait until bio submission time. All the pages in the bio are
  1745. * checksummed and sums are attached onto the ordered extent record.
  1746. *
  1747. * At IO completion time the cums attached on the ordered extent record
  1748. * are inserted into the btree
  1749. */
  1750. static blk_status_t __btrfs_submit_bio_done(void *private_data, struct bio *bio,
  1751. int mirror_num, unsigned long bio_flags,
  1752. u64 bio_offset)
  1753. {
  1754. struct inode *inode = private_data;
  1755. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  1756. blk_status_t ret;
  1757. ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
  1758. if (ret) {
  1759. bio->bi_status = ret;
  1760. bio_endio(bio);
  1761. }
  1762. return ret;
  1763. }
  1764. /*
  1765. * extent_io.c submission hook. This does the right thing for csum calculation
  1766. * on write, or reading the csums from the tree before a read.
  1767. *
  1768. * Rules about async/sync submit,
  1769. * a) read: sync submit
  1770. *
  1771. * b) write without checksum: sync submit
  1772. *
  1773. * c) write with checksum:
  1774. * c-1) if bio is issued by fsync: sync submit
  1775. * (sync_writers != 0)
  1776. *
  1777. * c-2) if root is reloc root: sync submit
  1778. * (only in case of buffered IO)
  1779. *
  1780. * c-3) otherwise: async submit
  1781. */
  1782. static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
  1783. int mirror_num, unsigned long bio_flags,
  1784. u64 bio_offset)
  1785. {
  1786. struct inode *inode = private_data;
  1787. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  1788. struct btrfs_root *root = BTRFS_I(inode)->root;
  1789. enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
  1790. blk_status_t ret = 0;
  1791. int skip_sum;
  1792. int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
  1793. skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
  1794. if (btrfs_is_free_space_inode(BTRFS_I(inode)))
  1795. metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
  1796. if (bio_op(bio) != REQ_OP_WRITE) {
  1797. ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
  1798. if (ret)
  1799. goto out;
  1800. if (bio_flags & EXTENT_BIO_COMPRESSED) {
  1801. ret = btrfs_submit_compressed_read(inode, bio,
  1802. mirror_num,
  1803. bio_flags);
  1804. goto out;
  1805. } else if (!skip_sum) {
  1806. ret = btrfs_lookup_bio_sums(inode, bio, NULL);
  1807. if (ret)
  1808. goto out;
  1809. }
  1810. goto mapit;
  1811. } else if (async && !skip_sum) {
  1812. /* csum items have already been cloned */
  1813. if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
  1814. goto mapit;
  1815. /* we're doing a write, do the async checksumming */
  1816. ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
  1817. bio_offset, inode,
  1818. __btrfs_submit_bio_start,
  1819. __btrfs_submit_bio_done);
  1820. goto out;
  1821. } else if (!skip_sum) {
  1822. ret = btrfs_csum_one_bio(inode, bio, 0, 0);
  1823. if (ret)
  1824. goto out;
  1825. }
  1826. mapit:
  1827. ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
  1828. out:
  1829. if (ret) {
  1830. bio->bi_status = ret;
  1831. bio_endio(bio);
  1832. }
  1833. return ret;
  1834. }
  1835. /*
  1836. * given a list of ordered sums record them in the inode. This happens
  1837. * at IO completion time based on sums calculated at bio submission time.
  1838. */
  1839. static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
  1840. struct inode *inode, struct list_head *list)
  1841. {
  1842. struct btrfs_ordered_sum *sum;
  1843. list_for_each_entry(sum, list, list) {
  1844. trans->adding_csums = 1;
  1845. btrfs_csum_file_blocks(trans,
  1846. BTRFS_I(inode)->root->fs_info->csum_root, sum);
  1847. trans->adding_csums = 0;
  1848. }
  1849. return 0;
  1850. }
  1851. int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
  1852. unsigned int extra_bits,
  1853. struct extent_state **cached_state, int dedupe)
  1854. {
  1855. WARN_ON((end & (PAGE_SIZE - 1)) == 0);
  1856. return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
  1857. extra_bits, cached_state);
  1858. }
  1859. /* see btrfs_writepage_start_hook for details on why this is required */
  1860. struct btrfs_writepage_fixup {
  1861. struct page *page;
  1862. struct btrfs_work work;
  1863. };
  1864. static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
  1865. {
  1866. struct btrfs_writepage_fixup *fixup;
  1867. struct btrfs_ordered_extent *ordered;
  1868. struct extent_state *cached_state = NULL;
  1869. struct extent_changeset *data_reserved = NULL;
  1870. struct page *page;
  1871. struct inode *inode;
  1872. u64 page_start;
  1873. u64 page_end;
  1874. int ret;
  1875. fixup = container_of(work, struct btrfs_writepage_fixup, work);
  1876. page = fixup->page;
  1877. again:
  1878. lock_page(page);
  1879. if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
  1880. ClearPageChecked(page);
  1881. goto out_page;
  1882. }
  1883. inode = page->mapping->host;
  1884. page_start = page_offset(page);
  1885. page_end = page_offset(page) + PAGE_SIZE - 1;
  1886. lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
  1887. &cached_state);
  1888. /* already ordered? We're done */
  1889. if (PagePrivate2(page))
  1890. goto out;
  1891. ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
  1892. PAGE_SIZE);
  1893. if (ordered) {
  1894. unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
  1895. page_end, &cached_state, GFP_NOFS);
  1896. unlock_page(page);
  1897. btrfs_start_ordered_extent(inode, ordered, 1);
  1898. btrfs_put_ordered_extent(ordered);
  1899. goto again;
  1900. }
  1901. ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
  1902. PAGE_SIZE);
  1903. if (ret) {
  1904. mapping_set_error(page->mapping, ret);
  1905. end_extent_writepage(page, ret, page_start, page_end);
  1906. ClearPageChecked(page);
  1907. goto out;
  1908. }
  1909. btrfs_set_extent_delalloc(inode, page_start, page_end, 0, &cached_state,
  1910. 0);
  1911. ClearPageChecked(page);
  1912. set_page_dirty(page);
  1913. btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
  1914. out:
  1915. unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
  1916. &cached_state, GFP_NOFS);
  1917. out_page:
  1918. unlock_page(page);
  1919. put_page(page);
  1920. kfree(fixup);
  1921. extent_changeset_free(data_reserved);
  1922. }
  1923. /*
  1924. * There are a few paths in the higher layers of the kernel that directly
  1925. * set the page dirty bit without asking the filesystem if it is a
  1926. * good idea. This causes problems because we want to make sure COW
  1927. * properly happens and the data=ordered rules are followed.
  1928. *
  1929. * In our case any range that doesn't have the ORDERED bit set
  1930. * hasn't been properly setup for IO. We kick off an async process
  1931. * to fix it up. The async helper will wait for ordered extents, set
  1932. * the delalloc bit and make it safe to write the page.
  1933. */
  1934. static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
  1935. {
  1936. struct inode *inode = page->mapping->host;
  1937. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  1938. struct btrfs_writepage_fixup *fixup;
  1939. /* this page is properly in the ordered list */
  1940. if (TestClearPagePrivate2(page))
  1941. return 0;
  1942. if (PageChecked(page))
  1943. return -EAGAIN;
  1944. fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
  1945. if (!fixup)
  1946. return -EAGAIN;
  1947. SetPageChecked(page);
  1948. get_page(page);
  1949. btrfs_init_work(&fixup->work, btrfs_fixup_helper,
  1950. btrfs_writepage_fixup_worker, NULL, NULL);
  1951. fixup->page = page;
  1952. btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
  1953. return -EBUSY;
  1954. }
  1955. static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
  1956. struct inode *inode, u64 file_pos,
  1957. u64 disk_bytenr, u64 disk_num_bytes,
  1958. u64 num_bytes, u64 ram_bytes,
  1959. u8 compression, u8 encryption,
  1960. u16 other_encoding, int extent_type)
  1961. {
  1962. struct btrfs_root *root = BTRFS_I(inode)->root;
  1963. struct btrfs_file_extent_item *fi;
  1964. struct btrfs_path *path;
  1965. struct extent_buffer *leaf;
  1966. struct btrfs_key ins;
  1967. u64 qg_released;
  1968. int extent_inserted = 0;
  1969. int ret;
  1970. path = btrfs_alloc_path();
  1971. if (!path)
  1972. return -ENOMEM;
  1973. /*
  1974. * we may be replacing one extent in the tree with another.
  1975. * The new extent is pinned in the extent map, and we don't want
  1976. * to drop it from the cache until it is completely in the btree.
  1977. *
  1978. * So, tell btrfs_drop_extents to leave this extent in the cache.
  1979. * the caller is expected to unpin it and allow it to be merged
  1980. * with the others.
  1981. */
  1982. ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
  1983. file_pos + num_bytes, NULL, 0,
  1984. 1, sizeof(*fi), &extent_inserted);
  1985. if (ret)
  1986. goto out;
  1987. if (!extent_inserted) {
  1988. ins.objectid = btrfs_ino(BTRFS_I(inode));
  1989. ins.offset = file_pos;
  1990. ins.type = BTRFS_EXTENT_DATA_KEY;
  1991. path->leave_spinning = 1;
  1992. ret = btrfs_insert_empty_item(trans, root, path, &ins,
  1993. sizeof(*fi));
  1994. if (ret)
  1995. goto out;
  1996. }
  1997. leaf = path->nodes[0];
  1998. fi = btrfs_item_ptr(leaf, path->slots[0],
  1999. struct btrfs_file_extent_item);
  2000. btrfs_set_file_extent_generation(leaf, fi, trans->transid);
  2001. btrfs_set_file_extent_type(leaf, fi, extent_type);
  2002. btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
  2003. btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
  2004. btrfs_set_file_extent_offset(leaf, fi, 0);
  2005. btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
  2006. btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
  2007. btrfs_set_file_extent_compression(leaf, fi, compression);
  2008. btrfs_set_file_extent_encryption(leaf, fi, encryption);
  2009. btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
  2010. btrfs_mark_buffer_dirty(leaf);
  2011. btrfs_release_path(path);
  2012. inode_add_bytes(inode, num_bytes);
  2013. ins.objectid = disk_bytenr;
  2014. ins.offset = disk_num_bytes;
  2015. ins.type = BTRFS_EXTENT_ITEM_KEY;
  2016. /*
  2017. * Release the reserved range from inode dirty range map, as it is
  2018. * already moved into delayed_ref_head
  2019. */
  2020. ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
  2021. if (ret < 0)
  2022. goto out;
  2023. qg_released = ret;
  2024. ret = btrfs_alloc_reserved_file_extent(trans, root,
  2025. btrfs_ino(BTRFS_I(inode)),
  2026. file_pos, qg_released, &ins);
  2027. out:
  2028. btrfs_free_path(path);
  2029. return ret;
  2030. }
  2031. /* snapshot-aware defrag */
  2032. struct sa_defrag_extent_backref {
  2033. struct rb_node node;
  2034. struct old_sa_defrag_extent *old;
  2035. u64 root_id;
  2036. u64 inum;
  2037. u64 file_pos;
  2038. u64 extent_offset;
  2039. u64 num_bytes;
  2040. u64 generation;
  2041. };
  2042. struct old_sa_defrag_extent {
  2043. struct list_head list;
  2044. struct new_sa_defrag_extent *new;
  2045. u64 extent_offset;
  2046. u64 bytenr;
  2047. u64 offset;
  2048. u64 len;
  2049. int count;
  2050. };
  2051. struct new_sa_defrag_extent {
  2052. struct rb_root root;
  2053. struct list_head head;
  2054. struct btrfs_path *path;
  2055. struct inode *inode;
  2056. u64 file_pos;
  2057. u64 len;
  2058. u64 bytenr;
  2059. u64 disk_len;
  2060. u8 compress_type;
  2061. };
  2062. static int backref_comp(struct sa_defrag_extent_backref *b1,
  2063. struct sa_defrag_extent_backref *b2)
  2064. {
  2065. if (b1->root_id < b2->root_id)
  2066. return -1;
  2067. else if (b1->root_id > b2->root_id)
  2068. return 1;
  2069. if (b1->inum < b2->inum)
  2070. return -1;
  2071. else if (b1->inum > b2->inum)
  2072. return 1;
  2073. if (b1->file_pos < b2->file_pos)
  2074. return -1;
  2075. else if (b1->file_pos > b2->file_pos)
  2076. return 1;
  2077. /*
  2078. * [------------------------------] ===> (a range of space)
  2079. * |<--->| |<---->| =============> (fs/file tree A)
  2080. * |<---------------------------->| ===> (fs/file tree B)
  2081. *
  2082. * A range of space can refer to two file extents in one tree while
  2083. * refer to only one file extent in another tree.
  2084. *
  2085. * So we may process a disk offset more than one time(two extents in A)
  2086. * and locate at the same extent(one extent in B), then insert two same
  2087. * backrefs(both refer to the extent in B).
  2088. */
  2089. return 0;
  2090. }
  2091. static void backref_insert(struct rb_root *root,
  2092. struct sa_defrag_extent_backref *backref)
  2093. {
  2094. struct rb_node **p = &root->rb_node;
  2095. struct rb_node *parent = NULL;
  2096. struct sa_defrag_extent_backref *entry;
  2097. int ret;
  2098. while (*p) {
  2099. parent = *p;
  2100. entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
  2101. ret = backref_comp(backref, entry);
  2102. if (ret < 0)
  2103. p = &(*p)->rb_left;
  2104. else
  2105. p = &(*p)->rb_right;
  2106. }
  2107. rb_link_node(&backref->node, parent, p);
  2108. rb_insert_color(&backref->node, root);
  2109. }
  2110. /*
  2111. * Note the backref might has changed, and in this case we just return 0.
  2112. */
  2113. static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
  2114. void *ctx)
  2115. {
  2116. struct btrfs_file_extent_item *extent;
  2117. struct old_sa_defrag_extent *old = ctx;
  2118. struct new_sa_defrag_extent *new = old->new;
  2119. struct btrfs_path *path = new->path;
  2120. struct btrfs_key key;
  2121. struct btrfs_root *root;
  2122. struct sa_defrag_extent_backref *backref;
  2123. struct extent_buffer *leaf;
  2124. struct inode *inode = new->inode;
  2125. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2126. int slot;
  2127. int ret;
  2128. u64 extent_offset;
  2129. u64 num_bytes;
  2130. if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
  2131. inum == btrfs_ino(BTRFS_I(inode)))
  2132. return 0;
  2133. key.objectid = root_id;
  2134. key.type = BTRFS_ROOT_ITEM_KEY;
  2135. key.offset = (u64)-1;
  2136. root = btrfs_read_fs_root_no_name(fs_info, &key);
  2137. if (IS_ERR(root)) {
  2138. if (PTR_ERR(root) == -ENOENT)
  2139. return 0;
  2140. WARN_ON(1);
  2141. btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
  2142. inum, offset, root_id);
  2143. return PTR_ERR(root);
  2144. }
  2145. key.objectid = inum;
  2146. key.type = BTRFS_EXTENT_DATA_KEY;
  2147. if (offset > (u64)-1 << 32)
  2148. key.offset = 0;
  2149. else
  2150. key.offset = offset;
  2151. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  2152. if (WARN_ON(ret < 0))
  2153. return ret;
  2154. ret = 0;
  2155. while (1) {
  2156. cond_resched();
  2157. leaf = path->nodes[0];
  2158. slot = path->slots[0];
  2159. if (slot >= btrfs_header_nritems(leaf)) {
  2160. ret = btrfs_next_leaf(root, path);
  2161. if (ret < 0) {
  2162. goto out;
  2163. } else if (ret > 0) {
  2164. ret = 0;
  2165. goto out;
  2166. }
  2167. continue;
  2168. }
  2169. path->slots[0]++;
  2170. btrfs_item_key_to_cpu(leaf, &key, slot);
  2171. if (key.objectid > inum)
  2172. goto out;
  2173. if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
  2174. continue;
  2175. extent = btrfs_item_ptr(leaf, slot,
  2176. struct btrfs_file_extent_item);
  2177. if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
  2178. continue;
  2179. /*
  2180. * 'offset' refers to the exact key.offset,
  2181. * NOT the 'offset' field in btrfs_extent_data_ref, ie.
  2182. * (key.offset - extent_offset).
  2183. */
  2184. if (key.offset != offset)
  2185. continue;
  2186. extent_offset = btrfs_file_extent_offset(leaf, extent);
  2187. num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
  2188. if (extent_offset >= old->extent_offset + old->offset +
  2189. old->len || extent_offset + num_bytes <=
  2190. old->extent_offset + old->offset)
  2191. continue;
  2192. break;
  2193. }
  2194. backref = kmalloc(sizeof(*backref), GFP_NOFS);
  2195. if (!backref) {
  2196. ret = -ENOENT;
  2197. goto out;
  2198. }
  2199. backref->root_id = root_id;
  2200. backref->inum = inum;
  2201. backref->file_pos = offset;
  2202. backref->num_bytes = num_bytes;
  2203. backref->extent_offset = extent_offset;
  2204. backref->generation = btrfs_file_extent_generation(leaf, extent);
  2205. backref->old = old;
  2206. backref_insert(&new->root, backref);
  2207. old->count++;
  2208. out:
  2209. btrfs_release_path(path);
  2210. WARN_ON(ret);
  2211. return ret;
  2212. }
  2213. static noinline bool record_extent_backrefs(struct btrfs_path *path,
  2214. struct new_sa_defrag_extent *new)
  2215. {
  2216. struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
  2217. struct old_sa_defrag_extent *old, *tmp;
  2218. int ret;
  2219. new->path = path;
  2220. list_for_each_entry_safe(old, tmp, &new->head, list) {
  2221. ret = iterate_inodes_from_logical(old->bytenr +
  2222. old->extent_offset, fs_info,
  2223. path, record_one_backref,
  2224. old, false);
  2225. if (ret < 0 && ret != -ENOENT)
  2226. return false;
  2227. /* no backref to be processed for this extent */
  2228. if (!old->count) {
  2229. list_del(&old->list);
  2230. kfree(old);
  2231. }
  2232. }
  2233. if (list_empty(&new->head))
  2234. return false;
  2235. return true;
  2236. }
  2237. static int relink_is_mergable(struct extent_buffer *leaf,
  2238. struct btrfs_file_extent_item *fi,
  2239. struct new_sa_defrag_extent *new)
  2240. {
  2241. if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
  2242. return 0;
  2243. if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
  2244. return 0;
  2245. if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
  2246. return 0;
  2247. if (btrfs_file_extent_encryption(leaf, fi) ||
  2248. btrfs_file_extent_other_encoding(leaf, fi))
  2249. return 0;
  2250. return 1;
  2251. }
  2252. /*
  2253. * Note the backref might has changed, and in this case we just return 0.
  2254. */
  2255. static noinline int relink_extent_backref(struct btrfs_path *path,
  2256. struct sa_defrag_extent_backref *prev,
  2257. struct sa_defrag_extent_backref *backref)
  2258. {
  2259. struct btrfs_file_extent_item *extent;
  2260. struct btrfs_file_extent_item *item;
  2261. struct btrfs_ordered_extent *ordered;
  2262. struct btrfs_trans_handle *trans;
  2263. struct btrfs_root *root;
  2264. struct btrfs_key key;
  2265. struct extent_buffer *leaf;
  2266. struct old_sa_defrag_extent *old = backref->old;
  2267. struct new_sa_defrag_extent *new = old->new;
  2268. struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
  2269. struct inode *inode;
  2270. struct extent_state *cached = NULL;
  2271. int ret = 0;
  2272. u64 start;
  2273. u64 len;
  2274. u64 lock_start;
  2275. u64 lock_end;
  2276. bool merge = false;
  2277. int index;
  2278. if (prev && prev->root_id == backref->root_id &&
  2279. prev->inum == backref->inum &&
  2280. prev->file_pos + prev->num_bytes == backref->file_pos)
  2281. merge = true;
  2282. /* step 1: get root */
  2283. key.objectid = backref->root_id;
  2284. key.type = BTRFS_ROOT_ITEM_KEY;
  2285. key.offset = (u64)-1;
  2286. index = srcu_read_lock(&fs_info->subvol_srcu);
  2287. root = btrfs_read_fs_root_no_name(fs_info, &key);
  2288. if (IS_ERR(root)) {
  2289. srcu_read_unlock(&fs_info->subvol_srcu, index);
  2290. if (PTR_ERR(root) == -ENOENT)
  2291. return 0;
  2292. return PTR_ERR(root);
  2293. }
  2294. if (btrfs_root_readonly(root)) {
  2295. srcu_read_unlock(&fs_info->subvol_srcu, index);
  2296. return 0;
  2297. }
  2298. /* step 2: get inode */
  2299. key.objectid = backref->inum;
  2300. key.type = BTRFS_INODE_ITEM_KEY;
  2301. key.offset = 0;
  2302. inode = btrfs_iget(fs_info->sb, &key, root, NULL);
  2303. if (IS_ERR(inode)) {
  2304. srcu_read_unlock(&fs_info->subvol_srcu, index);
  2305. return 0;
  2306. }
  2307. srcu_read_unlock(&fs_info->subvol_srcu, index);
  2308. /* step 3: relink backref */
  2309. lock_start = backref->file_pos;
  2310. lock_end = backref->file_pos + backref->num_bytes - 1;
  2311. lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
  2312. &cached);
  2313. ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
  2314. if (ordered) {
  2315. btrfs_put_ordered_extent(ordered);
  2316. goto out_unlock;
  2317. }
  2318. trans = btrfs_join_transaction(root);
  2319. if (IS_ERR(trans)) {
  2320. ret = PTR_ERR(trans);
  2321. goto out_unlock;
  2322. }
  2323. key.objectid = backref->inum;
  2324. key.type = BTRFS_EXTENT_DATA_KEY;
  2325. key.offset = backref->file_pos;
  2326. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  2327. if (ret < 0) {
  2328. goto out_free_path;
  2329. } else if (ret > 0) {
  2330. ret = 0;
  2331. goto out_free_path;
  2332. }
  2333. extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
  2334. struct btrfs_file_extent_item);
  2335. if (btrfs_file_extent_generation(path->nodes[0], extent) !=
  2336. backref->generation)
  2337. goto out_free_path;
  2338. btrfs_release_path(path);
  2339. start = backref->file_pos;
  2340. if (backref->extent_offset < old->extent_offset + old->offset)
  2341. start += old->extent_offset + old->offset -
  2342. backref->extent_offset;
  2343. len = min(backref->extent_offset + backref->num_bytes,
  2344. old->extent_offset + old->offset + old->len);
  2345. len -= max(backref->extent_offset, old->extent_offset + old->offset);
  2346. ret = btrfs_drop_extents(trans, root, inode, start,
  2347. start + len, 1);
  2348. if (ret)
  2349. goto out_free_path;
  2350. again:
  2351. key.objectid = btrfs_ino(BTRFS_I(inode));
  2352. key.type = BTRFS_EXTENT_DATA_KEY;
  2353. key.offset = start;
  2354. path->leave_spinning = 1;
  2355. if (merge) {
  2356. struct btrfs_file_extent_item *fi;
  2357. u64 extent_len;
  2358. struct btrfs_key found_key;
  2359. ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
  2360. if (ret < 0)
  2361. goto out_free_path;
  2362. path->slots[0]--;
  2363. leaf = path->nodes[0];
  2364. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  2365. fi = btrfs_item_ptr(leaf, path->slots[0],
  2366. struct btrfs_file_extent_item);
  2367. extent_len = btrfs_file_extent_num_bytes(leaf, fi);
  2368. if (extent_len + found_key.offset == start &&
  2369. relink_is_mergable(leaf, fi, new)) {
  2370. btrfs_set_file_extent_num_bytes(leaf, fi,
  2371. extent_len + len);
  2372. btrfs_mark_buffer_dirty(leaf);
  2373. inode_add_bytes(inode, len);
  2374. ret = 1;
  2375. goto out_free_path;
  2376. } else {
  2377. merge = false;
  2378. btrfs_release_path(path);
  2379. goto again;
  2380. }
  2381. }
  2382. ret = btrfs_insert_empty_item(trans, root, path, &key,
  2383. sizeof(*extent));
  2384. if (ret) {
  2385. btrfs_abort_transaction(trans, ret);
  2386. goto out_free_path;
  2387. }
  2388. leaf = path->nodes[0];
  2389. item = btrfs_item_ptr(leaf, path->slots[0],
  2390. struct btrfs_file_extent_item);
  2391. btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
  2392. btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
  2393. btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
  2394. btrfs_set_file_extent_num_bytes(leaf, item, len);
  2395. btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
  2396. btrfs_set_file_extent_generation(leaf, item, trans->transid);
  2397. btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
  2398. btrfs_set_file_extent_compression(leaf, item, new->compress_type);
  2399. btrfs_set_file_extent_encryption(leaf, item, 0);
  2400. btrfs_set_file_extent_other_encoding(leaf, item, 0);
  2401. btrfs_mark_buffer_dirty(leaf);
  2402. inode_add_bytes(inode, len);
  2403. btrfs_release_path(path);
  2404. ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
  2405. new->disk_len, 0,
  2406. backref->root_id, backref->inum,
  2407. new->file_pos); /* start - extent_offset */
  2408. if (ret) {
  2409. btrfs_abort_transaction(trans, ret);
  2410. goto out_free_path;
  2411. }
  2412. ret = 1;
  2413. out_free_path:
  2414. btrfs_release_path(path);
  2415. path->leave_spinning = 0;
  2416. btrfs_end_transaction(trans);
  2417. out_unlock:
  2418. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
  2419. &cached, GFP_NOFS);
  2420. iput(inode);
  2421. return ret;
  2422. }
  2423. static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
  2424. {
  2425. struct old_sa_defrag_extent *old, *tmp;
  2426. if (!new)
  2427. return;
  2428. list_for_each_entry_safe(old, tmp, &new->head, list) {
  2429. kfree(old);
  2430. }
  2431. kfree(new);
  2432. }
  2433. static void relink_file_extents(struct new_sa_defrag_extent *new)
  2434. {
  2435. struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
  2436. struct btrfs_path *path;
  2437. struct sa_defrag_extent_backref *backref;
  2438. struct sa_defrag_extent_backref *prev = NULL;
  2439. struct inode *inode;
  2440. struct btrfs_root *root;
  2441. struct rb_node *node;
  2442. int ret;
  2443. inode = new->inode;
  2444. root = BTRFS_I(inode)->root;
  2445. path = btrfs_alloc_path();
  2446. if (!path)
  2447. return;
  2448. if (!record_extent_backrefs(path, new)) {
  2449. btrfs_free_path(path);
  2450. goto out;
  2451. }
  2452. btrfs_release_path(path);
  2453. while (1) {
  2454. node = rb_first(&new->root);
  2455. if (!node)
  2456. break;
  2457. rb_erase(node, &new->root);
  2458. backref = rb_entry(node, struct sa_defrag_extent_backref, node);
  2459. ret = relink_extent_backref(path, prev, backref);
  2460. WARN_ON(ret < 0);
  2461. kfree(prev);
  2462. if (ret == 1)
  2463. prev = backref;
  2464. else
  2465. prev = NULL;
  2466. cond_resched();
  2467. }
  2468. kfree(prev);
  2469. btrfs_free_path(path);
  2470. out:
  2471. free_sa_defrag_extent(new);
  2472. atomic_dec(&fs_info->defrag_running);
  2473. wake_up(&fs_info->transaction_wait);
  2474. }
  2475. static struct new_sa_defrag_extent *
  2476. record_old_file_extents(struct inode *inode,
  2477. struct btrfs_ordered_extent *ordered)
  2478. {
  2479. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2480. struct btrfs_root *root = BTRFS_I(inode)->root;
  2481. struct btrfs_path *path;
  2482. struct btrfs_key key;
  2483. struct old_sa_defrag_extent *old;
  2484. struct new_sa_defrag_extent *new;
  2485. int ret;
  2486. new = kmalloc(sizeof(*new), GFP_NOFS);
  2487. if (!new)
  2488. return NULL;
  2489. new->inode = inode;
  2490. new->file_pos = ordered->file_offset;
  2491. new->len = ordered->len;
  2492. new->bytenr = ordered->start;
  2493. new->disk_len = ordered->disk_len;
  2494. new->compress_type = ordered->compress_type;
  2495. new->root = RB_ROOT;
  2496. INIT_LIST_HEAD(&new->head);
  2497. path = btrfs_alloc_path();
  2498. if (!path)
  2499. goto out_kfree;
  2500. key.objectid = btrfs_ino(BTRFS_I(inode));
  2501. key.type = BTRFS_EXTENT_DATA_KEY;
  2502. key.offset = new->file_pos;
  2503. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  2504. if (ret < 0)
  2505. goto out_free_path;
  2506. if (ret > 0 && path->slots[0] > 0)
  2507. path->slots[0]--;
  2508. /* find out all the old extents for the file range */
  2509. while (1) {
  2510. struct btrfs_file_extent_item *extent;
  2511. struct extent_buffer *l;
  2512. int slot;
  2513. u64 num_bytes;
  2514. u64 offset;
  2515. u64 end;
  2516. u64 disk_bytenr;
  2517. u64 extent_offset;
  2518. l = path->nodes[0];
  2519. slot = path->slots[0];
  2520. if (slot >= btrfs_header_nritems(l)) {
  2521. ret = btrfs_next_leaf(root, path);
  2522. if (ret < 0)
  2523. goto out_free_path;
  2524. else if (ret > 0)
  2525. break;
  2526. continue;
  2527. }
  2528. btrfs_item_key_to_cpu(l, &key, slot);
  2529. if (key.objectid != btrfs_ino(BTRFS_I(inode)))
  2530. break;
  2531. if (key.type != BTRFS_EXTENT_DATA_KEY)
  2532. break;
  2533. if (key.offset >= new->file_pos + new->len)
  2534. break;
  2535. extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
  2536. num_bytes = btrfs_file_extent_num_bytes(l, extent);
  2537. if (key.offset + num_bytes < new->file_pos)
  2538. goto next;
  2539. disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
  2540. if (!disk_bytenr)
  2541. goto next;
  2542. extent_offset = btrfs_file_extent_offset(l, extent);
  2543. old = kmalloc(sizeof(*old), GFP_NOFS);
  2544. if (!old)
  2545. goto out_free_path;
  2546. offset = max(new->file_pos, key.offset);
  2547. end = min(new->file_pos + new->len, key.offset + num_bytes);
  2548. old->bytenr = disk_bytenr;
  2549. old->extent_offset = extent_offset;
  2550. old->offset = offset - key.offset;
  2551. old->len = end - offset;
  2552. old->new = new;
  2553. old->count = 0;
  2554. list_add_tail(&old->list, &new->head);
  2555. next:
  2556. path->slots[0]++;
  2557. cond_resched();
  2558. }
  2559. btrfs_free_path(path);
  2560. atomic_inc(&fs_info->defrag_running);
  2561. return new;
  2562. out_free_path:
  2563. btrfs_free_path(path);
  2564. out_kfree:
  2565. free_sa_defrag_extent(new);
  2566. return NULL;
  2567. }
  2568. static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
  2569. u64 start, u64 len)
  2570. {
  2571. struct btrfs_block_group_cache *cache;
  2572. cache = btrfs_lookup_block_group(fs_info, start);
  2573. ASSERT(cache);
  2574. spin_lock(&cache->lock);
  2575. cache->delalloc_bytes -= len;
  2576. spin_unlock(&cache->lock);
  2577. btrfs_put_block_group(cache);
  2578. }
  2579. /* as ordered data IO finishes, this gets called so we can finish
  2580. * an ordered extent if the range of bytes in the file it covers are
  2581. * fully written.
  2582. */
  2583. static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
  2584. {
  2585. struct inode *inode = ordered_extent->inode;
  2586. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2587. struct btrfs_root *root = BTRFS_I(inode)->root;
  2588. struct btrfs_trans_handle *trans = NULL;
  2589. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  2590. struct extent_state *cached_state = NULL;
  2591. struct new_sa_defrag_extent *new = NULL;
  2592. int compress_type = 0;
  2593. int ret = 0;
  2594. u64 logical_len = ordered_extent->len;
  2595. bool nolock;
  2596. bool truncated = false;
  2597. bool range_locked = false;
  2598. bool clear_new_delalloc_bytes = false;
  2599. if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
  2600. !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
  2601. !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
  2602. clear_new_delalloc_bytes = true;
  2603. nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
  2604. if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
  2605. ret = -EIO;
  2606. goto out;
  2607. }
  2608. btrfs_free_io_failure_record(BTRFS_I(inode),
  2609. ordered_extent->file_offset,
  2610. ordered_extent->file_offset +
  2611. ordered_extent->len - 1);
  2612. if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
  2613. truncated = true;
  2614. logical_len = ordered_extent->truncated_len;
  2615. /* Truncated the entire extent, don't bother adding */
  2616. if (!logical_len)
  2617. goto out;
  2618. }
  2619. if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
  2620. BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
  2621. /*
  2622. * For mwrite(mmap + memset to write) case, we still reserve
  2623. * space for NOCOW range.
  2624. * As NOCOW won't cause a new delayed ref, just free the space
  2625. */
  2626. btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
  2627. ordered_extent->len);
  2628. btrfs_ordered_update_i_size(inode, 0, ordered_extent);
  2629. if (nolock)
  2630. trans = btrfs_join_transaction_nolock(root);
  2631. else
  2632. trans = btrfs_join_transaction(root);
  2633. if (IS_ERR(trans)) {
  2634. ret = PTR_ERR(trans);
  2635. trans = NULL;
  2636. goto out;
  2637. }
  2638. trans->block_rsv = &BTRFS_I(inode)->block_rsv;
  2639. ret = btrfs_update_inode_fallback(trans, root, inode);
  2640. if (ret) /* -ENOMEM or corruption */
  2641. btrfs_abort_transaction(trans, ret);
  2642. goto out;
  2643. }
  2644. range_locked = true;
  2645. lock_extent_bits(io_tree, ordered_extent->file_offset,
  2646. ordered_extent->file_offset + ordered_extent->len - 1,
  2647. &cached_state);
  2648. ret = test_range_bit(io_tree, ordered_extent->file_offset,
  2649. ordered_extent->file_offset + ordered_extent->len - 1,
  2650. EXTENT_DEFRAG, 0, cached_state);
  2651. if (ret) {
  2652. u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
  2653. if (0 && last_snapshot >= BTRFS_I(inode)->generation)
  2654. /* the inode is shared */
  2655. new = record_old_file_extents(inode, ordered_extent);
  2656. clear_extent_bit(io_tree, ordered_extent->file_offset,
  2657. ordered_extent->file_offset + ordered_extent->len - 1,
  2658. EXTENT_DEFRAG, 0, 0, &cached_state);
  2659. }
  2660. if (nolock)
  2661. trans = btrfs_join_transaction_nolock(root);
  2662. else
  2663. trans = btrfs_join_transaction(root);
  2664. if (IS_ERR(trans)) {
  2665. ret = PTR_ERR(trans);
  2666. trans = NULL;
  2667. goto out;
  2668. }
  2669. trans->block_rsv = &BTRFS_I(inode)->block_rsv;
  2670. if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
  2671. compress_type = ordered_extent->compress_type;
  2672. if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
  2673. BUG_ON(compress_type);
  2674. btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
  2675. ordered_extent->len);
  2676. ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
  2677. ordered_extent->file_offset,
  2678. ordered_extent->file_offset +
  2679. logical_len);
  2680. } else {
  2681. BUG_ON(root == fs_info->tree_root);
  2682. ret = insert_reserved_file_extent(trans, inode,
  2683. ordered_extent->file_offset,
  2684. ordered_extent->start,
  2685. ordered_extent->disk_len,
  2686. logical_len, logical_len,
  2687. compress_type, 0, 0,
  2688. BTRFS_FILE_EXTENT_REG);
  2689. if (!ret)
  2690. btrfs_release_delalloc_bytes(fs_info,
  2691. ordered_extent->start,
  2692. ordered_extent->disk_len);
  2693. }
  2694. unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
  2695. ordered_extent->file_offset, ordered_extent->len,
  2696. trans->transid);
  2697. if (ret < 0) {
  2698. btrfs_abort_transaction(trans, ret);
  2699. goto out;
  2700. }
  2701. add_pending_csums(trans, inode, &ordered_extent->list);
  2702. btrfs_ordered_update_i_size(inode, 0, ordered_extent);
  2703. ret = btrfs_update_inode_fallback(trans, root, inode);
  2704. if (ret) { /* -ENOMEM or corruption */
  2705. btrfs_abort_transaction(trans, ret);
  2706. goto out;
  2707. }
  2708. ret = 0;
  2709. out:
  2710. if (range_locked || clear_new_delalloc_bytes) {
  2711. unsigned int clear_bits = 0;
  2712. if (range_locked)
  2713. clear_bits |= EXTENT_LOCKED;
  2714. if (clear_new_delalloc_bytes)
  2715. clear_bits |= EXTENT_DELALLOC_NEW;
  2716. clear_extent_bit(&BTRFS_I(inode)->io_tree,
  2717. ordered_extent->file_offset,
  2718. ordered_extent->file_offset +
  2719. ordered_extent->len - 1,
  2720. clear_bits,
  2721. (clear_bits & EXTENT_LOCKED) ? 1 : 0,
  2722. 0, &cached_state);
  2723. }
  2724. if (trans)
  2725. btrfs_end_transaction(trans);
  2726. if (ret || truncated) {
  2727. u64 start, end;
  2728. if (truncated)
  2729. start = ordered_extent->file_offset + logical_len;
  2730. else
  2731. start = ordered_extent->file_offset;
  2732. end = ordered_extent->file_offset + ordered_extent->len - 1;
  2733. clear_extent_uptodate(io_tree, start, end, NULL);
  2734. /* Drop the cache for the part of the extent we didn't write. */
  2735. btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
  2736. /*
  2737. * If the ordered extent had an IOERR or something else went
  2738. * wrong we need to return the space for this ordered extent
  2739. * back to the allocator. We only free the extent in the
  2740. * truncated case if we didn't write out the extent at all.
  2741. */
  2742. if ((ret || !logical_len) &&
  2743. !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
  2744. !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
  2745. btrfs_free_reserved_extent(fs_info,
  2746. ordered_extent->start,
  2747. ordered_extent->disk_len, 1);
  2748. }
  2749. /*
  2750. * This needs to be done to make sure anybody waiting knows we are done
  2751. * updating everything for this ordered extent.
  2752. */
  2753. btrfs_remove_ordered_extent(inode, ordered_extent);
  2754. /* for snapshot-aware defrag */
  2755. if (new) {
  2756. if (ret) {
  2757. free_sa_defrag_extent(new);
  2758. atomic_dec(&fs_info->defrag_running);
  2759. } else {
  2760. relink_file_extents(new);
  2761. }
  2762. }
  2763. /* once for us */
  2764. btrfs_put_ordered_extent(ordered_extent);
  2765. /* once for the tree */
  2766. btrfs_put_ordered_extent(ordered_extent);
  2767. return ret;
  2768. }
  2769. static void finish_ordered_fn(struct btrfs_work *work)
  2770. {
  2771. struct btrfs_ordered_extent *ordered_extent;
  2772. ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
  2773. btrfs_finish_ordered_io(ordered_extent);
  2774. }
  2775. static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
  2776. struct extent_state *state, int uptodate)
  2777. {
  2778. struct inode *inode = page->mapping->host;
  2779. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2780. struct btrfs_ordered_extent *ordered_extent = NULL;
  2781. struct btrfs_workqueue *wq;
  2782. btrfs_work_func_t func;
  2783. trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
  2784. ClearPagePrivate2(page);
  2785. if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
  2786. end - start + 1, uptodate))
  2787. return;
  2788. if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
  2789. wq = fs_info->endio_freespace_worker;
  2790. func = btrfs_freespace_write_helper;
  2791. } else {
  2792. wq = fs_info->endio_write_workers;
  2793. func = btrfs_endio_write_helper;
  2794. }
  2795. btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
  2796. NULL);
  2797. btrfs_queue_work(wq, &ordered_extent->work);
  2798. }
  2799. static int __readpage_endio_check(struct inode *inode,
  2800. struct btrfs_io_bio *io_bio,
  2801. int icsum, struct page *page,
  2802. int pgoff, u64 start, size_t len)
  2803. {
  2804. char *kaddr;
  2805. u32 csum_expected;
  2806. u32 csum = ~(u32)0;
  2807. csum_expected = *(((u32 *)io_bio->csum) + icsum);
  2808. kaddr = kmap_atomic(page);
  2809. csum = btrfs_csum_data(kaddr + pgoff, csum, len);
  2810. btrfs_csum_final(csum, (u8 *)&csum);
  2811. if (csum != csum_expected)
  2812. goto zeroit;
  2813. kunmap_atomic(kaddr);
  2814. return 0;
  2815. zeroit:
  2816. btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
  2817. io_bio->mirror_num);
  2818. memset(kaddr + pgoff, 1, len);
  2819. flush_dcache_page(page);
  2820. kunmap_atomic(kaddr);
  2821. return -EIO;
  2822. }
  2823. /*
  2824. * when reads are done, we need to check csums to verify the data is correct
  2825. * if there's a match, we allow the bio to finish. If not, the code in
  2826. * extent_io.c will try to find good copies for us.
  2827. */
  2828. static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
  2829. u64 phy_offset, struct page *page,
  2830. u64 start, u64 end, int mirror)
  2831. {
  2832. size_t offset = start - page_offset(page);
  2833. struct inode *inode = page->mapping->host;
  2834. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  2835. struct btrfs_root *root = BTRFS_I(inode)->root;
  2836. if (PageChecked(page)) {
  2837. ClearPageChecked(page);
  2838. return 0;
  2839. }
  2840. if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
  2841. return 0;
  2842. if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
  2843. test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
  2844. clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
  2845. return 0;
  2846. }
  2847. phy_offset >>= inode->i_sb->s_blocksize_bits;
  2848. return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
  2849. start, (size_t)(end - start + 1));
  2850. }
  2851. void btrfs_add_delayed_iput(struct inode *inode)
  2852. {
  2853. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2854. struct btrfs_inode *binode = BTRFS_I(inode);
  2855. if (atomic_add_unless(&inode->i_count, -1, 1))
  2856. return;
  2857. spin_lock(&fs_info->delayed_iput_lock);
  2858. if (binode->delayed_iput_count == 0) {
  2859. ASSERT(list_empty(&binode->delayed_iput));
  2860. list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
  2861. } else {
  2862. binode->delayed_iput_count++;
  2863. }
  2864. spin_unlock(&fs_info->delayed_iput_lock);
  2865. }
  2866. void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
  2867. {
  2868. spin_lock(&fs_info->delayed_iput_lock);
  2869. while (!list_empty(&fs_info->delayed_iputs)) {
  2870. struct btrfs_inode *inode;
  2871. inode = list_first_entry(&fs_info->delayed_iputs,
  2872. struct btrfs_inode, delayed_iput);
  2873. if (inode->delayed_iput_count) {
  2874. inode->delayed_iput_count--;
  2875. list_move_tail(&inode->delayed_iput,
  2876. &fs_info->delayed_iputs);
  2877. } else {
  2878. list_del_init(&inode->delayed_iput);
  2879. }
  2880. spin_unlock(&fs_info->delayed_iput_lock);
  2881. iput(&inode->vfs_inode);
  2882. spin_lock(&fs_info->delayed_iput_lock);
  2883. }
  2884. spin_unlock(&fs_info->delayed_iput_lock);
  2885. }
  2886. /*
  2887. * This is called in transaction commit time. If there are no orphan
  2888. * files in the subvolume, it removes orphan item and frees block_rsv
  2889. * structure.
  2890. */
  2891. void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
  2892. struct btrfs_root *root)
  2893. {
  2894. struct btrfs_fs_info *fs_info = root->fs_info;
  2895. struct btrfs_block_rsv *block_rsv;
  2896. int ret;
  2897. if (atomic_read(&root->orphan_inodes) ||
  2898. root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
  2899. return;
  2900. spin_lock(&root->orphan_lock);
  2901. if (atomic_read(&root->orphan_inodes)) {
  2902. spin_unlock(&root->orphan_lock);
  2903. return;
  2904. }
  2905. if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
  2906. spin_unlock(&root->orphan_lock);
  2907. return;
  2908. }
  2909. block_rsv = root->orphan_block_rsv;
  2910. root->orphan_block_rsv = NULL;
  2911. spin_unlock(&root->orphan_lock);
  2912. if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
  2913. btrfs_root_refs(&root->root_item) > 0) {
  2914. ret = btrfs_del_orphan_item(trans, fs_info->tree_root,
  2915. root->root_key.objectid);
  2916. if (ret)
  2917. btrfs_abort_transaction(trans, ret);
  2918. else
  2919. clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
  2920. &root->state);
  2921. }
  2922. if (block_rsv) {
  2923. WARN_ON(block_rsv->size > 0);
  2924. btrfs_free_block_rsv(fs_info, block_rsv);
  2925. }
  2926. }
  2927. /*
  2928. * This creates an orphan entry for the given inode in case something goes
  2929. * wrong in the middle of an unlink/truncate.
  2930. *
  2931. * NOTE: caller of this function should reserve 5 units of metadata for
  2932. * this function.
  2933. */
  2934. int btrfs_orphan_add(struct btrfs_trans_handle *trans,
  2935. struct btrfs_inode *inode)
  2936. {
  2937. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  2938. struct btrfs_root *root = inode->root;
  2939. struct btrfs_block_rsv *block_rsv = NULL;
  2940. int reserve = 0;
  2941. int insert = 0;
  2942. int ret;
  2943. if (!root->orphan_block_rsv) {
  2944. block_rsv = btrfs_alloc_block_rsv(fs_info,
  2945. BTRFS_BLOCK_RSV_TEMP);
  2946. if (!block_rsv)
  2947. return -ENOMEM;
  2948. }
  2949. spin_lock(&root->orphan_lock);
  2950. if (!root->orphan_block_rsv) {
  2951. root->orphan_block_rsv = block_rsv;
  2952. } else if (block_rsv) {
  2953. btrfs_free_block_rsv(fs_info, block_rsv);
  2954. block_rsv = NULL;
  2955. }
  2956. if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
  2957. &inode->runtime_flags)) {
  2958. #if 0
  2959. /*
  2960. * For proper ENOSPC handling, we should do orphan
  2961. * cleanup when mounting. But this introduces backward
  2962. * compatibility issue.
  2963. */
  2964. if (!xchg(&root->orphan_item_inserted, 1))
  2965. insert = 2;
  2966. else
  2967. insert = 1;
  2968. #endif
  2969. insert = 1;
  2970. atomic_inc(&root->orphan_inodes);
  2971. }
  2972. if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
  2973. &inode->runtime_flags))
  2974. reserve = 1;
  2975. spin_unlock(&root->orphan_lock);
  2976. /* grab metadata reservation from transaction handle */
  2977. if (reserve) {
  2978. ret = btrfs_orphan_reserve_metadata(trans, inode);
  2979. ASSERT(!ret);
  2980. if (ret) {
  2981. atomic_dec(&root->orphan_inodes);
  2982. clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
  2983. &inode->runtime_flags);
  2984. if (insert)
  2985. clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
  2986. &inode->runtime_flags);
  2987. return ret;
  2988. }
  2989. }
  2990. /* insert an orphan item to track this unlinked/truncated file */
  2991. if (insert >= 1) {
  2992. ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
  2993. if (ret) {
  2994. atomic_dec(&root->orphan_inodes);
  2995. if (reserve) {
  2996. clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
  2997. &inode->runtime_flags);
  2998. btrfs_orphan_release_metadata(inode);
  2999. }
  3000. if (ret != -EEXIST) {
  3001. clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
  3002. &inode->runtime_flags);
  3003. btrfs_abort_transaction(trans, ret);
  3004. return ret;
  3005. }
  3006. }
  3007. ret = 0;
  3008. }
  3009. /* insert an orphan item to track subvolume contains orphan files */
  3010. if (insert >= 2) {
  3011. ret = btrfs_insert_orphan_item(trans, fs_info->tree_root,
  3012. root->root_key.objectid);
  3013. if (ret && ret != -EEXIST) {
  3014. btrfs_abort_transaction(trans, ret);
  3015. return ret;
  3016. }
  3017. }
  3018. return 0;
  3019. }
  3020. /*
  3021. * We have done the truncate/delete so we can go ahead and remove the orphan
  3022. * item for this particular inode.
  3023. */
  3024. static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
  3025. struct btrfs_inode *inode)
  3026. {
  3027. struct btrfs_root *root = inode->root;
  3028. int delete_item = 0;
  3029. int release_rsv = 0;
  3030. int ret = 0;
  3031. spin_lock(&root->orphan_lock);
  3032. if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
  3033. &inode->runtime_flags))
  3034. delete_item = 1;
  3035. if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
  3036. &inode->runtime_flags))
  3037. release_rsv = 1;
  3038. spin_unlock(&root->orphan_lock);
  3039. if (delete_item) {
  3040. atomic_dec(&root->orphan_inodes);
  3041. if (trans)
  3042. ret = btrfs_del_orphan_item(trans, root,
  3043. btrfs_ino(inode));
  3044. }
  3045. if (release_rsv)
  3046. btrfs_orphan_release_metadata(inode);
  3047. return ret;
  3048. }
  3049. /*
  3050. * this cleans up any orphans that may be left on the list from the last use
  3051. * of this root.
  3052. */
  3053. int btrfs_orphan_cleanup(struct btrfs_root *root)
  3054. {
  3055. struct btrfs_fs_info *fs_info = root->fs_info;
  3056. struct btrfs_path *path;
  3057. struct extent_buffer *leaf;
  3058. struct btrfs_key key, found_key;
  3059. struct btrfs_trans_handle *trans;
  3060. struct inode *inode;
  3061. u64 last_objectid = 0;
  3062. int ret = 0, nr_unlink = 0, nr_truncate = 0;
  3063. if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
  3064. return 0;
  3065. path = btrfs_alloc_path();
  3066. if (!path) {
  3067. ret = -ENOMEM;
  3068. goto out;
  3069. }
  3070. path->reada = READA_BACK;
  3071. key.objectid = BTRFS_ORPHAN_OBJECTID;
  3072. key.type = BTRFS_ORPHAN_ITEM_KEY;
  3073. key.offset = (u64)-1;
  3074. while (1) {
  3075. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  3076. if (ret < 0)
  3077. goto out;
  3078. /*
  3079. * if ret == 0 means we found what we were searching for, which
  3080. * is weird, but possible, so only screw with path if we didn't
  3081. * find the key and see if we have stuff that matches
  3082. */
  3083. if (ret > 0) {
  3084. ret = 0;
  3085. if (path->slots[0] == 0)
  3086. break;
  3087. path->slots[0]--;
  3088. }
  3089. /* pull out the item */
  3090. leaf = path->nodes[0];
  3091. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  3092. /* make sure the item matches what we want */
  3093. if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
  3094. break;
  3095. if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
  3096. break;
  3097. /* release the path since we're done with it */
  3098. btrfs_release_path(path);
  3099. /*
  3100. * this is where we are basically btrfs_lookup, without the
  3101. * crossing root thing. we store the inode number in the
  3102. * offset of the orphan item.
  3103. */
  3104. if (found_key.offset == last_objectid) {
  3105. btrfs_err(fs_info,
  3106. "Error removing orphan entry, stopping orphan cleanup");
  3107. ret = -EINVAL;
  3108. goto out;
  3109. }
  3110. last_objectid = found_key.offset;
  3111. found_key.objectid = found_key.offset;
  3112. found_key.type = BTRFS_INODE_ITEM_KEY;
  3113. found_key.offset = 0;
  3114. inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
  3115. ret = PTR_ERR_OR_ZERO(inode);
  3116. if (ret && ret != -ENOENT)
  3117. goto out;
  3118. if (ret == -ENOENT && root == fs_info->tree_root) {
  3119. struct btrfs_root *dead_root;
  3120. struct btrfs_fs_info *fs_info = root->fs_info;
  3121. int is_dead_root = 0;
  3122. /*
  3123. * this is an orphan in the tree root. Currently these
  3124. * could come from 2 sources:
  3125. * a) a snapshot deletion in progress
  3126. * b) a free space cache inode
  3127. * We need to distinguish those two, as the snapshot
  3128. * orphan must not get deleted.
  3129. * find_dead_roots already ran before us, so if this
  3130. * is a snapshot deletion, we should find the root
  3131. * in the dead_roots list
  3132. */
  3133. spin_lock(&fs_info->trans_lock);
  3134. list_for_each_entry(dead_root, &fs_info->dead_roots,
  3135. root_list) {
  3136. if (dead_root->root_key.objectid ==
  3137. found_key.objectid) {
  3138. is_dead_root = 1;
  3139. break;
  3140. }
  3141. }
  3142. spin_unlock(&fs_info->trans_lock);
  3143. if (is_dead_root) {
  3144. /* prevent this orphan from being found again */
  3145. key.offset = found_key.objectid - 1;
  3146. continue;
  3147. }
  3148. }
  3149. /*
  3150. * Inode is already gone but the orphan item is still there,
  3151. * kill the orphan item.
  3152. */
  3153. if (ret == -ENOENT) {
  3154. trans = btrfs_start_transaction(root, 1);
  3155. if (IS_ERR(trans)) {
  3156. ret = PTR_ERR(trans);
  3157. goto out;
  3158. }
  3159. btrfs_debug(fs_info, "auto deleting %Lu",
  3160. found_key.objectid);
  3161. ret = btrfs_del_orphan_item(trans, root,
  3162. found_key.objectid);
  3163. btrfs_end_transaction(trans);
  3164. if (ret)
  3165. goto out;
  3166. continue;
  3167. }
  3168. /*
  3169. * add this inode to the orphan list so btrfs_orphan_del does
  3170. * the proper thing when we hit it
  3171. */
  3172. set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
  3173. &BTRFS_I(inode)->runtime_flags);
  3174. atomic_inc(&root->orphan_inodes);
  3175. /* if we have links, this was a truncate, lets do that */
  3176. if (inode->i_nlink) {
  3177. if (WARN_ON(!S_ISREG(inode->i_mode))) {
  3178. iput(inode);
  3179. continue;
  3180. }
  3181. nr_truncate++;
  3182. /* 1 for the orphan item deletion. */
  3183. trans = btrfs_start_transaction(root, 1);
  3184. if (IS_ERR(trans)) {
  3185. iput(inode);
  3186. ret = PTR_ERR(trans);
  3187. goto out;
  3188. }
  3189. ret = btrfs_orphan_add(trans, BTRFS_I(inode));
  3190. btrfs_end_transaction(trans);
  3191. if (ret) {
  3192. iput(inode);
  3193. goto out;
  3194. }
  3195. ret = btrfs_truncate(inode);
  3196. if (ret)
  3197. btrfs_orphan_del(NULL, BTRFS_I(inode));
  3198. } else {
  3199. nr_unlink++;
  3200. }
  3201. /* this will do delete_inode and everything for us */
  3202. iput(inode);
  3203. if (ret)
  3204. goto out;
  3205. }
  3206. /* release the path since we're done with it */
  3207. btrfs_release_path(path);
  3208. root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
  3209. if (root->orphan_block_rsv)
  3210. btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
  3211. (u64)-1);
  3212. if (root->orphan_block_rsv ||
  3213. test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
  3214. trans = btrfs_join_transaction(root);
  3215. if (!IS_ERR(trans))
  3216. btrfs_end_transaction(trans);
  3217. }
  3218. if (nr_unlink)
  3219. btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
  3220. if (nr_truncate)
  3221. btrfs_debug(fs_info, "truncated %d orphans", nr_truncate);
  3222. out:
  3223. if (ret)
  3224. btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
  3225. btrfs_free_path(path);
  3226. return ret;
  3227. }
  3228. /*
  3229. * very simple check to peek ahead in the leaf looking for xattrs. If we
  3230. * don't find any xattrs, we know there can't be any acls.
  3231. *
  3232. * slot is the slot the inode is in, objectid is the objectid of the inode
  3233. */
  3234. static noinline int acls_after_inode_item(struct extent_buffer *leaf,
  3235. int slot, u64 objectid,
  3236. int *first_xattr_slot)
  3237. {
  3238. u32 nritems = btrfs_header_nritems(leaf);
  3239. struct btrfs_key found_key;
  3240. static u64 xattr_access = 0;
  3241. static u64 xattr_default = 0;
  3242. int scanned = 0;
  3243. if (!xattr_access) {
  3244. xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
  3245. strlen(XATTR_NAME_POSIX_ACL_ACCESS));
  3246. xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
  3247. strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
  3248. }
  3249. slot++;
  3250. *first_xattr_slot = -1;
  3251. while (slot < nritems) {
  3252. btrfs_item_key_to_cpu(leaf, &found_key, slot);
  3253. /* we found a different objectid, there must not be acls */
  3254. if (found_key.objectid != objectid)
  3255. return 0;
  3256. /* we found an xattr, assume we've got an acl */
  3257. if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
  3258. if (*first_xattr_slot == -1)
  3259. *first_xattr_slot = slot;
  3260. if (found_key.offset == xattr_access ||
  3261. found_key.offset == xattr_default)
  3262. return 1;
  3263. }
  3264. /*
  3265. * we found a key greater than an xattr key, there can't
  3266. * be any acls later on
  3267. */
  3268. if (found_key.type > BTRFS_XATTR_ITEM_KEY)
  3269. return 0;
  3270. slot++;
  3271. scanned++;
  3272. /*
  3273. * it goes inode, inode backrefs, xattrs, extents,
  3274. * so if there are a ton of hard links to an inode there can
  3275. * be a lot of backrefs. Don't waste time searching too hard,
  3276. * this is just an optimization
  3277. */
  3278. if (scanned >= 8)
  3279. break;
  3280. }
  3281. /* we hit the end of the leaf before we found an xattr or
  3282. * something larger than an xattr. We have to assume the inode
  3283. * has acls
  3284. */
  3285. if (*first_xattr_slot == -1)
  3286. *first_xattr_slot = slot;
  3287. return 1;
  3288. }
  3289. /*
  3290. * read an inode from the btree into the in-memory inode
  3291. */
  3292. static int btrfs_read_locked_inode(struct inode *inode)
  3293. {
  3294. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  3295. struct btrfs_path *path;
  3296. struct extent_buffer *leaf;
  3297. struct btrfs_inode_item *inode_item;
  3298. struct btrfs_root *root = BTRFS_I(inode)->root;
  3299. struct btrfs_key location;
  3300. unsigned long ptr;
  3301. int maybe_acls;
  3302. u32 rdev;
  3303. int ret;
  3304. bool filled = false;
  3305. int first_xattr_slot;
  3306. ret = btrfs_fill_inode(inode, &rdev);
  3307. if (!ret)
  3308. filled = true;
  3309. path = btrfs_alloc_path();
  3310. if (!path) {
  3311. ret = -ENOMEM;
  3312. goto make_bad;
  3313. }
  3314. memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
  3315. ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
  3316. if (ret) {
  3317. if (ret > 0)
  3318. ret = -ENOENT;
  3319. goto make_bad;
  3320. }
  3321. leaf = path->nodes[0];
  3322. if (filled)
  3323. goto cache_index;
  3324. inode_item = btrfs_item_ptr(leaf, path->slots[0],
  3325. struct btrfs_inode_item);
  3326. inode->i_mode = btrfs_inode_mode(leaf, inode_item);
  3327. set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
  3328. i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
  3329. i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
  3330. btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
  3331. inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
  3332. inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
  3333. inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
  3334. inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
  3335. inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
  3336. inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
  3337. BTRFS_I(inode)->i_otime.tv_sec =
  3338. btrfs_timespec_sec(leaf, &inode_item->otime);
  3339. BTRFS_I(inode)->i_otime.tv_nsec =
  3340. btrfs_timespec_nsec(leaf, &inode_item->otime);
  3341. inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
  3342. BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
  3343. BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
  3344. inode->i_version = btrfs_inode_sequence(leaf, inode_item);
  3345. inode->i_generation = BTRFS_I(inode)->generation;
  3346. inode->i_rdev = 0;
  3347. rdev = btrfs_inode_rdev(leaf, inode_item);
  3348. BTRFS_I(inode)->index_cnt = (u64)-1;
  3349. BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
  3350. cache_index:
  3351. /*
  3352. * If we were modified in the current generation and evicted from memory
  3353. * and then re-read we need to do a full sync since we don't have any
  3354. * idea about which extents were modified before we were evicted from
  3355. * cache.
  3356. *
  3357. * This is required for both inode re-read from disk and delayed inode
  3358. * in delayed_nodes_tree.
  3359. */
  3360. if (BTRFS_I(inode)->last_trans == fs_info->generation)
  3361. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  3362. &BTRFS_I(inode)->runtime_flags);
  3363. /*
  3364. * We don't persist the id of the transaction where an unlink operation
  3365. * against the inode was last made. So here we assume the inode might
  3366. * have been evicted, and therefore the exact value of last_unlink_trans
  3367. * lost, and set it to last_trans to avoid metadata inconsistencies
  3368. * between the inode and its parent if the inode is fsync'ed and the log
  3369. * replayed. For example, in the scenario:
  3370. *
  3371. * touch mydir/foo
  3372. * ln mydir/foo mydir/bar
  3373. * sync
  3374. * unlink mydir/bar
  3375. * echo 2 > /proc/sys/vm/drop_caches # evicts inode
  3376. * xfs_io -c fsync mydir/foo
  3377. * <power failure>
  3378. * mount fs, triggers fsync log replay
  3379. *
  3380. * We must make sure that when we fsync our inode foo we also log its
  3381. * parent inode, otherwise after log replay the parent still has the
  3382. * dentry with the "bar" name but our inode foo has a link count of 1
  3383. * and doesn't have an inode ref with the name "bar" anymore.
  3384. *
  3385. * Setting last_unlink_trans to last_trans is a pessimistic approach,
  3386. * but it guarantees correctness at the expense of occasional full
  3387. * transaction commits on fsync if our inode is a directory, or if our
  3388. * inode is not a directory, logging its parent unnecessarily.
  3389. */
  3390. BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
  3391. path->slots[0]++;
  3392. if (inode->i_nlink != 1 ||
  3393. path->slots[0] >= btrfs_header_nritems(leaf))
  3394. goto cache_acl;
  3395. btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
  3396. if (location.objectid != btrfs_ino(BTRFS_I(inode)))
  3397. goto cache_acl;
  3398. ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
  3399. if (location.type == BTRFS_INODE_REF_KEY) {
  3400. struct btrfs_inode_ref *ref;
  3401. ref = (struct btrfs_inode_ref *)ptr;
  3402. BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
  3403. } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
  3404. struct btrfs_inode_extref *extref;
  3405. extref = (struct btrfs_inode_extref *)ptr;
  3406. BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
  3407. extref);
  3408. }
  3409. cache_acl:
  3410. /*
  3411. * try to precache a NULL acl entry for files that don't have
  3412. * any xattrs or acls
  3413. */
  3414. maybe_acls = acls_after_inode_item(leaf, path->slots[0],
  3415. btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
  3416. if (first_xattr_slot != -1) {
  3417. path->slots[0] = first_xattr_slot;
  3418. ret = btrfs_load_inode_props(inode, path);
  3419. if (ret)
  3420. btrfs_err(fs_info,
  3421. "error loading props for ino %llu (root %llu): %d",
  3422. btrfs_ino(BTRFS_I(inode)),
  3423. root->root_key.objectid, ret);
  3424. }
  3425. btrfs_free_path(path);
  3426. if (!maybe_acls)
  3427. cache_no_acl(inode);
  3428. switch (inode->i_mode & S_IFMT) {
  3429. case S_IFREG:
  3430. inode->i_mapping->a_ops = &btrfs_aops;
  3431. BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
  3432. inode->i_fop = &btrfs_file_operations;
  3433. inode->i_op = &btrfs_file_inode_operations;
  3434. break;
  3435. case S_IFDIR:
  3436. inode->i_fop = &btrfs_dir_file_operations;
  3437. inode->i_op = &btrfs_dir_inode_operations;
  3438. break;
  3439. case S_IFLNK:
  3440. inode->i_op = &btrfs_symlink_inode_operations;
  3441. inode_nohighmem(inode);
  3442. inode->i_mapping->a_ops = &btrfs_symlink_aops;
  3443. break;
  3444. default:
  3445. inode->i_op = &btrfs_special_inode_operations;
  3446. init_special_inode(inode, inode->i_mode, rdev);
  3447. break;
  3448. }
  3449. btrfs_update_iflags(inode);
  3450. return 0;
  3451. make_bad:
  3452. btrfs_free_path(path);
  3453. make_bad_inode(inode);
  3454. return ret;
  3455. }
  3456. /*
  3457. * given a leaf and an inode, copy the inode fields into the leaf
  3458. */
  3459. static void fill_inode_item(struct btrfs_trans_handle *trans,
  3460. struct extent_buffer *leaf,
  3461. struct btrfs_inode_item *item,
  3462. struct inode *inode)
  3463. {
  3464. struct btrfs_map_token token;
  3465. btrfs_init_map_token(&token);
  3466. btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
  3467. btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
  3468. btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
  3469. &token);
  3470. btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
  3471. btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
  3472. btrfs_set_token_timespec_sec(leaf, &item->atime,
  3473. inode->i_atime.tv_sec, &token);
  3474. btrfs_set_token_timespec_nsec(leaf, &item->atime,
  3475. inode->i_atime.tv_nsec, &token);
  3476. btrfs_set_token_timespec_sec(leaf, &item->mtime,
  3477. inode->i_mtime.tv_sec, &token);
  3478. btrfs_set_token_timespec_nsec(leaf, &item->mtime,
  3479. inode->i_mtime.tv_nsec, &token);
  3480. btrfs_set_token_timespec_sec(leaf, &item->ctime,
  3481. inode->i_ctime.tv_sec, &token);
  3482. btrfs_set_token_timespec_nsec(leaf, &item->ctime,
  3483. inode->i_ctime.tv_nsec, &token);
  3484. btrfs_set_token_timespec_sec(leaf, &item->otime,
  3485. BTRFS_I(inode)->i_otime.tv_sec, &token);
  3486. btrfs_set_token_timespec_nsec(leaf, &item->otime,
  3487. BTRFS_I(inode)->i_otime.tv_nsec, &token);
  3488. btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
  3489. &token);
  3490. btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
  3491. &token);
  3492. btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
  3493. btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
  3494. btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
  3495. btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
  3496. btrfs_set_token_inode_block_group(leaf, item, 0, &token);
  3497. }
  3498. /*
  3499. * copy everything in the in-memory inode into the btree.
  3500. */
  3501. static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
  3502. struct btrfs_root *root, struct inode *inode)
  3503. {
  3504. struct btrfs_inode_item *inode_item;
  3505. struct btrfs_path *path;
  3506. struct extent_buffer *leaf;
  3507. int ret;
  3508. path = btrfs_alloc_path();
  3509. if (!path)
  3510. return -ENOMEM;
  3511. path->leave_spinning = 1;
  3512. ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
  3513. 1);
  3514. if (ret) {
  3515. if (ret > 0)
  3516. ret = -ENOENT;
  3517. goto failed;
  3518. }
  3519. leaf = path->nodes[0];
  3520. inode_item = btrfs_item_ptr(leaf, path->slots[0],
  3521. struct btrfs_inode_item);
  3522. fill_inode_item(trans, leaf, inode_item, inode);
  3523. btrfs_mark_buffer_dirty(leaf);
  3524. btrfs_set_inode_last_trans(trans, inode);
  3525. ret = 0;
  3526. failed:
  3527. btrfs_free_path(path);
  3528. return ret;
  3529. }
  3530. /*
  3531. * copy everything in the in-memory inode into the btree.
  3532. */
  3533. noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
  3534. struct btrfs_root *root, struct inode *inode)
  3535. {
  3536. struct btrfs_fs_info *fs_info = root->fs_info;
  3537. int ret;
  3538. /*
  3539. * If the inode is a free space inode, we can deadlock during commit
  3540. * if we put it into the delayed code.
  3541. *
  3542. * The data relocation inode should also be directly updated
  3543. * without delay
  3544. */
  3545. if (!btrfs_is_free_space_inode(BTRFS_I(inode))
  3546. && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
  3547. && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
  3548. btrfs_update_root_times(trans, root);
  3549. ret = btrfs_delayed_update_inode(trans, root, inode);
  3550. if (!ret)
  3551. btrfs_set_inode_last_trans(trans, inode);
  3552. return ret;
  3553. }
  3554. return btrfs_update_inode_item(trans, root, inode);
  3555. }
  3556. noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
  3557. struct btrfs_root *root,
  3558. struct inode *inode)
  3559. {
  3560. int ret;
  3561. ret = btrfs_update_inode(trans, root, inode);
  3562. if (ret == -ENOSPC)
  3563. return btrfs_update_inode_item(trans, root, inode);
  3564. return ret;
  3565. }
  3566. /*
  3567. * unlink helper that gets used here in inode.c and in the tree logging
  3568. * recovery code. It remove a link in a directory with a given name, and
  3569. * also drops the back refs in the inode to the directory
  3570. */
  3571. static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
  3572. struct btrfs_root *root,
  3573. struct btrfs_inode *dir,
  3574. struct btrfs_inode *inode,
  3575. const char *name, int name_len)
  3576. {
  3577. struct btrfs_fs_info *fs_info = root->fs_info;
  3578. struct btrfs_path *path;
  3579. int ret = 0;
  3580. struct extent_buffer *leaf;
  3581. struct btrfs_dir_item *di;
  3582. struct btrfs_key key;
  3583. u64 index;
  3584. u64 ino = btrfs_ino(inode);
  3585. u64 dir_ino = btrfs_ino(dir);
  3586. path = btrfs_alloc_path();
  3587. if (!path) {
  3588. ret = -ENOMEM;
  3589. goto out;
  3590. }
  3591. path->leave_spinning = 1;
  3592. di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
  3593. name, name_len, -1);
  3594. if (IS_ERR(di)) {
  3595. ret = PTR_ERR(di);
  3596. goto err;
  3597. }
  3598. if (!di) {
  3599. ret = -ENOENT;
  3600. goto err;
  3601. }
  3602. leaf = path->nodes[0];
  3603. btrfs_dir_item_key_to_cpu(leaf, di, &key);
  3604. ret = btrfs_delete_one_dir_name(trans, root, path, di);
  3605. if (ret)
  3606. goto err;
  3607. btrfs_release_path(path);
  3608. /*
  3609. * If we don't have dir index, we have to get it by looking up
  3610. * the inode ref, since we get the inode ref, remove it directly,
  3611. * it is unnecessary to do delayed deletion.
  3612. *
  3613. * But if we have dir index, needn't search inode ref to get it.
  3614. * Since the inode ref is close to the inode item, it is better
  3615. * that we delay to delete it, and just do this deletion when
  3616. * we update the inode item.
  3617. */
  3618. if (inode->dir_index) {
  3619. ret = btrfs_delayed_delete_inode_ref(inode);
  3620. if (!ret) {
  3621. index = inode->dir_index;
  3622. goto skip_backref;
  3623. }
  3624. }
  3625. ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
  3626. dir_ino, &index);
  3627. if (ret) {
  3628. btrfs_info(fs_info,
  3629. "failed to delete reference to %.*s, inode %llu parent %llu",
  3630. name_len, name, ino, dir_ino);
  3631. btrfs_abort_transaction(trans, ret);
  3632. goto err;
  3633. }
  3634. skip_backref:
  3635. ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
  3636. if (ret) {
  3637. btrfs_abort_transaction(trans, ret);
  3638. goto err;
  3639. }
  3640. ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
  3641. dir_ino);
  3642. if (ret != 0 && ret != -ENOENT) {
  3643. btrfs_abort_transaction(trans, ret);
  3644. goto err;
  3645. }
  3646. ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
  3647. index);
  3648. if (ret == -ENOENT)
  3649. ret = 0;
  3650. else if (ret)
  3651. btrfs_abort_transaction(trans, ret);
  3652. err:
  3653. btrfs_free_path(path);
  3654. if (ret)
  3655. goto out;
  3656. btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
  3657. inode_inc_iversion(&inode->vfs_inode);
  3658. inode_inc_iversion(&dir->vfs_inode);
  3659. inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
  3660. dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
  3661. ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
  3662. out:
  3663. return ret;
  3664. }
  3665. int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
  3666. struct btrfs_root *root,
  3667. struct btrfs_inode *dir, struct btrfs_inode *inode,
  3668. const char *name, int name_len)
  3669. {
  3670. int ret;
  3671. ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
  3672. if (!ret) {
  3673. drop_nlink(&inode->vfs_inode);
  3674. ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
  3675. }
  3676. return ret;
  3677. }
  3678. /*
  3679. * helper to start transaction for unlink and rmdir.
  3680. *
  3681. * unlink and rmdir are special in btrfs, they do not always free space, so
  3682. * if we cannot make our reservations the normal way try and see if there is
  3683. * plenty of slack room in the global reserve to migrate, otherwise we cannot
  3684. * allow the unlink to occur.
  3685. */
  3686. static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
  3687. {
  3688. struct btrfs_root *root = BTRFS_I(dir)->root;
  3689. /*
  3690. * 1 for the possible orphan item
  3691. * 1 for the dir item
  3692. * 1 for the dir index
  3693. * 1 for the inode ref
  3694. * 1 for the inode
  3695. */
  3696. return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
  3697. }
  3698. static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
  3699. {
  3700. struct btrfs_root *root = BTRFS_I(dir)->root;
  3701. struct btrfs_trans_handle *trans;
  3702. struct inode *inode = d_inode(dentry);
  3703. int ret;
  3704. trans = __unlink_start_trans(dir);
  3705. if (IS_ERR(trans))
  3706. return PTR_ERR(trans);
  3707. btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
  3708. 0);
  3709. ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
  3710. BTRFS_I(d_inode(dentry)), dentry->d_name.name,
  3711. dentry->d_name.len);
  3712. if (ret)
  3713. goto out;
  3714. if (inode->i_nlink == 0) {
  3715. ret = btrfs_orphan_add(trans, BTRFS_I(inode));
  3716. if (ret)
  3717. goto out;
  3718. }
  3719. out:
  3720. btrfs_end_transaction(trans);
  3721. btrfs_btree_balance_dirty(root->fs_info);
  3722. return ret;
  3723. }
  3724. int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
  3725. struct btrfs_root *root,
  3726. struct inode *dir, u64 objectid,
  3727. const char *name, int name_len)
  3728. {
  3729. struct btrfs_fs_info *fs_info = root->fs_info;
  3730. struct btrfs_path *path;
  3731. struct extent_buffer *leaf;
  3732. struct btrfs_dir_item *di;
  3733. struct btrfs_key key;
  3734. u64 index;
  3735. int ret;
  3736. u64 dir_ino = btrfs_ino(BTRFS_I(dir));
  3737. path = btrfs_alloc_path();
  3738. if (!path)
  3739. return -ENOMEM;
  3740. di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
  3741. name, name_len, -1);
  3742. if (IS_ERR_OR_NULL(di)) {
  3743. if (!di)
  3744. ret = -ENOENT;
  3745. else
  3746. ret = PTR_ERR(di);
  3747. goto out;
  3748. }
  3749. leaf = path->nodes[0];
  3750. btrfs_dir_item_key_to_cpu(leaf, di, &key);
  3751. WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
  3752. ret = btrfs_delete_one_dir_name(trans, root, path, di);
  3753. if (ret) {
  3754. btrfs_abort_transaction(trans, ret);
  3755. goto out;
  3756. }
  3757. btrfs_release_path(path);
  3758. ret = btrfs_del_root_ref(trans, fs_info, objectid,
  3759. root->root_key.objectid, dir_ino,
  3760. &index, name, name_len);
  3761. if (ret < 0) {
  3762. if (ret != -ENOENT) {
  3763. btrfs_abort_transaction(trans, ret);
  3764. goto out;
  3765. }
  3766. di = btrfs_search_dir_index_item(root, path, dir_ino,
  3767. name, name_len);
  3768. if (IS_ERR_OR_NULL(di)) {
  3769. if (!di)
  3770. ret = -ENOENT;
  3771. else
  3772. ret = PTR_ERR(di);
  3773. btrfs_abort_transaction(trans, ret);
  3774. goto out;
  3775. }
  3776. leaf = path->nodes[0];
  3777. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  3778. btrfs_release_path(path);
  3779. index = key.offset;
  3780. }
  3781. btrfs_release_path(path);
  3782. ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
  3783. if (ret) {
  3784. btrfs_abort_transaction(trans, ret);
  3785. goto out;
  3786. }
  3787. btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
  3788. inode_inc_iversion(dir);
  3789. dir->i_mtime = dir->i_ctime = current_time(dir);
  3790. ret = btrfs_update_inode_fallback(trans, root, dir);
  3791. if (ret)
  3792. btrfs_abort_transaction(trans, ret);
  3793. out:
  3794. btrfs_free_path(path);
  3795. return ret;
  3796. }
  3797. static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
  3798. {
  3799. struct inode *inode = d_inode(dentry);
  3800. int err = 0;
  3801. struct btrfs_root *root = BTRFS_I(dir)->root;
  3802. struct btrfs_trans_handle *trans;
  3803. u64 last_unlink_trans;
  3804. if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
  3805. return -ENOTEMPTY;
  3806. if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
  3807. return -EPERM;
  3808. trans = __unlink_start_trans(dir);
  3809. if (IS_ERR(trans))
  3810. return PTR_ERR(trans);
  3811. if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
  3812. err = btrfs_unlink_subvol(trans, root, dir,
  3813. BTRFS_I(inode)->location.objectid,
  3814. dentry->d_name.name,
  3815. dentry->d_name.len);
  3816. goto out;
  3817. }
  3818. err = btrfs_orphan_add(trans, BTRFS_I(inode));
  3819. if (err)
  3820. goto out;
  3821. last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
  3822. /* now the directory is empty */
  3823. err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
  3824. BTRFS_I(d_inode(dentry)), dentry->d_name.name,
  3825. dentry->d_name.len);
  3826. if (!err) {
  3827. btrfs_i_size_write(BTRFS_I(inode), 0);
  3828. /*
  3829. * Propagate the last_unlink_trans value of the deleted dir to
  3830. * its parent directory. This is to prevent an unrecoverable
  3831. * log tree in the case we do something like this:
  3832. * 1) create dir foo
  3833. * 2) create snapshot under dir foo
  3834. * 3) delete the snapshot
  3835. * 4) rmdir foo
  3836. * 5) mkdir foo
  3837. * 6) fsync foo or some file inside foo
  3838. */
  3839. if (last_unlink_trans >= trans->transid)
  3840. BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
  3841. }
  3842. out:
  3843. btrfs_end_transaction(trans);
  3844. btrfs_btree_balance_dirty(root->fs_info);
  3845. return err;
  3846. }
  3847. static int truncate_space_check(struct btrfs_trans_handle *trans,
  3848. struct btrfs_root *root,
  3849. u64 bytes_deleted)
  3850. {
  3851. struct btrfs_fs_info *fs_info = root->fs_info;
  3852. int ret;
  3853. /*
  3854. * This is only used to apply pressure to the enospc system, we don't
  3855. * intend to use this reservation at all.
  3856. */
  3857. bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
  3858. bytes_deleted *= fs_info->nodesize;
  3859. ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
  3860. bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
  3861. if (!ret) {
  3862. trace_btrfs_space_reservation(fs_info, "transaction",
  3863. trans->transid,
  3864. bytes_deleted, 1);
  3865. trans->bytes_reserved += bytes_deleted;
  3866. }
  3867. return ret;
  3868. }
  3869. /*
  3870. * Return this if we need to call truncate_block for the last bit of the
  3871. * truncate.
  3872. */
  3873. #define NEED_TRUNCATE_BLOCK 1
  3874. /*
  3875. * this can truncate away extent items, csum items and directory items.
  3876. * It starts at a high offset and removes keys until it can't find
  3877. * any higher than new_size
  3878. *
  3879. * csum items that cross the new i_size are truncated to the new size
  3880. * as well.
  3881. *
  3882. * min_type is the minimum key type to truncate down to. If set to 0, this
  3883. * will kill all the items on this inode, including the INODE_ITEM_KEY.
  3884. */
  3885. int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
  3886. struct btrfs_root *root,
  3887. struct inode *inode,
  3888. u64 new_size, u32 min_type)
  3889. {
  3890. struct btrfs_fs_info *fs_info = root->fs_info;
  3891. struct btrfs_path *path;
  3892. struct extent_buffer *leaf;
  3893. struct btrfs_file_extent_item *fi;
  3894. struct btrfs_key key;
  3895. struct btrfs_key found_key;
  3896. u64 extent_start = 0;
  3897. u64 extent_num_bytes = 0;
  3898. u64 extent_offset = 0;
  3899. u64 item_end = 0;
  3900. u64 last_size = new_size;
  3901. u32 found_type = (u8)-1;
  3902. int found_extent;
  3903. int del_item;
  3904. int pending_del_nr = 0;
  3905. int pending_del_slot = 0;
  3906. int extent_type = -1;
  3907. int ret;
  3908. int err = 0;
  3909. u64 ino = btrfs_ino(BTRFS_I(inode));
  3910. u64 bytes_deleted = 0;
  3911. bool be_nice = false;
  3912. bool should_throttle = false;
  3913. bool should_end = false;
  3914. BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
  3915. /*
  3916. * for non-free space inodes and ref cows, we want to back off from
  3917. * time to time
  3918. */
  3919. if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
  3920. test_bit(BTRFS_ROOT_REF_COWS, &root->state))
  3921. be_nice = true;
  3922. path = btrfs_alloc_path();
  3923. if (!path)
  3924. return -ENOMEM;
  3925. path->reada = READA_BACK;
  3926. /*
  3927. * We want to drop from the next block forward in case this new size is
  3928. * not block aligned since we will be keeping the last block of the
  3929. * extent just the way it is.
  3930. */
  3931. if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
  3932. root == fs_info->tree_root)
  3933. btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
  3934. fs_info->sectorsize),
  3935. (u64)-1, 0);
  3936. /*
  3937. * This function is also used to drop the items in the log tree before
  3938. * we relog the inode, so if root != BTRFS_I(inode)->root, it means
  3939. * it is used to drop the loged items. So we shouldn't kill the delayed
  3940. * items.
  3941. */
  3942. if (min_type == 0 && root == BTRFS_I(inode)->root)
  3943. btrfs_kill_delayed_inode_items(BTRFS_I(inode));
  3944. key.objectid = ino;
  3945. key.offset = (u64)-1;
  3946. key.type = (u8)-1;
  3947. search_again:
  3948. /*
  3949. * with a 16K leaf size and 128MB extents, you can actually queue
  3950. * up a huge file in a single leaf. Most of the time that
  3951. * bytes_deleted is > 0, it will be huge by the time we get here
  3952. */
  3953. if (be_nice && bytes_deleted > SZ_32M) {
  3954. if (btrfs_should_end_transaction(trans)) {
  3955. err = -EAGAIN;
  3956. goto error;
  3957. }
  3958. }
  3959. path->leave_spinning = 1;
  3960. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  3961. if (ret < 0) {
  3962. err = ret;
  3963. goto out;
  3964. }
  3965. if (ret > 0) {
  3966. /* there are no items in the tree for us to truncate, we're
  3967. * done
  3968. */
  3969. if (path->slots[0] == 0)
  3970. goto out;
  3971. path->slots[0]--;
  3972. }
  3973. while (1) {
  3974. fi = NULL;
  3975. leaf = path->nodes[0];
  3976. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  3977. found_type = found_key.type;
  3978. if (found_key.objectid != ino)
  3979. break;
  3980. if (found_type < min_type)
  3981. break;
  3982. item_end = found_key.offset;
  3983. if (found_type == BTRFS_EXTENT_DATA_KEY) {
  3984. fi = btrfs_item_ptr(leaf, path->slots[0],
  3985. struct btrfs_file_extent_item);
  3986. extent_type = btrfs_file_extent_type(leaf, fi);
  3987. if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
  3988. item_end +=
  3989. btrfs_file_extent_num_bytes(leaf, fi);
  3990. trace_btrfs_truncate_show_fi_regular(
  3991. BTRFS_I(inode), leaf, fi,
  3992. found_key.offset);
  3993. } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  3994. item_end += btrfs_file_extent_inline_len(leaf,
  3995. path->slots[0], fi);
  3996. trace_btrfs_truncate_show_fi_inline(
  3997. BTRFS_I(inode), leaf, fi, path->slots[0],
  3998. found_key.offset);
  3999. }
  4000. item_end--;
  4001. }
  4002. if (found_type > min_type) {
  4003. del_item = 1;
  4004. } else {
  4005. if (item_end < new_size)
  4006. break;
  4007. if (found_key.offset >= new_size)
  4008. del_item = 1;
  4009. else
  4010. del_item = 0;
  4011. }
  4012. found_extent = 0;
  4013. /* FIXME, shrink the extent if the ref count is only 1 */
  4014. if (found_type != BTRFS_EXTENT_DATA_KEY)
  4015. goto delete;
  4016. if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
  4017. u64 num_dec;
  4018. extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
  4019. if (!del_item) {
  4020. u64 orig_num_bytes =
  4021. btrfs_file_extent_num_bytes(leaf, fi);
  4022. extent_num_bytes = ALIGN(new_size -
  4023. found_key.offset,
  4024. fs_info->sectorsize);
  4025. btrfs_set_file_extent_num_bytes(leaf, fi,
  4026. extent_num_bytes);
  4027. num_dec = (orig_num_bytes -
  4028. extent_num_bytes);
  4029. if (test_bit(BTRFS_ROOT_REF_COWS,
  4030. &root->state) &&
  4031. extent_start != 0)
  4032. inode_sub_bytes(inode, num_dec);
  4033. btrfs_mark_buffer_dirty(leaf);
  4034. } else {
  4035. extent_num_bytes =
  4036. btrfs_file_extent_disk_num_bytes(leaf,
  4037. fi);
  4038. extent_offset = found_key.offset -
  4039. btrfs_file_extent_offset(leaf, fi);
  4040. /* FIXME blocksize != 4096 */
  4041. num_dec = btrfs_file_extent_num_bytes(leaf, fi);
  4042. if (extent_start != 0) {
  4043. found_extent = 1;
  4044. if (test_bit(BTRFS_ROOT_REF_COWS,
  4045. &root->state))
  4046. inode_sub_bytes(inode, num_dec);
  4047. }
  4048. }
  4049. } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  4050. /*
  4051. * we can't truncate inline items that have had
  4052. * special encodings
  4053. */
  4054. if (!del_item &&
  4055. btrfs_file_extent_encryption(leaf, fi) == 0 &&
  4056. btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
  4057. btrfs_file_extent_compression(leaf, fi) == 0) {
  4058. u32 size = (u32)(new_size - found_key.offset);
  4059. btrfs_set_file_extent_ram_bytes(leaf, fi, size);
  4060. size = btrfs_file_extent_calc_inline_size(size);
  4061. btrfs_truncate_item(root->fs_info, path, size, 1);
  4062. } else if (!del_item) {
  4063. /*
  4064. * We have to bail so the last_size is set to
  4065. * just before this extent.
  4066. */
  4067. err = NEED_TRUNCATE_BLOCK;
  4068. break;
  4069. }
  4070. if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
  4071. inode_sub_bytes(inode, item_end + 1 - new_size);
  4072. }
  4073. delete:
  4074. if (del_item)
  4075. last_size = found_key.offset;
  4076. else
  4077. last_size = new_size;
  4078. if (del_item) {
  4079. if (!pending_del_nr) {
  4080. /* no pending yet, add ourselves */
  4081. pending_del_slot = path->slots[0];
  4082. pending_del_nr = 1;
  4083. } else if (pending_del_nr &&
  4084. path->slots[0] + 1 == pending_del_slot) {
  4085. /* hop on the pending chunk */
  4086. pending_del_nr++;
  4087. pending_del_slot = path->slots[0];
  4088. } else {
  4089. BUG();
  4090. }
  4091. } else {
  4092. break;
  4093. }
  4094. should_throttle = false;
  4095. if (found_extent &&
  4096. (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
  4097. root == fs_info->tree_root)) {
  4098. btrfs_set_path_blocking(path);
  4099. bytes_deleted += extent_num_bytes;
  4100. ret = btrfs_free_extent(trans, root, extent_start,
  4101. extent_num_bytes, 0,
  4102. btrfs_header_owner(leaf),
  4103. ino, extent_offset);
  4104. BUG_ON(ret);
  4105. if (btrfs_should_throttle_delayed_refs(trans, fs_info))
  4106. btrfs_async_run_delayed_refs(fs_info,
  4107. trans->delayed_ref_updates * 2,
  4108. trans->transid, 0);
  4109. if (be_nice) {
  4110. if (truncate_space_check(trans, root,
  4111. extent_num_bytes)) {
  4112. should_end = true;
  4113. }
  4114. if (btrfs_should_throttle_delayed_refs(trans,
  4115. fs_info))
  4116. should_throttle = true;
  4117. }
  4118. }
  4119. if (found_type == BTRFS_INODE_ITEM_KEY)
  4120. break;
  4121. if (path->slots[0] == 0 ||
  4122. path->slots[0] != pending_del_slot ||
  4123. should_throttle || should_end) {
  4124. if (pending_del_nr) {
  4125. ret = btrfs_del_items(trans, root, path,
  4126. pending_del_slot,
  4127. pending_del_nr);
  4128. if (ret) {
  4129. btrfs_abort_transaction(trans, ret);
  4130. goto error;
  4131. }
  4132. pending_del_nr = 0;
  4133. }
  4134. btrfs_release_path(path);
  4135. if (should_throttle) {
  4136. unsigned long updates = trans->delayed_ref_updates;
  4137. if (updates) {
  4138. trans->delayed_ref_updates = 0;
  4139. ret = btrfs_run_delayed_refs(trans,
  4140. fs_info,
  4141. updates * 2);
  4142. if (ret && !err)
  4143. err = ret;
  4144. }
  4145. }
  4146. /*
  4147. * if we failed to refill our space rsv, bail out
  4148. * and let the transaction restart
  4149. */
  4150. if (should_end) {
  4151. err = -EAGAIN;
  4152. goto error;
  4153. }
  4154. goto search_again;
  4155. } else {
  4156. path->slots[0]--;
  4157. }
  4158. }
  4159. out:
  4160. if (pending_del_nr) {
  4161. ret = btrfs_del_items(trans, root, path, pending_del_slot,
  4162. pending_del_nr);
  4163. if (ret)
  4164. btrfs_abort_transaction(trans, ret);
  4165. }
  4166. error:
  4167. if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
  4168. ASSERT(last_size >= new_size);
  4169. if (!err && last_size > new_size)
  4170. last_size = new_size;
  4171. btrfs_ordered_update_i_size(inode, last_size, NULL);
  4172. }
  4173. btrfs_free_path(path);
  4174. if (be_nice && bytes_deleted > SZ_32M) {
  4175. unsigned long updates = trans->delayed_ref_updates;
  4176. if (updates) {
  4177. trans->delayed_ref_updates = 0;
  4178. ret = btrfs_run_delayed_refs(trans, fs_info,
  4179. updates * 2);
  4180. if (ret && !err)
  4181. err = ret;
  4182. }
  4183. }
  4184. return err;
  4185. }
  4186. /*
  4187. * btrfs_truncate_block - read, zero a chunk and write a block
  4188. * @inode - inode that we're zeroing
  4189. * @from - the offset to start zeroing
  4190. * @len - the length to zero, 0 to zero the entire range respective to the
  4191. * offset
  4192. * @front - zero up to the offset instead of from the offset on
  4193. *
  4194. * This will find the block for the "from" offset and cow the block and zero the
  4195. * part we want to zero. This is used with truncate and hole punching.
  4196. */
  4197. int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
  4198. int front)
  4199. {
  4200. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  4201. struct address_space *mapping = inode->i_mapping;
  4202. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  4203. struct btrfs_ordered_extent *ordered;
  4204. struct extent_state *cached_state = NULL;
  4205. struct extent_changeset *data_reserved = NULL;
  4206. char *kaddr;
  4207. u32 blocksize = fs_info->sectorsize;
  4208. pgoff_t index = from >> PAGE_SHIFT;
  4209. unsigned offset = from & (blocksize - 1);
  4210. struct page *page;
  4211. gfp_t mask = btrfs_alloc_write_mask(mapping);
  4212. int ret = 0;
  4213. u64 block_start;
  4214. u64 block_end;
  4215. if ((offset & (blocksize - 1)) == 0 &&
  4216. (!len || ((len & (blocksize - 1)) == 0)))
  4217. goto out;
  4218. block_start = round_down(from, blocksize);
  4219. block_end = block_start + blocksize - 1;
  4220. ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
  4221. block_start, blocksize);
  4222. if (ret)
  4223. goto out;
  4224. again:
  4225. page = find_or_create_page(mapping, index, mask);
  4226. if (!page) {
  4227. btrfs_delalloc_release_space(inode, data_reserved,
  4228. block_start, blocksize);
  4229. btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
  4230. ret = -ENOMEM;
  4231. goto out;
  4232. }
  4233. if (!PageUptodate(page)) {
  4234. ret = btrfs_readpage(NULL, page);
  4235. lock_page(page);
  4236. if (page->mapping != mapping) {
  4237. unlock_page(page);
  4238. put_page(page);
  4239. goto again;
  4240. }
  4241. if (!PageUptodate(page)) {
  4242. ret = -EIO;
  4243. goto out_unlock;
  4244. }
  4245. }
  4246. wait_on_page_writeback(page);
  4247. lock_extent_bits(io_tree, block_start, block_end, &cached_state);
  4248. set_page_extent_mapped(page);
  4249. ordered = btrfs_lookup_ordered_extent(inode, block_start);
  4250. if (ordered) {
  4251. unlock_extent_cached(io_tree, block_start, block_end,
  4252. &cached_state, GFP_NOFS);
  4253. unlock_page(page);
  4254. put_page(page);
  4255. btrfs_start_ordered_extent(inode, ordered, 1);
  4256. btrfs_put_ordered_extent(ordered);
  4257. goto again;
  4258. }
  4259. clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
  4260. EXTENT_DIRTY | EXTENT_DELALLOC |
  4261. EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
  4262. 0, 0, &cached_state);
  4263. ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
  4264. &cached_state, 0);
  4265. if (ret) {
  4266. unlock_extent_cached(io_tree, block_start, block_end,
  4267. &cached_state, GFP_NOFS);
  4268. goto out_unlock;
  4269. }
  4270. if (offset != blocksize) {
  4271. if (!len)
  4272. len = blocksize - offset;
  4273. kaddr = kmap(page);
  4274. if (front)
  4275. memset(kaddr + (block_start - page_offset(page)),
  4276. 0, offset);
  4277. else
  4278. memset(kaddr + (block_start - page_offset(page)) + offset,
  4279. 0, len);
  4280. flush_dcache_page(page);
  4281. kunmap(page);
  4282. }
  4283. ClearPageChecked(page);
  4284. set_page_dirty(page);
  4285. unlock_extent_cached(io_tree, block_start, block_end, &cached_state,
  4286. GFP_NOFS);
  4287. out_unlock:
  4288. if (ret)
  4289. btrfs_delalloc_release_space(inode, data_reserved, block_start,
  4290. blocksize);
  4291. btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
  4292. unlock_page(page);
  4293. put_page(page);
  4294. out:
  4295. extent_changeset_free(data_reserved);
  4296. return ret;
  4297. }
  4298. static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
  4299. u64 offset, u64 len)
  4300. {
  4301. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  4302. struct btrfs_trans_handle *trans;
  4303. int ret;
  4304. /*
  4305. * Still need to make sure the inode looks like it's been updated so
  4306. * that any holes get logged if we fsync.
  4307. */
  4308. if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
  4309. BTRFS_I(inode)->last_trans = fs_info->generation;
  4310. BTRFS_I(inode)->last_sub_trans = root->log_transid;
  4311. BTRFS_I(inode)->last_log_commit = root->last_log_commit;
  4312. return 0;
  4313. }
  4314. /*
  4315. * 1 - for the one we're dropping
  4316. * 1 - for the one we're adding
  4317. * 1 - for updating the inode.
  4318. */
  4319. trans = btrfs_start_transaction(root, 3);
  4320. if (IS_ERR(trans))
  4321. return PTR_ERR(trans);
  4322. ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
  4323. if (ret) {
  4324. btrfs_abort_transaction(trans, ret);
  4325. btrfs_end_transaction(trans);
  4326. return ret;
  4327. }
  4328. ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
  4329. offset, 0, 0, len, 0, len, 0, 0, 0);
  4330. if (ret)
  4331. btrfs_abort_transaction(trans, ret);
  4332. else
  4333. btrfs_update_inode(trans, root, inode);
  4334. btrfs_end_transaction(trans);
  4335. return ret;
  4336. }
  4337. /*
  4338. * This function puts in dummy file extents for the area we're creating a hole
  4339. * for. So if we are truncating this file to a larger size we need to insert
  4340. * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
  4341. * the range between oldsize and size
  4342. */
  4343. int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
  4344. {
  4345. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  4346. struct btrfs_root *root = BTRFS_I(inode)->root;
  4347. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  4348. struct extent_map *em = NULL;
  4349. struct extent_state *cached_state = NULL;
  4350. struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
  4351. u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
  4352. u64 block_end = ALIGN(size, fs_info->sectorsize);
  4353. u64 last_byte;
  4354. u64 cur_offset;
  4355. u64 hole_size;
  4356. int err = 0;
  4357. /*
  4358. * If our size started in the middle of a block we need to zero out the
  4359. * rest of the block before we expand the i_size, otherwise we could
  4360. * expose stale data.
  4361. */
  4362. err = btrfs_truncate_block(inode, oldsize, 0, 0);
  4363. if (err)
  4364. return err;
  4365. if (size <= hole_start)
  4366. return 0;
  4367. while (1) {
  4368. struct btrfs_ordered_extent *ordered;
  4369. lock_extent_bits(io_tree, hole_start, block_end - 1,
  4370. &cached_state);
  4371. ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
  4372. block_end - hole_start);
  4373. if (!ordered)
  4374. break;
  4375. unlock_extent_cached(io_tree, hole_start, block_end - 1,
  4376. &cached_state, GFP_NOFS);
  4377. btrfs_start_ordered_extent(inode, ordered, 1);
  4378. btrfs_put_ordered_extent(ordered);
  4379. }
  4380. cur_offset = hole_start;
  4381. while (1) {
  4382. em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
  4383. block_end - cur_offset, 0);
  4384. if (IS_ERR(em)) {
  4385. err = PTR_ERR(em);
  4386. em = NULL;
  4387. break;
  4388. }
  4389. last_byte = min(extent_map_end(em), block_end);
  4390. last_byte = ALIGN(last_byte, fs_info->sectorsize);
  4391. if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
  4392. struct extent_map *hole_em;
  4393. hole_size = last_byte - cur_offset;
  4394. err = maybe_insert_hole(root, inode, cur_offset,
  4395. hole_size);
  4396. if (err)
  4397. break;
  4398. btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
  4399. cur_offset + hole_size - 1, 0);
  4400. hole_em = alloc_extent_map();
  4401. if (!hole_em) {
  4402. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  4403. &BTRFS_I(inode)->runtime_flags);
  4404. goto next;
  4405. }
  4406. hole_em->start = cur_offset;
  4407. hole_em->len = hole_size;
  4408. hole_em->orig_start = cur_offset;
  4409. hole_em->block_start = EXTENT_MAP_HOLE;
  4410. hole_em->block_len = 0;
  4411. hole_em->orig_block_len = 0;
  4412. hole_em->ram_bytes = hole_size;
  4413. hole_em->bdev = fs_info->fs_devices->latest_bdev;
  4414. hole_em->compress_type = BTRFS_COMPRESS_NONE;
  4415. hole_em->generation = fs_info->generation;
  4416. while (1) {
  4417. write_lock(&em_tree->lock);
  4418. err = add_extent_mapping(em_tree, hole_em, 1);
  4419. write_unlock(&em_tree->lock);
  4420. if (err != -EEXIST)
  4421. break;
  4422. btrfs_drop_extent_cache(BTRFS_I(inode),
  4423. cur_offset,
  4424. cur_offset +
  4425. hole_size - 1, 0);
  4426. }
  4427. free_extent_map(hole_em);
  4428. }
  4429. next:
  4430. free_extent_map(em);
  4431. em = NULL;
  4432. cur_offset = last_byte;
  4433. if (cur_offset >= block_end)
  4434. break;
  4435. }
  4436. free_extent_map(em);
  4437. unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
  4438. GFP_NOFS);
  4439. return err;
  4440. }
  4441. static int btrfs_setsize(struct inode *inode, struct iattr *attr)
  4442. {
  4443. struct btrfs_root *root = BTRFS_I(inode)->root;
  4444. struct btrfs_trans_handle *trans;
  4445. loff_t oldsize = i_size_read(inode);
  4446. loff_t newsize = attr->ia_size;
  4447. int mask = attr->ia_valid;
  4448. int ret;
  4449. /*
  4450. * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
  4451. * special case where we need to update the times despite not having
  4452. * these flags set. For all other operations the VFS set these flags
  4453. * explicitly if it wants a timestamp update.
  4454. */
  4455. if (newsize != oldsize) {
  4456. inode_inc_iversion(inode);
  4457. if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
  4458. inode->i_ctime = inode->i_mtime =
  4459. current_time(inode);
  4460. }
  4461. if (newsize > oldsize) {
  4462. /*
  4463. * Don't do an expanding truncate while snapshotting is ongoing.
  4464. * This is to ensure the snapshot captures a fully consistent
  4465. * state of this file - if the snapshot captures this expanding
  4466. * truncation, it must capture all writes that happened before
  4467. * this truncation.
  4468. */
  4469. btrfs_wait_for_snapshot_creation(root);
  4470. ret = btrfs_cont_expand(inode, oldsize, newsize);
  4471. if (ret) {
  4472. btrfs_end_write_no_snapshotting(root);
  4473. return ret;
  4474. }
  4475. trans = btrfs_start_transaction(root, 1);
  4476. if (IS_ERR(trans)) {
  4477. btrfs_end_write_no_snapshotting(root);
  4478. return PTR_ERR(trans);
  4479. }
  4480. i_size_write(inode, newsize);
  4481. btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
  4482. pagecache_isize_extended(inode, oldsize, newsize);
  4483. ret = btrfs_update_inode(trans, root, inode);
  4484. btrfs_end_write_no_snapshotting(root);
  4485. btrfs_end_transaction(trans);
  4486. } else {
  4487. /*
  4488. * We're truncating a file that used to have good data down to
  4489. * zero. Make sure it gets into the ordered flush list so that
  4490. * any new writes get down to disk quickly.
  4491. */
  4492. if (newsize == 0)
  4493. set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
  4494. &BTRFS_I(inode)->runtime_flags);
  4495. /*
  4496. * 1 for the orphan item we're going to add
  4497. * 1 for the orphan item deletion.
  4498. */
  4499. trans = btrfs_start_transaction(root, 2);
  4500. if (IS_ERR(trans))
  4501. return PTR_ERR(trans);
  4502. /*
  4503. * We need to do this in case we fail at _any_ point during the
  4504. * actual truncate. Once we do the truncate_setsize we could
  4505. * invalidate pages which forces any outstanding ordered io to
  4506. * be instantly completed which will give us extents that need
  4507. * to be truncated. If we fail to get an orphan inode down we
  4508. * could have left over extents that were never meant to live,
  4509. * so we need to guarantee from this point on that everything
  4510. * will be consistent.
  4511. */
  4512. ret = btrfs_orphan_add(trans, BTRFS_I(inode));
  4513. btrfs_end_transaction(trans);
  4514. if (ret)
  4515. return ret;
  4516. /* we don't support swapfiles, so vmtruncate shouldn't fail */
  4517. truncate_setsize(inode, newsize);
  4518. /* Disable nonlocked read DIO to avoid the end less truncate */
  4519. btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
  4520. inode_dio_wait(inode);
  4521. btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
  4522. ret = btrfs_truncate(inode);
  4523. if (ret && inode->i_nlink) {
  4524. int err;
  4525. /* To get a stable disk_i_size */
  4526. err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
  4527. if (err) {
  4528. btrfs_orphan_del(NULL, BTRFS_I(inode));
  4529. return err;
  4530. }
  4531. /*
  4532. * failed to truncate, disk_i_size is only adjusted down
  4533. * as we remove extents, so it should represent the true
  4534. * size of the inode, so reset the in memory size and
  4535. * delete our orphan entry.
  4536. */
  4537. trans = btrfs_join_transaction(root);
  4538. if (IS_ERR(trans)) {
  4539. btrfs_orphan_del(NULL, BTRFS_I(inode));
  4540. return ret;
  4541. }
  4542. i_size_write(inode, BTRFS_I(inode)->disk_i_size);
  4543. err = btrfs_orphan_del(trans, BTRFS_I(inode));
  4544. if (err)
  4545. btrfs_abort_transaction(trans, err);
  4546. btrfs_end_transaction(trans);
  4547. }
  4548. }
  4549. return ret;
  4550. }
  4551. static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
  4552. {
  4553. struct inode *inode = d_inode(dentry);
  4554. struct btrfs_root *root = BTRFS_I(inode)->root;
  4555. int err;
  4556. if (btrfs_root_readonly(root))
  4557. return -EROFS;
  4558. err = setattr_prepare(dentry, attr);
  4559. if (err)
  4560. return err;
  4561. if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
  4562. err = btrfs_setsize(inode, attr);
  4563. if (err)
  4564. return err;
  4565. }
  4566. if (attr->ia_valid) {
  4567. setattr_copy(inode, attr);
  4568. inode_inc_iversion(inode);
  4569. err = btrfs_dirty_inode(inode);
  4570. if (!err && attr->ia_valid & ATTR_MODE)
  4571. err = posix_acl_chmod(inode, inode->i_mode);
  4572. }
  4573. return err;
  4574. }
  4575. /*
  4576. * While truncating the inode pages during eviction, we get the VFS calling
  4577. * btrfs_invalidatepage() against each page of the inode. This is slow because
  4578. * the calls to btrfs_invalidatepage() result in a huge amount of calls to
  4579. * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
  4580. * extent_state structures over and over, wasting lots of time.
  4581. *
  4582. * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
  4583. * those expensive operations on a per page basis and do only the ordered io
  4584. * finishing, while we release here the extent_map and extent_state structures,
  4585. * without the excessive merging and splitting.
  4586. */
  4587. static void evict_inode_truncate_pages(struct inode *inode)
  4588. {
  4589. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  4590. struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
  4591. struct rb_node *node;
  4592. ASSERT(inode->i_state & I_FREEING);
  4593. truncate_inode_pages_final(&inode->i_data);
  4594. write_lock(&map_tree->lock);
  4595. while (!RB_EMPTY_ROOT(&map_tree->map)) {
  4596. struct extent_map *em;
  4597. node = rb_first(&map_tree->map);
  4598. em = rb_entry(node, struct extent_map, rb_node);
  4599. clear_bit(EXTENT_FLAG_PINNED, &em->flags);
  4600. clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
  4601. remove_extent_mapping(map_tree, em);
  4602. free_extent_map(em);
  4603. if (need_resched()) {
  4604. write_unlock(&map_tree->lock);
  4605. cond_resched();
  4606. write_lock(&map_tree->lock);
  4607. }
  4608. }
  4609. write_unlock(&map_tree->lock);
  4610. /*
  4611. * Keep looping until we have no more ranges in the io tree.
  4612. * We can have ongoing bios started by readpages (called from readahead)
  4613. * that have their endio callback (extent_io.c:end_bio_extent_readpage)
  4614. * still in progress (unlocked the pages in the bio but did not yet
  4615. * unlocked the ranges in the io tree). Therefore this means some
  4616. * ranges can still be locked and eviction started because before
  4617. * submitting those bios, which are executed by a separate task (work
  4618. * queue kthread), inode references (inode->i_count) were not taken
  4619. * (which would be dropped in the end io callback of each bio).
  4620. * Therefore here we effectively end up waiting for those bios and
  4621. * anyone else holding locked ranges without having bumped the inode's
  4622. * reference count - if we don't do it, when they access the inode's
  4623. * io_tree to unlock a range it may be too late, leading to an
  4624. * use-after-free issue.
  4625. */
  4626. spin_lock(&io_tree->lock);
  4627. while (!RB_EMPTY_ROOT(&io_tree->state)) {
  4628. struct extent_state *state;
  4629. struct extent_state *cached_state = NULL;
  4630. u64 start;
  4631. u64 end;
  4632. node = rb_first(&io_tree->state);
  4633. state = rb_entry(node, struct extent_state, rb_node);
  4634. start = state->start;
  4635. end = state->end;
  4636. spin_unlock(&io_tree->lock);
  4637. lock_extent_bits(io_tree, start, end, &cached_state);
  4638. /*
  4639. * If still has DELALLOC flag, the extent didn't reach disk,
  4640. * and its reserved space won't be freed by delayed_ref.
  4641. * So we need to free its reserved space here.
  4642. * (Refer to comment in btrfs_invalidatepage, case 2)
  4643. *
  4644. * Note, end is the bytenr of last byte, so we need + 1 here.
  4645. */
  4646. if (state->state & EXTENT_DELALLOC)
  4647. btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
  4648. clear_extent_bit(io_tree, start, end,
  4649. EXTENT_LOCKED | EXTENT_DIRTY |
  4650. EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
  4651. EXTENT_DEFRAG, 1, 1, &cached_state);
  4652. cond_resched();
  4653. spin_lock(&io_tree->lock);
  4654. }
  4655. spin_unlock(&io_tree->lock);
  4656. }
  4657. void btrfs_evict_inode(struct inode *inode)
  4658. {
  4659. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  4660. struct btrfs_trans_handle *trans;
  4661. struct btrfs_root *root = BTRFS_I(inode)->root;
  4662. struct btrfs_block_rsv *rsv, *global_rsv;
  4663. int steal_from_global = 0;
  4664. u64 min_size;
  4665. int ret;
  4666. trace_btrfs_inode_evict(inode);
  4667. if (!root) {
  4668. kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
  4669. return;
  4670. }
  4671. min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
  4672. evict_inode_truncate_pages(inode);
  4673. if (inode->i_nlink &&
  4674. ((btrfs_root_refs(&root->root_item) != 0 &&
  4675. root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
  4676. btrfs_is_free_space_inode(BTRFS_I(inode))))
  4677. goto no_delete;
  4678. if (is_bad_inode(inode)) {
  4679. btrfs_orphan_del(NULL, BTRFS_I(inode));
  4680. goto no_delete;
  4681. }
  4682. /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
  4683. if (!special_file(inode->i_mode))
  4684. btrfs_wait_ordered_range(inode, 0, (u64)-1);
  4685. btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
  4686. if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
  4687. BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
  4688. &BTRFS_I(inode)->runtime_flags));
  4689. goto no_delete;
  4690. }
  4691. if (inode->i_nlink > 0) {
  4692. BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
  4693. root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
  4694. goto no_delete;
  4695. }
  4696. ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
  4697. if (ret) {
  4698. btrfs_orphan_del(NULL, BTRFS_I(inode));
  4699. goto no_delete;
  4700. }
  4701. rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
  4702. if (!rsv) {
  4703. btrfs_orphan_del(NULL, BTRFS_I(inode));
  4704. goto no_delete;
  4705. }
  4706. rsv->size = min_size;
  4707. rsv->failfast = 1;
  4708. global_rsv = &fs_info->global_block_rsv;
  4709. btrfs_i_size_write(BTRFS_I(inode), 0);
  4710. /*
  4711. * This is a bit simpler than btrfs_truncate since we've already
  4712. * reserved our space for our orphan item in the unlink, so we just
  4713. * need to reserve some slack space in case we add bytes and update
  4714. * inode item when doing the truncate.
  4715. */
  4716. while (1) {
  4717. ret = btrfs_block_rsv_refill(root, rsv, min_size,
  4718. BTRFS_RESERVE_FLUSH_LIMIT);
  4719. /*
  4720. * Try and steal from the global reserve since we will
  4721. * likely not use this space anyway, we want to try as
  4722. * hard as possible to get this to work.
  4723. */
  4724. if (ret)
  4725. steal_from_global++;
  4726. else
  4727. steal_from_global = 0;
  4728. ret = 0;
  4729. /*
  4730. * steal_from_global == 0: we reserved stuff, hooray!
  4731. * steal_from_global == 1: we didn't reserve stuff, boo!
  4732. * steal_from_global == 2: we've committed, still not a lot of
  4733. * room but maybe we'll have room in the global reserve this
  4734. * time.
  4735. * steal_from_global == 3: abandon all hope!
  4736. */
  4737. if (steal_from_global > 2) {
  4738. btrfs_warn(fs_info,
  4739. "Could not get space for a delete, will truncate on mount %d",
  4740. ret);
  4741. btrfs_orphan_del(NULL, BTRFS_I(inode));
  4742. btrfs_free_block_rsv(fs_info, rsv);
  4743. goto no_delete;
  4744. }
  4745. trans = btrfs_join_transaction(root);
  4746. if (IS_ERR(trans)) {
  4747. btrfs_orphan_del(NULL, BTRFS_I(inode));
  4748. btrfs_free_block_rsv(fs_info, rsv);
  4749. goto no_delete;
  4750. }
  4751. /*
  4752. * We can't just steal from the global reserve, we need to make
  4753. * sure there is room to do it, if not we need to commit and try
  4754. * again.
  4755. */
  4756. if (steal_from_global) {
  4757. if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
  4758. ret = btrfs_block_rsv_migrate(global_rsv, rsv,
  4759. min_size, 0);
  4760. else
  4761. ret = -ENOSPC;
  4762. }
  4763. /*
  4764. * Couldn't steal from the global reserve, we have too much
  4765. * pending stuff built up, commit the transaction and try it
  4766. * again.
  4767. */
  4768. if (ret) {
  4769. ret = btrfs_commit_transaction(trans);
  4770. if (ret) {
  4771. btrfs_orphan_del(NULL, BTRFS_I(inode));
  4772. btrfs_free_block_rsv(fs_info, rsv);
  4773. goto no_delete;
  4774. }
  4775. continue;
  4776. } else {
  4777. steal_from_global = 0;
  4778. }
  4779. trans->block_rsv = rsv;
  4780. ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
  4781. if (ret != -ENOSPC && ret != -EAGAIN)
  4782. break;
  4783. trans->block_rsv = &fs_info->trans_block_rsv;
  4784. btrfs_end_transaction(trans);
  4785. trans = NULL;
  4786. btrfs_btree_balance_dirty(fs_info);
  4787. }
  4788. btrfs_free_block_rsv(fs_info, rsv);
  4789. /*
  4790. * Errors here aren't a big deal, it just means we leave orphan items
  4791. * in the tree. They will be cleaned up on the next mount.
  4792. */
  4793. if (ret == 0) {
  4794. trans->block_rsv = root->orphan_block_rsv;
  4795. btrfs_orphan_del(trans, BTRFS_I(inode));
  4796. } else {
  4797. btrfs_orphan_del(NULL, BTRFS_I(inode));
  4798. }
  4799. trans->block_rsv = &fs_info->trans_block_rsv;
  4800. if (!(root == fs_info->tree_root ||
  4801. root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
  4802. btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
  4803. btrfs_end_transaction(trans);
  4804. btrfs_btree_balance_dirty(fs_info);
  4805. no_delete:
  4806. btrfs_remove_delayed_node(BTRFS_I(inode));
  4807. clear_inode(inode);
  4808. }
  4809. /*
  4810. * this returns the key found in the dir entry in the location pointer.
  4811. * If no dir entries were found, location->objectid is 0.
  4812. */
  4813. static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
  4814. struct btrfs_key *location)
  4815. {
  4816. const char *name = dentry->d_name.name;
  4817. int namelen = dentry->d_name.len;
  4818. struct btrfs_dir_item *di;
  4819. struct btrfs_path *path;
  4820. struct btrfs_root *root = BTRFS_I(dir)->root;
  4821. int ret = 0;
  4822. path = btrfs_alloc_path();
  4823. if (!path)
  4824. return -ENOMEM;
  4825. di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
  4826. name, namelen, 0);
  4827. if (IS_ERR(di))
  4828. ret = PTR_ERR(di);
  4829. if (IS_ERR_OR_NULL(di))
  4830. goto out_err;
  4831. btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
  4832. if (location->type != BTRFS_INODE_ITEM_KEY &&
  4833. location->type != BTRFS_ROOT_ITEM_KEY) {
  4834. btrfs_warn(root->fs_info,
  4835. "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
  4836. __func__, name, btrfs_ino(BTRFS_I(dir)),
  4837. location->objectid, location->type, location->offset);
  4838. goto out_err;
  4839. }
  4840. out:
  4841. btrfs_free_path(path);
  4842. return ret;
  4843. out_err:
  4844. location->objectid = 0;
  4845. goto out;
  4846. }
  4847. /*
  4848. * when we hit a tree root in a directory, the btrfs part of the inode
  4849. * needs to be changed to reflect the root directory of the tree root. This
  4850. * is kind of like crossing a mount point.
  4851. */
  4852. static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
  4853. struct inode *dir,
  4854. struct dentry *dentry,
  4855. struct btrfs_key *location,
  4856. struct btrfs_root **sub_root)
  4857. {
  4858. struct btrfs_path *path;
  4859. struct btrfs_root *new_root;
  4860. struct btrfs_root_ref *ref;
  4861. struct extent_buffer *leaf;
  4862. struct btrfs_key key;
  4863. int ret;
  4864. int err = 0;
  4865. path = btrfs_alloc_path();
  4866. if (!path) {
  4867. err = -ENOMEM;
  4868. goto out;
  4869. }
  4870. err = -ENOENT;
  4871. key.objectid = BTRFS_I(dir)->root->root_key.objectid;
  4872. key.type = BTRFS_ROOT_REF_KEY;
  4873. key.offset = location->objectid;
  4874. ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
  4875. if (ret) {
  4876. if (ret < 0)
  4877. err = ret;
  4878. goto out;
  4879. }
  4880. leaf = path->nodes[0];
  4881. ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
  4882. if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
  4883. btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
  4884. goto out;
  4885. ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
  4886. (unsigned long)(ref + 1),
  4887. dentry->d_name.len);
  4888. if (ret)
  4889. goto out;
  4890. btrfs_release_path(path);
  4891. new_root = btrfs_read_fs_root_no_name(fs_info, location);
  4892. if (IS_ERR(new_root)) {
  4893. err = PTR_ERR(new_root);
  4894. goto out;
  4895. }
  4896. *sub_root = new_root;
  4897. location->objectid = btrfs_root_dirid(&new_root->root_item);
  4898. location->type = BTRFS_INODE_ITEM_KEY;
  4899. location->offset = 0;
  4900. err = 0;
  4901. out:
  4902. btrfs_free_path(path);
  4903. return err;
  4904. }
  4905. static void inode_tree_add(struct inode *inode)
  4906. {
  4907. struct btrfs_root *root = BTRFS_I(inode)->root;
  4908. struct btrfs_inode *entry;
  4909. struct rb_node **p;
  4910. struct rb_node *parent;
  4911. struct rb_node *new = &BTRFS_I(inode)->rb_node;
  4912. u64 ino = btrfs_ino(BTRFS_I(inode));
  4913. if (inode_unhashed(inode))
  4914. return;
  4915. parent = NULL;
  4916. spin_lock(&root->inode_lock);
  4917. p = &root->inode_tree.rb_node;
  4918. while (*p) {
  4919. parent = *p;
  4920. entry = rb_entry(parent, struct btrfs_inode, rb_node);
  4921. if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
  4922. p = &parent->rb_left;
  4923. else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
  4924. p = &parent->rb_right;
  4925. else {
  4926. WARN_ON(!(entry->vfs_inode.i_state &
  4927. (I_WILL_FREE | I_FREEING)));
  4928. rb_replace_node(parent, new, &root->inode_tree);
  4929. RB_CLEAR_NODE(parent);
  4930. spin_unlock(&root->inode_lock);
  4931. return;
  4932. }
  4933. }
  4934. rb_link_node(new, parent, p);
  4935. rb_insert_color(new, &root->inode_tree);
  4936. spin_unlock(&root->inode_lock);
  4937. }
  4938. static void inode_tree_del(struct inode *inode)
  4939. {
  4940. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  4941. struct btrfs_root *root = BTRFS_I(inode)->root;
  4942. int empty = 0;
  4943. spin_lock(&root->inode_lock);
  4944. if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
  4945. rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
  4946. RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
  4947. empty = RB_EMPTY_ROOT(&root->inode_tree);
  4948. }
  4949. spin_unlock(&root->inode_lock);
  4950. if (empty && btrfs_root_refs(&root->root_item) == 0) {
  4951. synchronize_srcu(&fs_info->subvol_srcu);
  4952. spin_lock(&root->inode_lock);
  4953. empty = RB_EMPTY_ROOT(&root->inode_tree);
  4954. spin_unlock(&root->inode_lock);
  4955. if (empty)
  4956. btrfs_add_dead_root(root);
  4957. }
  4958. }
  4959. void btrfs_invalidate_inodes(struct btrfs_root *root)
  4960. {
  4961. struct btrfs_fs_info *fs_info = root->fs_info;
  4962. struct rb_node *node;
  4963. struct rb_node *prev;
  4964. struct btrfs_inode *entry;
  4965. struct inode *inode;
  4966. u64 objectid = 0;
  4967. if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
  4968. WARN_ON(btrfs_root_refs(&root->root_item) != 0);
  4969. spin_lock(&root->inode_lock);
  4970. again:
  4971. node = root->inode_tree.rb_node;
  4972. prev = NULL;
  4973. while (node) {
  4974. prev = node;
  4975. entry = rb_entry(node, struct btrfs_inode, rb_node);
  4976. if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
  4977. node = node->rb_left;
  4978. else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
  4979. node = node->rb_right;
  4980. else
  4981. break;
  4982. }
  4983. if (!node) {
  4984. while (prev) {
  4985. entry = rb_entry(prev, struct btrfs_inode, rb_node);
  4986. if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
  4987. node = prev;
  4988. break;
  4989. }
  4990. prev = rb_next(prev);
  4991. }
  4992. }
  4993. while (node) {
  4994. entry = rb_entry(node, struct btrfs_inode, rb_node);
  4995. objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
  4996. inode = igrab(&entry->vfs_inode);
  4997. if (inode) {
  4998. spin_unlock(&root->inode_lock);
  4999. if (atomic_read(&inode->i_count) > 1)
  5000. d_prune_aliases(inode);
  5001. /*
  5002. * btrfs_drop_inode will have it removed from
  5003. * the inode cache when its usage count
  5004. * hits zero.
  5005. */
  5006. iput(inode);
  5007. cond_resched();
  5008. spin_lock(&root->inode_lock);
  5009. goto again;
  5010. }
  5011. if (cond_resched_lock(&root->inode_lock))
  5012. goto again;
  5013. node = rb_next(node);
  5014. }
  5015. spin_unlock(&root->inode_lock);
  5016. }
  5017. static int btrfs_init_locked_inode(struct inode *inode, void *p)
  5018. {
  5019. struct btrfs_iget_args *args = p;
  5020. inode->i_ino = args->location->objectid;
  5021. memcpy(&BTRFS_I(inode)->location, args->location,
  5022. sizeof(*args->location));
  5023. BTRFS_I(inode)->root = args->root;
  5024. return 0;
  5025. }
  5026. static int btrfs_find_actor(struct inode *inode, void *opaque)
  5027. {
  5028. struct btrfs_iget_args *args = opaque;
  5029. return args->location->objectid == BTRFS_I(inode)->location.objectid &&
  5030. args->root == BTRFS_I(inode)->root;
  5031. }
  5032. static struct inode *btrfs_iget_locked(struct super_block *s,
  5033. struct btrfs_key *location,
  5034. struct btrfs_root *root)
  5035. {
  5036. struct inode *inode;
  5037. struct btrfs_iget_args args;
  5038. unsigned long hashval = btrfs_inode_hash(location->objectid, root);
  5039. args.location = location;
  5040. args.root = root;
  5041. inode = iget5_locked(s, hashval, btrfs_find_actor,
  5042. btrfs_init_locked_inode,
  5043. (void *)&args);
  5044. return inode;
  5045. }
  5046. /* Get an inode object given its location and corresponding root.
  5047. * Returns in *is_new if the inode was read from disk
  5048. */
  5049. struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
  5050. struct btrfs_root *root, int *new)
  5051. {
  5052. struct inode *inode;
  5053. inode = btrfs_iget_locked(s, location, root);
  5054. if (!inode)
  5055. return ERR_PTR(-ENOMEM);
  5056. if (inode->i_state & I_NEW) {
  5057. int ret;
  5058. ret = btrfs_read_locked_inode(inode);
  5059. if (!is_bad_inode(inode)) {
  5060. inode_tree_add(inode);
  5061. unlock_new_inode(inode);
  5062. if (new)
  5063. *new = 1;
  5064. } else {
  5065. unlock_new_inode(inode);
  5066. iput(inode);
  5067. ASSERT(ret < 0);
  5068. inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
  5069. }
  5070. }
  5071. return inode;
  5072. }
  5073. static struct inode *new_simple_dir(struct super_block *s,
  5074. struct btrfs_key *key,
  5075. struct btrfs_root *root)
  5076. {
  5077. struct inode *inode = new_inode(s);
  5078. if (!inode)
  5079. return ERR_PTR(-ENOMEM);
  5080. BTRFS_I(inode)->root = root;
  5081. memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
  5082. set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
  5083. inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
  5084. inode->i_op = &btrfs_dir_ro_inode_operations;
  5085. inode->i_opflags &= ~IOP_XATTR;
  5086. inode->i_fop = &simple_dir_operations;
  5087. inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
  5088. inode->i_mtime = current_time(inode);
  5089. inode->i_atime = inode->i_mtime;
  5090. inode->i_ctime = inode->i_mtime;
  5091. BTRFS_I(inode)->i_otime = inode->i_mtime;
  5092. return inode;
  5093. }
  5094. struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
  5095. {
  5096. struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
  5097. struct inode *inode;
  5098. struct btrfs_root *root = BTRFS_I(dir)->root;
  5099. struct btrfs_root *sub_root = root;
  5100. struct btrfs_key location;
  5101. int index;
  5102. int ret = 0;
  5103. if (dentry->d_name.len > BTRFS_NAME_LEN)
  5104. return ERR_PTR(-ENAMETOOLONG);
  5105. ret = btrfs_inode_by_name(dir, dentry, &location);
  5106. if (ret < 0)
  5107. return ERR_PTR(ret);
  5108. if (location.objectid == 0)
  5109. return ERR_PTR(-ENOENT);
  5110. if (location.type == BTRFS_INODE_ITEM_KEY) {
  5111. inode = btrfs_iget(dir->i_sb, &location, root, NULL);
  5112. return inode;
  5113. }
  5114. index = srcu_read_lock(&fs_info->subvol_srcu);
  5115. ret = fixup_tree_root_location(fs_info, dir, dentry,
  5116. &location, &sub_root);
  5117. if (ret < 0) {
  5118. if (ret != -ENOENT)
  5119. inode = ERR_PTR(ret);
  5120. else
  5121. inode = new_simple_dir(dir->i_sb, &location, sub_root);
  5122. } else {
  5123. inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
  5124. }
  5125. srcu_read_unlock(&fs_info->subvol_srcu, index);
  5126. if (!IS_ERR(inode) && root != sub_root) {
  5127. down_read(&fs_info->cleanup_work_sem);
  5128. if (!sb_rdonly(inode->i_sb))
  5129. ret = btrfs_orphan_cleanup(sub_root);
  5130. up_read(&fs_info->cleanup_work_sem);
  5131. if (ret) {
  5132. iput(inode);
  5133. inode = ERR_PTR(ret);
  5134. }
  5135. }
  5136. return inode;
  5137. }
  5138. static int btrfs_dentry_delete(const struct dentry *dentry)
  5139. {
  5140. struct btrfs_root *root;
  5141. struct inode *inode = d_inode(dentry);
  5142. if (!inode && !IS_ROOT(dentry))
  5143. inode = d_inode(dentry->d_parent);
  5144. if (inode) {
  5145. root = BTRFS_I(inode)->root;
  5146. if (btrfs_root_refs(&root->root_item) == 0)
  5147. return 1;
  5148. if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
  5149. return 1;
  5150. }
  5151. return 0;
  5152. }
  5153. static void btrfs_dentry_release(struct dentry *dentry)
  5154. {
  5155. kfree(dentry->d_fsdata);
  5156. }
  5157. static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
  5158. unsigned int flags)
  5159. {
  5160. struct inode *inode;
  5161. inode = btrfs_lookup_dentry(dir, dentry);
  5162. if (IS_ERR(inode)) {
  5163. if (PTR_ERR(inode) == -ENOENT)
  5164. inode = NULL;
  5165. else
  5166. return ERR_CAST(inode);
  5167. }
  5168. return d_splice_alias(inode, dentry);
  5169. }
  5170. unsigned char btrfs_filetype_table[] = {
  5171. DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
  5172. };
  5173. /*
  5174. * All this infrastructure exists because dir_emit can fault, and we are holding
  5175. * the tree lock when doing readdir. For now just allocate a buffer and copy
  5176. * our information into that, and then dir_emit from the buffer. This is
  5177. * similar to what NFS does, only we don't keep the buffer around in pagecache
  5178. * because I'm afraid I'll mess that up. Long term we need to make filldir do
  5179. * copy_to_user_inatomic so we don't have to worry about page faulting under the
  5180. * tree lock.
  5181. */
  5182. static int btrfs_opendir(struct inode *inode, struct file *file)
  5183. {
  5184. struct btrfs_file_private *private;
  5185. private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
  5186. if (!private)
  5187. return -ENOMEM;
  5188. private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
  5189. if (!private->filldir_buf) {
  5190. kfree(private);
  5191. return -ENOMEM;
  5192. }
  5193. file->private_data = private;
  5194. return 0;
  5195. }
  5196. struct dir_entry {
  5197. u64 ino;
  5198. u64 offset;
  5199. unsigned type;
  5200. int name_len;
  5201. };
  5202. static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
  5203. {
  5204. while (entries--) {
  5205. struct dir_entry *entry = addr;
  5206. char *name = (char *)(entry + 1);
  5207. ctx->pos = entry->offset;
  5208. if (!dir_emit(ctx, name, entry->name_len, entry->ino,
  5209. entry->type))
  5210. return 1;
  5211. addr += sizeof(struct dir_entry) + entry->name_len;
  5212. ctx->pos++;
  5213. }
  5214. return 0;
  5215. }
  5216. static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
  5217. {
  5218. struct inode *inode = file_inode(file);
  5219. struct btrfs_root *root = BTRFS_I(inode)->root;
  5220. struct btrfs_file_private *private = file->private_data;
  5221. struct btrfs_dir_item *di;
  5222. struct btrfs_key key;
  5223. struct btrfs_key found_key;
  5224. struct btrfs_path *path;
  5225. void *addr;
  5226. struct list_head ins_list;
  5227. struct list_head del_list;
  5228. int ret;
  5229. struct extent_buffer *leaf;
  5230. int slot;
  5231. char *name_ptr;
  5232. int name_len;
  5233. int entries = 0;
  5234. int total_len = 0;
  5235. bool put = false;
  5236. struct btrfs_key location;
  5237. if (!dir_emit_dots(file, ctx))
  5238. return 0;
  5239. path = btrfs_alloc_path();
  5240. if (!path)
  5241. return -ENOMEM;
  5242. addr = private->filldir_buf;
  5243. path->reada = READA_FORWARD;
  5244. INIT_LIST_HEAD(&ins_list);
  5245. INIT_LIST_HEAD(&del_list);
  5246. put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
  5247. again:
  5248. key.type = BTRFS_DIR_INDEX_KEY;
  5249. key.offset = ctx->pos;
  5250. key.objectid = btrfs_ino(BTRFS_I(inode));
  5251. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  5252. if (ret < 0)
  5253. goto err;
  5254. while (1) {
  5255. struct dir_entry *entry;
  5256. leaf = path->nodes[0];
  5257. slot = path->slots[0];
  5258. if (slot >= btrfs_header_nritems(leaf)) {
  5259. ret = btrfs_next_leaf(root, path);
  5260. if (ret < 0)
  5261. goto err;
  5262. else if (ret > 0)
  5263. break;
  5264. continue;
  5265. }
  5266. btrfs_item_key_to_cpu(leaf, &found_key, slot);
  5267. if (found_key.objectid != key.objectid)
  5268. break;
  5269. if (found_key.type != BTRFS_DIR_INDEX_KEY)
  5270. break;
  5271. if (found_key.offset < ctx->pos)
  5272. goto next;
  5273. if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
  5274. goto next;
  5275. di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
  5276. name_len = btrfs_dir_name_len(leaf, di);
  5277. if ((total_len + sizeof(struct dir_entry) + name_len) >=
  5278. PAGE_SIZE) {
  5279. btrfs_release_path(path);
  5280. ret = btrfs_filldir(private->filldir_buf, entries, ctx);
  5281. if (ret)
  5282. goto nopos;
  5283. addr = private->filldir_buf;
  5284. entries = 0;
  5285. total_len = 0;
  5286. goto again;
  5287. }
  5288. entry = addr;
  5289. entry->name_len = name_len;
  5290. name_ptr = (char *)(entry + 1);
  5291. read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
  5292. name_len);
  5293. entry->type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
  5294. btrfs_dir_item_key_to_cpu(leaf, di, &location);
  5295. entry->ino = location.objectid;
  5296. entry->offset = found_key.offset;
  5297. entries++;
  5298. addr += sizeof(struct dir_entry) + name_len;
  5299. total_len += sizeof(struct dir_entry) + name_len;
  5300. next:
  5301. path->slots[0]++;
  5302. }
  5303. btrfs_release_path(path);
  5304. ret = btrfs_filldir(private->filldir_buf, entries, ctx);
  5305. if (ret)
  5306. goto nopos;
  5307. ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
  5308. if (ret)
  5309. goto nopos;
  5310. /*
  5311. * Stop new entries from being returned after we return the last
  5312. * entry.
  5313. *
  5314. * New directory entries are assigned a strictly increasing
  5315. * offset. This means that new entries created during readdir
  5316. * are *guaranteed* to be seen in the future by that readdir.
  5317. * This has broken buggy programs which operate on names as
  5318. * they're returned by readdir. Until we re-use freed offsets
  5319. * we have this hack to stop new entries from being returned
  5320. * under the assumption that they'll never reach this huge
  5321. * offset.
  5322. *
  5323. * This is being careful not to overflow 32bit loff_t unless the
  5324. * last entry requires it because doing so has broken 32bit apps
  5325. * in the past.
  5326. */
  5327. if (ctx->pos >= INT_MAX)
  5328. ctx->pos = LLONG_MAX;
  5329. else
  5330. ctx->pos = INT_MAX;
  5331. nopos:
  5332. ret = 0;
  5333. err:
  5334. if (put)
  5335. btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
  5336. btrfs_free_path(path);
  5337. return ret;
  5338. }
  5339. int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
  5340. {
  5341. struct btrfs_root *root = BTRFS_I(inode)->root;
  5342. struct btrfs_trans_handle *trans;
  5343. int ret = 0;
  5344. bool nolock = false;
  5345. if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
  5346. return 0;
  5347. if (btrfs_fs_closing(root->fs_info) &&
  5348. btrfs_is_free_space_inode(BTRFS_I(inode)))
  5349. nolock = true;
  5350. if (wbc->sync_mode == WB_SYNC_ALL) {
  5351. if (nolock)
  5352. trans = btrfs_join_transaction_nolock(root);
  5353. else
  5354. trans = btrfs_join_transaction(root);
  5355. if (IS_ERR(trans))
  5356. return PTR_ERR(trans);
  5357. ret = btrfs_commit_transaction(trans);
  5358. }
  5359. return ret;
  5360. }
  5361. /*
  5362. * This is somewhat expensive, updating the tree every time the
  5363. * inode changes. But, it is most likely to find the inode in cache.
  5364. * FIXME, needs more benchmarking...there are no reasons other than performance
  5365. * to keep or drop this code.
  5366. */
  5367. static int btrfs_dirty_inode(struct inode *inode)
  5368. {
  5369. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  5370. struct btrfs_root *root = BTRFS_I(inode)->root;
  5371. struct btrfs_trans_handle *trans;
  5372. int ret;
  5373. if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
  5374. return 0;
  5375. trans = btrfs_join_transaction(root);
  5376. if (IS_ERR(trans))
  5377. return PTR_ERR(trans);
  5378. ret = btrfs_update_inode(trans, root, inode);
  5379. if (ret && ret == -ENOSPC) {
  5380. /* whoops, lets try again with the full transaction */
  5381. btrfs_end_transaction(trans);
  5382. trans = btrfs_start_transaction(root, 1);
  5383. if (IS_ERR(trans))
  5384. return PTR_ERR(trans);
  5385. ret = btrfs_update_inode(trans, root, inode);
  5386. }
  5387. btrfs_end_transaction(trans);
  5388. if (BTRFS_I(inode)->delayed_node)
  5389. btrfs_balance_delayed_items(fs_info);
  5390. return ret;
  5391. }
  5392. /*
  5393. * This is a copy of file_update_time. We need this so we can return error on
  5394. * ENOSPC for updating the inode in the case of file write and mmap writes.
  5395. */
  5396. static int btrfs_update_time(struct inode *inode, struct timespec *now,
  5397. int flags)
  5398. {
  5399. struct btrfs_root *root = BTRFS_I(inode)->root;
  5400. if (btrfs_root_readonly(root))
  5401. return -EROFS;
  5402. if (flags & S_VERSION)
  5403. inode_inc_iversion(inode);
  5404. if (flags & S_CTIME)
  5405. inode->i_ctime = *now;
  5406. if (flags & S_MTIME)
  5407. inode->i_mtime = *now;
  5408. if (flags & S_ATIME)
  5409. inode->i_atime = *now;
  5410. return btrfs_dirty_inode(inode);
  5411. }
  5412. /*
  5413. * find the highest existing sequence number in a directory
  5414. * and then set the in-memory index_cnt variable to reflect
  5415. * free sequence numbers
  5416. */
  5417. static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
  5418. {
  5419. struct btrfs_root *root = inode->root;
  5420. struct btrfs_key key, found_key;
  5421. struct btrfs_path *path;
  5422. struct extent_buffer *leaf;
  5423. int ret;
  5424. key.objectid = btrfs_ino(inode);
  5425. key.type = BTRFS_DIR_INDEX_KEY;
  5426. key.offset = (u64)-1;
  5427. path = btrfs_alloc_path();
  5428. if (!path)
  5429. return -ENOMEM;
  5430. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  5431. if (ret < 0)
  5432. goto out;
  5433. /* FIXME: we should be able to handle this */
  5434. if (ret == 0)
  5435. goto out;
  5436. ret = 0;
  5437. /*
  5438. * MAGIC NUMBER EXPLANATION:
  5439. * since we search a directory based on f_pos we have to start at 2
  5440. * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
  5441. * else has to start at 2
  5442. */
  5443. if (path->slots[0] == 0) {
  5444. inode->index_cnt = 2;
  5445. goto out;
  5446. }
  5447. path->slots[0]--;
  5448. leaf = path->nodes[0];
  5449. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  5450. if (found_key.objectid != btrfs_ino(inode) ||
  5451. found_key.type != BTRFS_DIR_INDEX_KEY) {
  5452. inode->index_cnt = 2;
  5453. goto out;
  5454. }
  5455. inode->index_cnt = found_key.offset + 1;
  5456. out:
  5457. btrfs_free_path(path);
  5458. return ret;
  5459. }
  5460. /*
  5461. * helper to find a free sequence number in a given directory. This current
  5462. * code is very simple, later versions will do smarter things in the btree
  5463. */
  5464. int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
  5465. {
  5466. int ret = 0;
  5467. if (dir->index_cnt == (u64)-1) {
  5468. ret = btrfs_inode_delayed_dir_index_count(dir);
  5469. if (ret) {
  5470. ret = btrfs_set_inode_index_count(dir);
  5471. if (ret)
  5472. return ret;
  5473. }
  5474. }
  5475. *index = dir->index_cnt;
  5476. dir->index_cnt++;
  5477. return ret;
  5478. }
  5479. static int btrfs_insert_inode_locked(struct inode *inode)
  5480. {
  5481. struct btrfs_iget_args args;
  5482. args.location = &BTRFS_I(inode)->location;
  5483. args.root = BTRFS_I(inode)->root;
  5484. return insert_inode_locked4(inode,
  5485. btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
  5486. btrfs_find_actor, &args);
  5487. }
  5488. /*
  5489. * Inherit flags from the parent inode.
  5490. *
  5491. * Currently only the compression flags and the cow flags are inherited.
  5492. */
  5493. static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
  5494. {
  5495. unsigned int flags;
  5496. if (!dir)
  5497. return;
  5498. flags = BTRFS_I(dir)->flags;
  5499. if (flags & BTRFS_INODE_NOCOMPRESS) {
  5500. BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
  5501. BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
  5502. } else if (flags & BTRFS_INODE_COMPRESS) {
  5503. BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
  5504. BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
  5505. }
  5506. if (flags & BTRFS_INODE_NODATACOW) {
  5507. BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
  5508. if (S_ISREG(inode->i_mode))
  5509. BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
  5510. }
  5511. btrfs_update_iflags(inode);
  5512. }
  5513. static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
  5514. struct btrfs_root *root,
  5515. struct inode *dir,
  5516. const char *name, int name_len,
  5517. u64 ref_objectid, u64 objectid,
  5518. umode_t mode, u64 *index)
  5519. {
  5520. struct btrfs_fs_info *fs_info = root->fs_info;
  5521. struct inode *inode;
  5522. struct btrfs_inode_item *inode_item;
  5523. struct btrfs_key *location;
  5524. struct btrfs_path *path;
  5525. struct btrfs_inode_ref *ref;
  5526. struct btrfs_key key[2];
  5527. u32 sizes[2];
  5528. int nitems = name ? 2 : 1;
  5529. unsigned long ptr;
  5530. int ret;
  5531. path = btrfs_alloc_path();
  5532. if (!path)
  5533. return ERR_PTR(-ENOMEM);
  5534. inode = new_inode(fs_info->sb);
  5535. if (!inode) {
  5536. btrfs_free_path(path);
  5537. return ERR_PTR(-ENOMEM);
  5538. }
  5539. /*
  5540. * O_TMPFILE, set link count to 0, so that after this point,
  5541. * we fill in an inode item with the correct link count.
  5542. */
  5543. if (!name)
  5544. set_nlink(inode, 0);
  5545. /*
  5546. * we have to initialize this early, so we can reclaim the inode
  5547. * number if we fail afterwards in this function.
  5548. */
  5549. inode->i_ino = objectid;
  5550. if (dir && name) {
  5551. trace_btrfs_inode_request(dir);
  5552. ret = btrfs_set_inode_index(BTRFS_I(dir), index);
  5553. if (ret) {
  5554. btrfs_free_path(path);
  5555. iput(inode);
  5556. return ERR_PTR(ret);
  5557. }
  5558. } else if (dir) {
  5559. *index = 0;
  5560. }
  5561. /*
  5562. * index_cnt is ignored for everything but a dir,
  5563. * btrfs_get_inode_index_count has an explanation for the magic
  5564. * number
  5565. */
  5566. BTRFS_I(inode)->index_cnt = 2;
  5567. BTRFS_I(inode)->dir_index = *index;
  5568. BTRFS_I(inode)->root = root;
  5569. BTRFS_I(inode)->generation = trans->transid;
  5570. inode->i_generation = BTRFS_I(inode)->generation;
  5571. /*
  5572. * We could have gotten an inode number from somebody who was fsynced
  5573. * and then removed in this same transaction, so let's just set full
  5574. * sync since it will be a full sync anyway and this will blow away the
  5575. * old info in the log.
  5576. */
  5577. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
  5578. key[0].objectid = objectid;
  5579. key[0].type = BTRFS_INODE_ITEM_KEY;
  5580. key[0].offset = 0;
  5581. sizes[0] = sizeof(struct btrfs_inode_item);
  5582. if (name) {
  5583. /*
  5584. * Start new inodes with an inode_ref. This is slightly more
  5585. * efficient for small numbers of hard links since they will
  5586. * be packed into one item. Extended refs will kick in if we
  5587. * add more hard links than can fit in the ref item.
  5588. */
  5589. key[1].objectid = objectid;
  5590. key[1].type = BTRFS_INODE_REF_KEY;
  5591. key[1].offset = ref_objectid;
  5592. sizes[1] = name_len + sizeof(*ref);
  5593. }
  5594. location = &BTRFS_I(inode)->location;
  5595. location->objectid = objectid;
  5596. location->offset = 0;
  5597. location->type = BTRFS_INODE_ITEM_KEY;
  5598. ret = btrfs_insert_inode_locked(inode);
  5599. if (ret < 0)
  5600. goto fail;
  5601. path->leave_spinning = 1;
  5602. ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
  5603. if (ret != 0)
  5604. goto fail_unlock;
  5605. inode_init_owner(inode, dir, mode);
  5606. inode_set_bytes(inode, 0);
  5607. inode->i_mtime = current_time(inode);
  5608. inode->i_atime = inode->i_mtime;
  5609. inode->i_ctime = inode->i_mtime;
  5610. BTRFS_I(inode)->i_otime = inode->i_mtime;
  5611. inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
  5612. struct btrfs_inode_item);
  5613. memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
  5614. sizeof(*inode_item));
  5615. fill_inode_item(trans, path->nodes[0], inode_item, inode);
  5616. if (name) {
  5617. ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
  5618. struct btrfs_inode_ref);
  5619. btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
  5620. btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
  5621. ptr = (unsigned long)(ref + 1);
  5622. write_extent_buffer(path->nodes[0], name, ptr, name_len);
  5623. }
  5624. btrfs_mark_buffer_dirty(path->nodes[0]);
  5625. btrfs_free_path(path);
  5626. btrfs_inherit_iflags(inode, dir);
  5627. if (S_ISREG(mode)) {
  5628. if (btrfs_test_opt(fs_info, NODATASUM))
  5629. BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
  5630. if (btrfs_test_opt(fs_info, NODATACOW))
  5631. BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
  5632. BTRFS_INODE_NODATASUM;
  5633. }
  5634. inode_tree_add(inode);
  5635. trace_btrfs_inode_new(inode);
  5636. btrfs_set_inode_last_trans(trans, inode);
  5637. btrfs_update_root_times(trans, root);
  5638. ret = btrfs_inode_inherit_props(trans, inode, dir);
  5639. if (ret)
  5640. btrfs_err(fs_info,
  5641. "error inheriting props for ino %llu (root %llu): %d",
  5642. btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
  5643. return inode;
  5644. fail_unlock:
  5645. unlock_new_inode(inode);
  5646. fail:
  5647. if (dir && name)
  5648. BTRFS_I(dir)->index_cnt--;
  5649. btrfs_free_path(path);
  5650. iput(inode);
  5651. return ERR_PTR(ret);
  5652. }
  5653. static inline u8 btrfs_inode_type(struct inode *inode)
  5654. {
  5655. return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
  5656. }
  5657. /*
  5658. * utility function to add 'inode' into 'parent_inode' with
  5659. * a give name and a given sequence number.
  5660. * if 'add_backref' is true, also insert a backref from the
  5661. * inode to the parent directory.
  5662. */
  5663. int btrfs_add_link(struct btrfs_trans_handle *trans,
  5664. struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
  5665. const char *name, int name_len, int add_backref, u64 index)
  5666. {
  5667. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  5668. int ret = 0;
  5669. struct btrfs_key key;
  5670. struct btrfs_root *root = parent_inode->root;
  5671. u64 ino = btrfs_ino(inode);
  5672. u64 parent_ino = btrfs_ino(parent_inode);
  5673. if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
  5674. memcpy(&key, &inode->root->root_key, sizeof(key));
  5675. } else {
  5676. key.objectid = ino;
  5677. key.type = BTRFS_INODE_ITEM_KEY;
  5678. key.offset = 0;
  5679. }
  5680. if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
  5681. ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
  5682. root->root_key.objectid, parent_ino,
  5683. index, name, name_len);
  5684. } else if (add_backref) {
  5685. ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
  5686. parent_ino, index);
  5687. }
  5688. /* Nothing to clean up yet */
  5689. if (ret)
  5690. return ret;
  5691. ret = btrfs_insert_dir_item(trans, root, name, name_len,
  5692. parent_inode, &key,
  5693. btrfs_inode_type(&inode->vfs_inode), index);
  5694. if (ret == -EEXIST || ret == -EOVERFLOW)
  5695. goto fail_dir_item;
  5696. else if (ret) {
  5697. btrfs_abort_transaction(trans, ret);
  5698. return ret;
  5699. }
  5700. btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
  5701. name_len * 2);
  5702. inode_inc_iversion(&parent_inode->vfs_inode);
  5703. parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
  5704. current_time(&parent_inode->vfs_inode);
  5705. ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
  5706. if (ret)
  5707. btrfs_abort_transaction(trans, ret);
  5708. return ret;
  5709. fail_dir_item:
  5710. if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
  5711. u64 local_index;
  5712. int err;
  5713. err = btrfs_del_root_ref(trans, fs_info, key.objectid,
  5714. root->root_key.objectid, parent_ino,
  5715. &local_index, name, name_len);
  5716. } else if (add_backref) {
  5717. u64 local_index;
  5718. int err;
  5719. err = btrfs_del_inode_ref(trans, root, name, name_len,
  5720. ino, parent_ino, &local_index);
  5721. }
  5722. return ret;
  5723. }
  5724. static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
  5725. struct btrfs_inode *dir, struct dentry *dentry,
  5726. struct btrfs_inode *inode, int backref, u64 index)
  5727. {
  5728. int err = btrfs_add_link(trans, dir, inode,
  5729. dentry->d_name.name, dentry->d_name.len,
  5730. backref, index);
  5731. if (err > 0)
  5732. err = -EEXIST;
  5733. return err;
  5734. }
  5735. static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
  5736. umode_t mode, dev_t rdev)
  5737. {
  5738. struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
  5739. struct btrfs_trans_handle *trans;
  5740. struct btrfs_root *root = BTRFS_I(dir)->root;
  5741. struct inode *inode = NULL;
  5742. int err;
  5743. int drop_inode = 0;
  5744. u64 objectid;
  5745. u64 index = 0;
  5746. /*
  5747. * 2 for inode item and ref
  5748. * 2 for dir items
  5749. * 1 for xattr if selinux is on
  5750. */
  5751. trans = btrfs_start_transaction(root, 5);
  5752. if (IS_ERR(trans))
  5753. return PTR_ERR(trans);
  5754. err = btrfs_find_free_ino(root, &objectid);
  5755. if (err)
  5756. goto out_unlock;
  5757. inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
  5758. dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
  5759. mode, &index);
  5760. if (IS_ERR(inode)) {
  5761. err = PTR_ERR(inode);
  5762. goto out_unlock;
  5763. }
  5764. /*
  5765. * If the active LSM wants to access the inode during
  5766. * d_instantiate it needs these. Smack checks to see
  5767. * if the filesystem supports xattrs by looking at the
  5768. * ops vector.
  5769. */
  5770. inode->i_op = &btrfs_special_inode_operations;
  5771. init_special_inode(inode, inode->i_mode, rdev);
  5772. err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
  5773. if (err)
  5774. goto out_unlock_inode;
  5775. err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
  5776. 0, index);
  5777. if (err) {
  5778. goto out_unlock_inode;
  5779. } else {
  5780. btrfs_update_inode(trans, root, inode);
  5781. unlock_new_inode(inode);
  5782. d_instantiate(dentry, inode);
  5783. }
  5784. out_unlock:
  5785. btrfs_end_transaction(trans);
  5786. btrfs_btree_balance_dirty(fs_info);
  5787. if (drop_inode) {
  5788. inode_dec_link_count(inode);
  5789. iput(inode);
  5790. }
  5791. return err;
  5792. out_unlock_inode:
  5793. drop_inode = 1;
  5794. unlock_new_inode(inode);
  5795. goto out_unlock;
  5796. }
  5797. static int btrfs_create(struct inode *dir, struct dentry *dentry,
  5798. umode_t mode, bool excl)
  5799. {
  5800. struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
  5801. struct btrfs_trans_handle *trans;
  5802. struct btrfs_root *root = BTRFS_I(dir)->root;
  5803. struct inode *inode = NULL;
  5804. int drop_inode_on_err = 0;
  5805. int err;
  5806. u64 objectid;
  5807. u64 index = 0;
  5808. /*
  5809. * 2 for inode item and ref
  5810. * 2 for dir items
  5811. * 1 for xattr if selinux is on
  5812. */
  5813. trans = btrfs_start_transaction(root, 5);
  5814. if (IS_ERR(trans))
  5815. return PTR_ERR(trans);
  5816. err = btrfs_find_free_ino(root, &objectid);
  5817. if (err)
  5818. goto out_unlock;
  5819. inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
  5820. dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
  5821. mode, &index);
  5822. if (IS_ERR(inode)) {
  5823. err = PTR_ERR(inode);
  5824. goto out_unlock;
  5825. }
  5826. drop_inode_on_err = 1;
  5827. /*
  5828. * If the active LSM wants to access the inode during
  5829. * d_instantiate it needs these. Smack checks to see
  5830. * if the filesystem supports xattrs by looking at the
  5831. * ops vector.
  5832. */
  5833. inode->i_fop = &btrfs_file_operations;
  5834. inode->i_op = &btrfs_file_inode_operations;
  5835. inode->i_mapping->a_ops = &btrfs_aops;
  5836. err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
  5837. if (err)
  5838. goto out_unlock_inode;
  5839. err = btrfs_update_inode(trans, root, inode);
  5840. if (err)
  5841. goto out_unlock_inode;
  5842. err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
  5843. 0, index);
  5844. if (err)
  5845. goto out_unlock_inode;
  5846. BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
  5847. unlock_new_inode(inode);
  5848. d_instantiate(dentry, inode);
  5849. out_unlock:
  5850. btrfs_end_transaction(trans);
  5851. if (err && drop_inode_on_err) {
  5852. inode_dec_link_count(inode);
  5853. iput(inode);
  5854. }
  5855. btrfs_btree_balance_dirty(fs_info);
  5856. return err;
  5857. out_unlock_inode:
  5858. unlock_new_inode(inode);
  5859. goto out_unlock;
  5860. }
  5861. static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
  5862. struct dentry *dentry)
  5863. {
  5864. struct btrfs_trans_handle *trans = NULL;
  5865. struct btrfs_root *root = BTRFS_I(dir)->root;
  5866. struct inode *inode = d_inode(old_dentry);
  5867. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  5868. u64 index;
  5869. int err;
  5870. int drop_inode = 0;
  5871. /* do not allow sys_link's with other subvols of the same device */
  5872. if (root->objectid != BTRFS_I(inode)->root->objectid)
  5873. return -EXDEV;
  5874. if (inode->i_nlink >= BTRFS_LINK_MAX)
  5875. return -EMLINK;
  5876. err = btrfs_set_inode_index(BTRFS_I(dir), &index);
  5877. if (err)
  5878. goto fail;
  5879. /*
  5880. * 2 items for inode and inode ref
  5881. * 2 items for dir items
  5882. * 1 item for parent inode
  5883. */
  5884. trans = btrfs_start_transaction(root, 5);
  5885. if (IS_ERR(trans)) {
  5886. err = PTR_ERR(trans);
  5887. trans = NULL;
  5888. goto fail;
  5889. }
  5890. /* There are several dir indexes for this inode, clear the cache. */
  5891. BTRFS_I(inode)->dir_index = 0ULL;
  5892. inc_nlink(inode);
  5893. inode_inc_iversion(inode);
  5894. inode->i_ctime = current_time(inode);
  5895. ihold(inode);
  5896. set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
  5897. err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
  5898. 1, index);
  5899. if (err) {
  5900. drop_inode = 1;
  5901. } else {
  5902. struct dentry *parent = dentry->d_parent;
  5903. err = btrfs_update_inode(trans, root, inode);
  5904. if (err)
  5905. goto fail;
  5906. if (inode->i_nlink == 1) {
  5907. /*
  5908. * If new hard link count is 1, it's a file created
  5909. * with open(2) O_TMPFILE flag.
  5910. */
  5911. err = btrfs_orphan_del(trans, BTRFS_I(inode));
  5912. if (err)
  5913. goto fail;
  5914. }
  5915. d_instantiate(dentry, inode);
  5916. btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
  5917. }
  5918. fail:
  5919. if (trans)
  5920. btrfs_end_transaction(trans);
  5921. if (drop_inode) {
  5922. inode_dec_link_count(inode);
  5923. iput(inode);
  5924. }
  5925. btrfs_btree_balance_dirty(fs_info);
  5926. return err;
  5927. }
  5928. static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
  5929. {
  5930. struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
  5931. struct inode *inode = NULL;
  5932. struct btrfs_trans_handle *trans;
  5933. struct btrfs_root *root = BTRFS_I(dir)->root;
  5934. int err = 0;
  5935. int drop_on_err = 0;
  5936. u64 objectid = 0;
  5937. u64 index = 0;
  5938. /*
  5939. * 2 items for inode and ref
  5940. * 2 items for dir items
  5941. * 1 for xattr if selinux is on
  5942. */
  5943. trans = btrfs_start_transaction(root, 5);
  5944. if (IS_ERR(trans))
  5945. return PTR_ERR(trans);
  5946. err = btrfs_find_free_ino(root, &objectid);
  5947. if (err)
  5948. goto out_fail;
  5949. inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
  5950. dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
  5951. S_IFDIR | mode, &index);
  5952. if (IS_ERR(inode)) {
  5953. err = PTR_ERR(inode);
  5954. goto out_fail;
  5955. }
  5956. drop_on_err = 1;
  5957. /* these must be set before we unlock the inode */
  5958. inode->i_op = &btrfs_dir_inode_operations;
  5959. inode->i_fop = &btrfs_dir_file_operations;
  5960. err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
  5961. if (err)
  5962. goto out_fail_inode;
  5963. btrfs_i_size_write(BTRFS_I(inode), 0);
  5964. err = btrfs_update_inode(trans, root, inode);
  5965. if (err)
  5966. goto out_fail_inode;
  5967. err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
  5968. dentry->d_name.name,
  5969. dentry->d_name.len, 0, index);
  5970. if (err)
  5971. goto out_fail_inode;
  5972. d_instantiate(dentry, inode);
  5973. /*
  5974. * mkdir is special. We're unlocking after we call d_instantiate
  5975. * to avoid a race with nfsd calling d_instantiate.
  5976. */
  5977. unlock_new_inode(inode);
  5978. drop_on_err = 0;
  5979. out_fail:
  5980. btrfs_end_transaction(trans);
  5981. if (drop_on_err) {
  5982. inode_dec_link_count(inode);
  5983. iput(inode);
  5984. }
  5985. btrfs_btree_balance_dirty(fs_info);
  5986. return err;
  5987. out_fail_inode:
  5988. unlock_new_inode(inode);
  5989. goto out_fail;
  5990. }
  5991. /* Find next extent map of a given extent map, caller needs to ensure locks */
  5992. static struct extent_map *next_extent_map(struct extent_map *em)
  5993. {
  5994. struct rb_node *next;
  5995. next = rb_next(&em->rb_node);
  5996. if (!next)
  5997. return NULL;
  5998. return container_of(next, struct extent_map, rb_node);
  5999. }
  6000. static struct extent_map *prev_extent_map(struct extent_map *em)
  6001. {
  6002. struct rb_node *prev;
  6003. prev = rb_prev(&em->rb_node);
  6004. if (!prev)
  6005. return NULL;
  6006. return container_of(prev, struct extent_map, rb_node);
  6007. }
  6008. /* helper for btfs_get_extent. Given an existing extent in the tree,
  6009. * the existing extent is the nearest extent to map_start,
  6010. * and an extent that you want to insert, deal with overlap and insert
  6011. * the best fitted new extent into the tree.
  6012. */
  6013. static int merge_extent_mapping(struct extent_map_tree *em_tree,
  6014. struct extent_map *existing,
  6015. struct extent_map *em,
  6016. u64 map_start)
  6017. {
  6018. struct extent_map *prev;
  6019. struct extent_map *next;
  6020. u64 start;
  6021. u64 end;
  6022. u64 start_diff;
  6023. BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
  6024. if (existing->start > map_start) {
  6025. next = existing;
  6026. prev = prev_extent_map(next);
  6027. } else {
  6028. prev = existing;
  6029. next = next_extent_map(prev);
  6030. }
  6031. start = prev ? extent_map_end(prev) : em->start;
  6032. start = max_t(u64, start, em->start);
  6033. end = next ? next->start : extent_map_end(em);
  6034. end = min_t(u64, end, extent_map_end(em));
  6035. start_diff = start - em->start;
  6036. em->start = start;
  6037. em->len = end - start;
  6038. if (em->block_start < EXTENT_MAP_LAST_BYTE &&
  6039. !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
  6040. em->block_start += start_diff;
  6041. em->block_len -= start_diff;
  6042. }
  6043. return add_extent_mapping(em_tree, em, 0);
  6044. }
  6045. static noinline int uncompress_inline(struct btrfs_path *path,
  6046. struct page *page,
  6047. size_t pg_offset, u64 extent_offset,
  6048. struct btrfs_file_extent_item *item)
  6049. {
  6050. int ret;
  6051. struct extent_buffer *leaf = path->nodes[0];
  6052. char *tmp;
  6053. size_t max_size;
  6054. unsigned long inline_size;
  6055. unsigned long ptr;
  6056. int compress_type;
  6057. WARN_ON(pg_offset != 0);
  6058. compress_type = btrfs_file_extent_compression(leaf, item);
  6059. max_size = btrfs_file_extent_ram_bytes(leaf, item);
  6060. inline_size = btrfs_file_extent_inline_item_len(leaf,
  6061. btrfs_item_nr(path->slots[0]));
  6062. tmp = kmalloc(inline_size, GFP_NOFS);
  6063. if (!tmp)
  6064. return -ENOMEM;
  6065. ptr = btrfs_file_extent_inline_start(item);
  6066. read_extent_buffer(leaf, tmp, ptr, inline_size);
  6067. max_size = min_t(unsigned long, PAGE_SIZE, max_size);
  6068. ret = btrfs_decompress(compress_type, tmp, page,
  6069. extent_offset, inline_size, max_size);
  6070. /*
  6071. * decompression code contains a memset to fill in any space between the end
  6072. * of the uncompressed data and the end of max_size in case the decompressed
  6073. * data ends up shorter than ram_bytes. That doesn't cover the hole between
  6074. * the end of an inline extent and the beginning of the next block, so we
  6075. * cover that region here.
  6076. */
  6077. if (max_size + pg_offset < PAGE_SIZE) {
  6078. char *map = kmap(page);
  6079. memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
  6080. kunmap(page);
  6081. }
  6082. kfree(tmp);
  6083. return ret;
  6084. }
  6085. /*
  6086. * a bit scary, this does extent mapping from logical file offset to the disk.
  6087. * the ugly parts come from merging extents from the disk with the in-ram
  6088. * representation. This gets more complex because of the data=ordered code,
  6089. * where the in-ram extents might be locked pending data=ordered completion.
  6090. *
  6091. * This also copies inline extents directly into the page.
  6092. */
  6093. struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
  6094. struct page *page,
  6095. size_t pg_offset, u64 start, u64 len,
  6096. int create)
  6097. {
  6098. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  6099. int ret;
  6100. int err = 0;
  6101. u64 extent_start = 0;
  6102. u64 extent_end = 0;
  6103. u64 objectid = btrfs_ino(inode);
  6104. u32 found_type;
  6105. struct btrfs_path *path = NULL;
  6106. struct btrfs_root *root = inode->root;
  6107. struct btrfs_file_extent_item *item;
  6108. struct extent_buffer *leaf;
  6109. struct btrfs_key found_key;
  6110. struct extent_map *em = NULL;
  6111. struct extent_map_tree *em_tree = &inode->extent_tree;
  6112. struct extent_io_tree *io_tree = &inode->io_tree;
  6113. struct btrfs_trans_handle *trans = NULL;
  6114. const bool new_inline = !page || create;
  6115. again:
  6116. read_lock(&em_tree->lock);
  6117. em = lookup_extent_mapping(em_tree, start, len);
  6118. if (em)
  6119. em->bdev = fs_info->fs_devices->latest_bdev;
  6120. read_unlock(&em_tree->lock);
  6121. if (em) {
  6122. if (em->start > start || em->start + em->len <= start)
  6123. free_extent_map(em);
  6124. else if (em->block_start == EXTENT_MAP_INLINE && page)
  6125. free_extent_map(em);
  6126. else
  6127. goto out;
  6128. }
  6129. em = alloc_extent_map();
  6130. if (!em) {
  6131. err = -ENOMEM;
  6132. goto out;
  6133. }
  6134. em->bdev = fs_info->fs_devices->latest_bdev;
  6135. em->start = EXTENT_MAP_HOLE;
  6136. em->orig_start = EXTENT_MAP_HOLE;
  6137. em->len = (u64)-1;
  6138. em->block_len = (u64)-1;
  6139. if (!path) {
  6140. path = btrfs_alloc_path();
  6141. if (!path) {
  6142. err = -ENOMEM;
  6143. goto out;
  6144. }
  6145. /*
  6146. * Chances are we'll be called again, so go ahead and do
  6147. * readahead
  6148. */
  6149. path->reada = READA_FORWARD;
  6150. }
  6151. ret = btrfs_lookup_file_extent(trans, root, path,
  6152. objectid, start, trans != NULL);
  6153. if (ret < 0) {
  6154. err = ret;
  6155. goto out;
  6156. }
  6157. if (ret != 0) {
  6158. if (path->slots[0] == 0)
  6159. goto not_found;
  6160. path->slots[0]--;
  6161. }
  6162. leaf = path->nodes[0];
  6163. item = btrfs_item_ptr(leaf, path->slots[0],
  6164. struct btrfs_file_extent_item);
  6165. /* are we inside the extent that was found? */
  6166. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  6167. found_type = found_key.type;
  6168. if (found_key.objectid != objectid ||
  6169. found_type != BTRFS_EXTENT_DATA_KEY) {
  6170. /*
  6171. * If we backup past the first extent we want to move forward
  6172. * and see if there is an extent in front of us, otherwise we'll
  6173. * say there is a hole for our whole search range which can
  6174. * cause problems.
  6175. */
  6176. extent_end = start;
  6177. goto next;
  6178. }
  6179. found_type = btrfs_file_extent_type(leaf, item);
  6180. extent_start = found_key.offset;
  6181. if (found_type == BTRFS_FILE_EXTENT_REG ||
  6182. found_type == BTRFS_FILE_EXTENT_PREALLOC) {
  6183. extent_end = extent_start +
  6184. btrfs_file_extent_num_bytes(leaf, item);
  6185. trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
  6186. extent_start);
  6187. } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
  6188. size_t size;
  6189. size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
  6190. extent_end = ALIGN(extent_start + size,
  6191. fs_info->sectorsize);
  6192. trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
  6193. path->slots[0],
  6194. extent_start);
  6195. }
  6196. next:
  6197. if (start >= extent_end) {
  6198. path->slots[0]++;
  6199. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  6200. ret = btrfs_next_leaf(root, path);
  6201. if (ret < 0) {
  6202. err = ret;
  6203. goto out;
  6204. }
  6205. if (ret > 0)
  6206. goto not_found;
  6207. leaf = path->nodes[0];
  6208. }
  6209. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  6210. if (found_key.objectid != objectid ||
  6211. found_key.type != BTRFS_EXTENT_DATA_KEY)
  6212. goto not_found;
  6213. if (start + len <= found_key.offset)
  6214. goto not_found;
  6215. if (start > found_key.offset)
  6216. goto next;
  6217. em->start = start;
  6218. em->orig_start = start;
  6219. em->len = found_key.offset - start;
  6220. goto not_found_em;
  6221. }
  6222. btrfs_extent_item_to_extent_map(inode, path, item,
  6223. new_inline, em);
  6224. if (found_type == BTRFS_FILE_EXTENT_REG ||
  6225. found_type == BTRFS_FILE_EXTENT_PREALLOC) {
  6226. goto insert;
  6227. } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
  6228. unsigned long ptr;
  6229. char *map;
  6230. size_t size;
  6231. size_t extent_offset;
  6232. size_t copy_size;
  6233. if (new_inline)
  6234. goto out;
  6235. size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
  6236. extent_offset = page_offset(page) + pg_offset - extent_start;
  6237. copy_size = min_t(u64, PAGE_SIZE - pg_offset,
  6238. size - extent_offset);
  6239. em->start = extent_start + extent_offset;
  6240. em->len = ALIGN(copy_size, fs_info->sectorsize);
  6241. em->orig_block_len = em->len;
  6242. em->orig_start = em->start;
  6243. ptr = btrfs_file_extent_inline_start(item) + extent_offset;
  6244. if (create == 0 && !PageUptodate(page)) {
  6245. if (btrfs_file_extent_compression(leaf, item) !=
  6246. BTRFS_COMPRESS_NONE) {
  6247. ret = uncompress_inline(path, page, pg_offset,
  6248. extent_offset, item);
  6249. if (ret) {
  6250. err = ret;
  6251. goto out;
  6252. }
  6253. } else {
  6254. map = kmap(page);
  6255. read_extent_buffer(leaf, map + pg_offset, ptr,
  6256. copy_size);
  6257. if (pg_offset + copy_size < PAGE_SIZE) {
  6258. memset(map + pg_offset + copy_size, 0,
  6259. PAGE_SIZE - pg_offset -
  6260. copy_size);
  6261. }
  6262. kunmap(page);
  6263. }
  6264. flush_dcache_page(page);
  6265. } else if (create && PageUptodate(page)) {
  6266. BUG();
  6267. if (!trans) {
  6268. kunmap(page);
  6269. free_extent_map(em);
  6270. em = NULL;
  6271. btrfs_release_path(path);
  6272. trans = btrfs_join_transaction(root);
  6273. if (IS_ERR(trans))
  6274. return ERR_CAST(trans);
  6275. goto again;
  6276. }
  6277. map = kmap(page);
  6278. write_extent_buffer(leaf, map + pg_offset, ptr,
  6279. copy_size);
  6280. kunmap(page);
  6281. btrfs_mark_buffer_dirty(leaf);
  6282. }
  6283. set_extent_uptodate(io_tree, em->start,
  6284. extent_map_end(em) - 1, NULL, GFP_NOFS);
  6285. goto insert;
  6286. }
  6287. not_found:
  6288. em->start = start;
  6289. em->orig_start = start;
  6290. em->len = len;
  6291. not_found_em:
  6292. em->block_start = EXTENT_MAP_HOLE;
  6293. set_bit(EXTENT_FLAG_VACANCY, &em->flags);
  6294. insert:
  6295. btrfs_release_path(path);
  6296. if (em->start > start || extent_map_end(em) <= start) {
  6297. btrfs_err(fs_info,
  6298. "bad extent! em: [%llu %llu] passed [%llu %llu]",
  6299. em->start, em->len, start, len);
  6300. err = -EIO;
  6301. goto out;
  6302. }
  6303. err = 0;
  6304. write_lock(&em_tree->lock);
  6305. ret = add_extent_mapping(em_tree, em, 0);
  6306. /* it is possible that someone inserted the extent into the tree
  6307. * while we had the lock dropped. It is also possible that
  6308. * an overlapping map exists in the tree
  6309. */
  6310. if (ret == -EEXIST) {
  6311. struct extent_map *existing;
  6312. ret = 0;
  6313. existing = search_extent_mapping(em_tree, start, len);
  6314. /*
  6315. * existing will always be non-NULL, since there must be
  6316. * extent causing the -EEXIST.
  6317. */
  6318. if (existing->start == em->start &&
  6319. extent_map_end(existing) >= extent_map_end(em) &&
  6320. em->block_start == existing->block_start) {
  6321. /*
  6322. * The existing extent map already encompasses the
  6323. * entire extent map we tried to add.
  6324. */
  6325. free_extent_map(em);
  6326. em = existing;
  6327. err = 0;
  6328. } else if (start >= extent_map_end(existing) ||
  6329. start <= existing->start) {
  6330. /*
  6331. * The existing extent map is the one nearest to
  6332. * the [start, start + len) range which overlaps
  6333. */
  6334. err = merge_extent_mapping(em_tree, existing,
  6335. em, start);
  6336. free_extent_map(existing);
  6337. if (err) {
  6338. free_extent_map(em);
  6339. em = NULL;
  6340. }
  6341. } else {
  6342. free_extent_map(em);
  6343. em = existing;
  6344. err = 0;
  6345. }
  6346. }
  6347. write_unlock(&em_tree->lock);
  6348. out:
  6349. trace_btrfs_get_extent(root, inode, em);
  6350. btrfs_free_path(path);
  6351. if (trans) {
  6352. ret = btrfs_end_transaction(trans);
  6353. if (!err)
  6354. err = ret;
  6355. }
  6356. if (err) {
  6357. free_extent_map(em);
  6358. return ERR_PTR(err);
  6359. }
  6360. BUG_ON(!em); /* Error is always set */
  6361. return em;
  6362. }
  6363. struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
  6364. struct page *page,
  6365. size_t pg_offset, u64 start, u64 len,
  6366. int create)
  6367. {
  6368. struct extent_map *em;
  6369. struct extent_map *hole_em = NULL;
  6370. u64 range_start = start;
  6371. u64 end;
  6372. u64 found;
  6373. u64 found_end;
  6374. int err = 0;
  6375. em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
  6376. if (IS_ERR(em))
  6377. return em;
  6378. /*
  6379. * If our em maps to:
  6380. * - a hole or
  6381. * - a pre-alloc extent,
  6382. * there might actually be delalloc bytes behind it.
  6383. */
  6384. if (em->block_start != EXTENT_MAP_HOLE &&
  6385. !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
  6386. return em;
  6387. else
  6388. hole_em = em;
  6389. /* check to see if we've wrapped (len == -1 or similar) */
  6390. end = start + len;
  6391. if (end < start)
  6392. end = (u64)-1;
  6393. else
  6394. end -= 1;
  6395. em = NULL;
  6396. /* ok, we didn't find anything, lets look for delalloc */
  6397. found = count_range_bits(&inode->io_tree, &range_start,
  6398. end, len, EXTENT_DELALLOC, 1);
  6399. found_end = range_start + found;
  6400. if (found_end < range_start)
  6401. found_end = (u64)-1;
  6402. /*
  6403. * we didn't find anything useful, return
  6404. * the original results from get_extent()
  6405. */
  6406. if (range_start > end || found_end <= start) {
  6407. em = hole_em;
  6408. hole_em = NULL;
  6409. goto out;
  6410. }
  6411. /* adjust the range_start to make sure it doesn't
  6412. * go backwards from the start they passed in
  6413. */
  6414. range_start = max(start, range_start);
  6415. found = found_end - range_start;
  6416. if (found > 0) {
  6417. u64 hole_start = start;
  6418. u64 hole_len = len;
  6419. em = alloc_extent_map();
  6420. if (!em) {
  6421. err = -ENOMEM;
  6422. goto out;
  6423. }
  6424. /*
  6425. * when btrfs_get_extent can't find anything it
  6426. * returns one huge hole
  6427. *
  6428. * make sure what it found really fits our range, and
  6429. * adjust to make sure it is based on the start from
  6430. * the caller
  6431. */
  6432. if (hole_em) {
  6433. u64 calc_end = extent_map_end(hole_em);
  6434. if (calc_end <= start || (hole_em->start > end)) {
  6435. free_extent_map(hole_em);
  6436. hole_em = NULL;
  6437. } else {
  6438. hole_start = max(hole_em->start, start);
  6439. hole_len = calc_end - hole_start;
  6440. }
  6441. }
  6442. em->bdev = NULL;
  6443. if (hole_em && range_start > hole_start) {
  6444. /* our hole starts before our delalloc, so we
  6445. * have to return just the parts of the hole
  6446. * that go until the delalloc starts
  6447. */
  6448. em->len = min(hole_len,
  6449. range_start - hole_start);
  6450. em->start = hole_start;
  6451. em->orig_start = hole_start;
  6452. /*
  6453. * don't adjust block start at all,
  6454. * it is fixed at EXTENT_MAP_HOLE
  6455. */
  6456. em->block_start = hole_em->block_start;
  6457. em->block_len = hole_len;
  6458. if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
  6459. set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
  6460. } else {
  6461. em->start = range_start;
  6462. em->len = found;
  6463. em->orig_start = range_start;
  6464. em->block_start = EXTENT_MAP_DELALLOC;
  6465. em->block_len = found;
  6466. }
  6467. } else if (hole_em) {
  6468. return hole_em;
  6469. }
  6470. out:
  6471. free_extent_map(hole_em);
  6472. if (err) {
  6473. free_extent_map(em);
  6474. return ERR_PTR(err);
  6475. }
  6476. return em;
  6477. }
  6478. static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
  6479. const u64 start,
  6480. const u64 len,
  6481. const u64 orig_start,
  6482. const u64 block_start,
  6483. const u64 block_len,
  6484. const u64 orig_block_len,
  6485. const u64 ram_bytes,
  6486. const int type)
  6487. {
  6488. struct extent_map *em = NULL;
  6489. int ret;
  6490. if (type != BTRFS_ORDERED_NOCOW) {
  6491. em = create_io_em(inode, start, len, orig_start,
  6492. block_start, block_len, orig_block_len,
  6493. ram_bytes,
  6494. BTRFS_COMPRESS_NONE, /* compress_type */
  6495. type);
  6496. if (IS_ERR(em))
  6497. goto out;
  6498. }
  6499. ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
  6500. len, block_len, type);
  6501. if (ret) {
  6502. if (em) {
  6503. free_extent_map(em);
  6504. btrfs_drop_extent_cache(BTRFS_I(inode), start,
  6505. start + len - 1, 0);
  6506. }
  6507. em = ERR_PTR(ret);
  6508. }
  6509. out:
  6510. return em;
  6511. }
  6512. static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
  6513. u64 start, u64 len)
  6514. {
  6515. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  6516. struct btrfs_root *root = BTRFS_I(inode)->root;
  6517. struct extent_map *em;
  6518. struct btrfs_key ins;
  6519. u64 alloc_hint;
  6520. int ret;
  6521. alloc_hint = get_extent_allocation_hint(inode, start, len);
  6522. ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
  6523. 0, alloc_hint, &ins, 1, 1);
  6524. if (ret)
  6525. return ERR_PTR(ret);
  6526. em = btrfs_create_dio_extent(inode, start, ins.offset, start,
  6527. ins.objectid, ins.offset, ins.offset,
  6528. ins.offset, BTRFS_ORDERED_REGULAR);
  6529. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  6530. if (IS_ERR(em))
  6531. btrfs_free_reserved_extent(fs_info, ins.objectid,
  6532. ins.offset, 1);
  6533. return em;
  6534. }
  6535. /*
  6536. * returns 1 when the nocow is safe, < 1 on error, 0 if the
  6537. * block must be cow'd
  6538. */
  6539. noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
  6540. u64 *orig_start, u64 *orig_block_len,
  6541. u64 *ram_bytes)
  6542. {
  6543. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  6544. struct btrfs_path *path;
  6545. int ret;
  6546. struct extent_buffer *leaf;
  6547. struct btrfs_root *root = BTRFS_I(inode)->root;
  6548. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  6549. struct btrfs_file_extent_item *fi;
  6550. struct btrfs_key key;
  6551. u64 disk_bytenr;
  6552. u64 backref_offset;
  6553. u64 extent_end;
  6554. u64 num_bytes;
  6555. int slot;
  6556. int found_type;
  6557. bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
  6558. path = btrfs_alloc_path();
  6559. if (!path)
  6560. return -ENOMEM;
  6561. ret = btrfs_lookup_file_extent(NULL, root, path,
  6562. btrfs_ino(BTRFS_I(inode)), offset, 0);
  6563. if (ret < 0)
  6564. goto out;
  6565. slot = path->slots[0];
  6566. if (ret == 1) {
  6567. if (slot == 0) {
  6568. /* can't find the item, must cow */
  6569. ret = 0;
  6570. goto out;
  6571. }
  6572. slot--;
  6573. }
  6574. ret = 0;
  6575. leaf = path->nodes[0];
  6576. btrfs_item_key_to_cpu(leaf, &key, slot);
  6577. if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
  6578. key.type != BTRFS_EXTENT_DATA_KEY) {
  6579. /* not our file or wrong item type, must cow */
  6580. goto out;
  6581. }
  6582. if (key.offset > offset) {
  6583. /* Wrong offset, must cow */
  6584. goto out;
  6585. }
  6586. fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
  6587. found_type = btrfs_file_extent_type(leaf, fi);
  6588. if (found_type != BTRFS_FILE_EXTENT_REG &&
  6589. found_type != BTRFS_FILE_EXTENT_PREALLOC) {
  6590. /* not a regular extent, must cow */
  6591. goto out;
  6592. }
  6593. if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
  6594. goto out;
  6595. extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
  6596. if (extent_end <= offset)
  6597. goto out;
  6598. disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  6599. if (disk_bytenr == 0)
  6600. goto out;
  6601. if (btrfs_file_extent_compression(leaf, fi) ||
  6602. btrfs_file_extent_encryption(leaf, fi) ||
  6603. btrfs_file_extent_other_encoding(leaf, fi))
  6604. goto out;
  6605. backref_offset = btrfs_file_extent_offset(leaf, fi);
  6606. if (orig_start) {
  6607. *orig_start = key.offset - backref_offset;
  6608. *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
  6609. *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
  6610. }
  6611. if (btrfs_extent_readonly(fs_info, disk_bytenr))
  6612. goto out;
  6613. num_bytes = min(offset + *len, extent_end) - offset;
  6614. if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
  6615. u64 range_end;
  6616. range_end = round_up(offset + num_bytes,
  6617. root->fs_info->sectorsize) - 1;
  6618. ret = test_range_bit(io_tree, offset, range_end,
  6619. EXTENT_DELALLOC, 0, NULL);
  6620. if (ret) {
  6621. ret = -EAGAIN;
  6622. goto out;
  6623. }
  6624. }
  6625. btrfs_release_path(path);
  6626. /*
  6627. * look for other files referencing this extent, if we
  6628. * find any we must cow
  6629. */
  6630. ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
  6631. key.offset - backref_offset, disk_bytenr);
  6632. if (ret) {
  6633. ret = 0;
  6634. goto out;
  6635. }
  6636. /*
  6637. * adjust disk_bytenr and num_bytes to cover just the bytes
  6638. * in this extent we are about to write. If there
  6639. * are any csums in that range we have to cow in order
  6640. * to keep the csums correct
  6641. */
  6642. disk_bytenr += backref_offset;
  6643. disk_bytenr += offset - key.offset;
  6644. if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
  6645. goto out;
  6646. /*
  6647. * all of the above have passed, it is safe to overwrite this extent
  6648. * without cow
  6649. */
  6650. *len = num_bytes;
  6651. ret = 1;
  6652. out:
  6653. btrfs_free_path(path);
  6654. return ret;
  6655. }
  6656. bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
  6657. {
  6658. struct radix_tree_root *root = &inode->i_mapping->page_tree;
  6659. bool found = false;
  6660. void **pagep = NULL;
  6661. struct page *page = NULL;
  6662. unsigned long start_idx;
  6663. unsigned long end_idx;
  6664. start_idx = start >> PAGE_SHIFT;
  6665. /*
  6666. * end is the last byte in the last page. end == start is legal
  6667. */
  6668. end_idx = end >> PAGE_SHIFT;
  6669. rcu_read_lock();
  6670. /* Most of the code in this while loop is lifted from
  6671. * find_get_page. It's been modified to begin searching from a
  6672. * page and return just the first page found in that range. If the
  6673. * found idx is less than or equal to the end idx then we know that
  6674. * a page exists. If no pages are found or if those pages are
  6675. * outside of the range then we're fine (yay!) */
  6676. while (page == NULL &&
  6677. radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
  6678. page = radix_tree_deref_slot(pagep);
  6679. if (unlikely(!page))
  6680. break;
  6681. if (radix_tree_exception(page)) {
  6682. if (radix_tree_deref_retry(page)) {
  6683. page = NULL;
  6684. continue;
  6685. }
  6686. /*
  6687. * Otherwise, shmem/tmpfs must be storing a swap entry
  6688. * here as an exceptional entry: so return it without
  6689. * attempting to raise page count.
  6690. */
  6691. page = NULL;
  6692. break; /* TODO: Is this relevant for this use case? */
  6693. }
  6694. if (!page_cache_get_speculative(page)) {
  6695. page = NULL;
  6696. continue;
  6697. }
  6698. /*
  6699. * Has the page moved?
  6700. * This is part of the lockless pagecache protocol. See
  6701. * include/linux/pagemap.h for details.
  6702. */
  6703. if (unlikely(page != *pagep)) {
  6704. put_page(page);
  6705. page = NULL;
  6706. }
  6707. }
  6708. if (page) {
  6709. if (page->index <= end_idx)
  6710. found = true;
  6711. put_page(page);
  6712. }
  6713. rcu_read_unlock();
  6714. return found;
  6715. }
  6716. static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
  6717. struct extent_state **cached_state, int writing)
  6718. {
  6719. struct btrfs_ordered_extent *ordered;
  6720. int ret = 0;
  6721. while (1) {
  6722. lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  6723. cached_state);
  6724. /*
  6725. * We're concerned with the entire range that we're going to be
  6726. * doing DIO to, so we need to make sure there's no ordered
  6727. * extents in this range.
  6728. */
  6729. ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
  6730. lockend - lockstart + 1);
  6731. /*
  6732. * We need to make sure there are no buffered pages in this
  6733. * range either, we could have raced between the invalidate in
  6734. * generic_file_direct_write and locking the extent. The
  6735. * invalidate needs to happen so that reads after a write do not
  6736. * get stale data.
  6737. */
  6738. if (!ordered &&
  6739. (!writing ||
  6740. !btrfs_page_exists_in_range(inode, lockstart, lockend)))
  6741. break;
  6742. unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  6743. cached_state, GFP_NOFS);
  6744. if (ordered) {
  6745. /*
  6746. * If we are doing a DIO read and the ordered extent we
  6747. * found is for a buffered write, we can not wait for it
  6748. * to complete and retry, because if we do so we can
  6749. * deadlock with concurrent buffered writes on page
  6750. * locks. This happens only if our DIO read covers more
  6751. * than one extent map, if at this point has already
  6752. * created an ordered extent for a previous extent map
  6753. * and locked its range in the inode's io tree, and a
  6754. * concurrent write against that previous extent map's
  6755. * range and this range started (we unlock the ranges
  6756. * in the io tree only when the bios complete and
  6757. * buffered writes always lock pages before attempting
  6758. * to lock range in the io tree).
  6759. */
  6760. if (writing ||
  6761. test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
  6762. btrfs_start_ordered_extent(inode, ordered, 1);
  6763. else
  6764. ret = -ENOTBLK;
  6765. btrfs_put_ordered_extent(ordered);
  6766. } else {
  6767. /*
  6768. * We could trigger writeback for this range (and wait
  6769. * for it to complete) and then invalidate the pages for
  6770. * this range (through invalidate_inode_pages2_range()),
  6771. * but that can lead us to a deadlock with a concurrent
  6772. * call to readpages() (a buffered read or a defrag call
  6773. * triggered a readahead) on a page lock due to an
  6774. * ordered dio extent we created before but did not have
  6775. * yet a corresponding bio submitted (whence it can not
  6776. * complete), which makes readpages() wait for that
  6777. * ordered extent to complete while holding a lock on
  6778. * that page.
  6779. */
  6780. ret = -ENOTBLK;
  6781. }
  6782. if (ret)
  6783. break;
  6784. cond_resched();
  6785. }
  6786. return ret;
  6787. }
  6788. /* The callers of this must take lock_extent() */
  6789. static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
  6790. u64 orig_start, u64 block_start,
  6791. u64 block_len, u64 orig_block_len,
  6792. u64 ram_bytes, int compress_type,
  6793. int type)
  6794. {
  6795. struct extent_map_tree *em_tree;
  6796. struct extent_map *em;
  6797. struct btrfs_root *root = BTRFS_I(inode)->root;
  6798. int ret;
  6799. ASSERT(type == BTRFS_ORDERED_PREALLOC ||
  6800. type == BTRFS_ORDERED_COMPRESSED ||
  6801. type == BTRFS_ORDERED_NOCOW ||
  6802. type == BTRFS_ORDERED_REGULAR);
  6803. em_tree = &BTRFS_I(inode)->extent_tree;
  6804. em = alloc_extent_map();
  6805. if (!em)
  6806. return ERR_PTR(-ENOMEM);
  6807. em->start = start;
  6808. em->orig_start = orig_start;
  6809. em->len = len;
  6810. em->block_len = block_len;
  6811. em->block_start = block_start;
  6812. em->bdev = root->fs_info->fs_devices->latest_bdev;
  6813. em->orig_block_len = orig_block_len;
  6814. em->ram_bytes = ram_bytes;
  6815. em->generation = -1;
  6816. set_bit(EXTENT_FLAG_PINNED, &em->flags);
  6817. if (type == BTRFS_ORDERED_PREALLOC) {
  6818. set_bit(EXTENT_FLAG_FILLING, &em->flags);
  6819. } else if (type == BTRFS_ORDERED_COMPRESSED) {
  6820. set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
  6821. em->compress_type = compress_type;
  6822. }
  6823. do {
  6824. btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
  6825. em->start + em->len - 1, 0);
  6826. write_lock(&em_tree->lock);
  6827. ret = add_extent_mapping(em_tree, em, 1);
  6828. write_unlock(&em_tree->lock);
  6829. /*
  6830. * The caller has taken lock_extent(), who could race with us
  6831. * to add em?
  6832. */
  6833. } while (ret == -EEXIST);
  6834. if (ret) {
  6835. free_extent_map(em);
  6836. return ERR_PTR(ret);
  6837. }
  6838. /* em got 2 refs now, callers needs to do free_extent_map once. */
  6839. return em;
  6840. }
  6841. static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
  6842. struct buffer_head *bh_result, int create)
  6843. {
  6844. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  6845. struct extent_map *em;
  6846. struct extent_state *cached_state = NULL;
  6847. struct btrfs_dio_data *dio_data = NULL;
  6848. u64 start = iblock << inode->i_blkbits;
  6849. u64 lockstart, lockend;
  6850. u64 len = bh_result->b_size;
  6851. int unlock_bits = EXTENT_LOCKED;
  6852. int ret = 0;
  6853. if (create)
  6854. unlock_bits |= EXTENT_DIRTY;
  6855. else
  6856. len = min_t(u64, len, fs_info->sectorsize);
  6857. lockstart = start;
  6858. lockend = start + len - 1;
  6859. if (current->journal_info) {
  6860. /*
  6861. * Need to pull our outstanding extents and set journal_info to NULL so
  6862. * that anything that needs to check if there's a transaction doesn't get
  6863. * confused.
  6864. */
  6865. dio_data = current->journal_info;
  6866. current->journal_info = NULL;
  6867. }
  6868. /*
  6869. * If this errors out it's because we couldn't invalidate pagecache for
  6870. * this range and we need to fallback to buffered.
  6871. */
  6872. if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
  6873. create)) {
  6874. ret = -ENOTBLK;
  6875. goto err;
  6876. }
  6877. em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
  6878. if (IS_ERR(em)) {
  6879. ret = PTR_ERR(em);
  6880. goto unlock_err;
  6881. }
  6882. /*
  6883. * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
  6884. * io. INLINE is special, and we could probably kludge it in here, but
  6885. * it's still buffered so for safety lets just fall back to the generic
  6886. * buffered path.
  6887. *
  6888. * For COMPRESSED we _have_ to read the entire extent in so we can
  6889. * decompress it, so there will be buffering required no matter what we
  6890. * do, so go ahead and fallback to buffered.
  6891. *
  6892. * We return -ENOTBLK because that's what makes DIO go ahead and go back
  6893. * to buffered IO. Don't blame me, this is the price we pay for using
  6894. * the generic code.
  6895. */
  6896. if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
  6897. em->block_start == EXTENT_MAP_INLINE) {
  6898. free_extent_map(em);
  6899. ret = -ENOTBLK;
  6900. goto unlock_err;
  6901. }
  6902. /* Just a good old fashioned hole, return */
  6903. if (!create && (em->block_start == EXTENT_MAP_HOLE ||
  6904. test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
  6905. free_extent_map(em);
  6906. goto unlock_err;
  6907. }
  6908. /*
  6909. * We don't allocate a new extent in the following cases
  6910. *
  6911. * 1) The inode is marked as NODATACOW. In this case we'll just use the
  6912. * existing extent.
  6913. * 2) The extent is marked as PREALLOC. We're good to go here and can
  6914. * just use the extent.
  6915. *
  6916. */
  6917. if (!create) {
  6918. len = min(len, em->len - (start - em->start));
  6919. lockstart = start + len;
  6920. goto unlock;
  6921. }
  6922. if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
  6923. ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
  6924. em->block_start != EXTENT_MAP_HOLE)) {
  6925. int type;
  6926. u64 block_start, orig_start, orig_block_len, ram_bytes;
  6927. if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
  6928. type = BTRFS_ORDERED_PREALLOC;
  6929. else
  6930. type = BTRFS_ORDERED_NOCOW;
  6931. len = min(len, em->len - (start - em->start));
  6932. block_start = em->block_start + (start - em->start);
  6933. if (can_nocow_extent(inode, start, &len, &orig_start,
  6934. &orig_block_len, &ram_bytes) == 1 &&
  6935. btrfs_inc_nocow_writers(fs_info, block_start)) {
  6936. struct extent_map *em2;
  6937. em2 = btrfs_create_dio_extent(inode, start, len,
  6938. orig_start, block_start,
  6939. len, orig_block_len,
  6940. ram_bytes, type);
  6941. btrfs_dec_nocow_writers(fs_info, block_start);
  6942. if (type == BTRFS_ORDERED_PREALLOC) {
  6943. free_extent_map(em);
  6944. em = em2;
  6945. }
  6946. if (em2 && IS_ERR(em2)) {
  6947. ret = PTR_ERR(em2);
  6948. goto unlock_err;
  6949. }
  6950. /*
  6951. * For inode marked NODATACOW or extent marked PREALLOC,
  6952. * use the existing or preallocated extent, so does not
  6953. * need to adjust btrfs_space_info's bytes_may_use.
  6954. */
  6955. btrfs_free_reserved_data_space_noquota(inode,
  6956. start, len);
  6957. goto unlock;
  6958. }
  6959. }
  6960. /*
  6961. * this will cow the extent, reset the len in case we changed
  6962. * it above
  6963. */
  6964. len = bh_result->b_size;
  6965. free_extent_map(em);
  6966. em = btrfs_new_extent_direct(inode, start, len);
  6967. if (IS_ERR(em)) {
  6968. ret = PTR_ERR(em);
  6969. goto unlock_err;
  6970. }
  6971. len = min(len, em->len - (start - em->start));
  6972. unlock:
  6973. bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
  6974. inode->i_blkbits;
  6975. bh_result->b_size = len;
  6976. bh_result->b_bdev = em->bdev;
  6977. set_buffer_mapped(bh_result);
  6978. if (create) {
  6979. if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
  6980. set_buffer_new(bh_result);
  6981. /*
  6982. * Need to update the i_size under the extent lock so buffered
  6983. * readers will get the updated i_size when we unlock.
  6984. */
  6985. if (!dio_data->overwrite && start + len > i_size_read(inode))
  6986. i_size_write(inode, start + len);
  6987. WARN_ON(dio_data->reserve < len);
  6988. dio_data->reserve -= len;
  6989. dio_data->unsubmitted_oe_range_end = start + len;
  6990. current->journal_info = dio_data;
  6991. }
  6992. /*
  6993. * In the case of write we need to clear and unlock the entire range,
  6994. * in the case of read we need to unlock only the end area that we
  6995. * aren't using if there is any left over space.
  6996. */
  6997. if (lockstart < lockend) {
  6998. clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
  6999. lockend, unlock_bits, 1, 0,
  7000. &cached_state);
  7001. } else {
  7002. free_extent_state(cached_state);
  7003. }
  7004. free_extent_map(em);
  7005. return 0;
  7006. unlock_err:
  7007. clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  7008. unlock_bits, 1, 0, &cached_state);
  7009. err:
  7010. if (dio_data)
  7011. current->journal_info = dio_data;
  7012. return ret;
  7013. }
  7014. static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
  7015. struct bio *bio,
  7016. int mirror_num)
  7017. {
  7018. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  7019. blk_status_t ret;
  7020. BUG_ON(bio_op(bio) == REQ_OP_WRITE);
  7021. bio_get(bio);
  7022. ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
  7023. if (ret)
  7024. goto err;
  7025. ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
  7026. err:
  7027. bio_put(bio);
  7028. return ret;
  7029. }
  7030. static int btrfs_check_dio_repairable(struct inode *inode,
  7031. struct bio *failed_bio,
  7032. struct io_failure_record *failrec,
  7033. int failed_mirror)
  7034. {
  7035. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  7036. int num_copies;
  7037. num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
  7038. if (num_copies == 1) {
  7039. /*
  7040. * we only have a single copy of the data, so don't bother with
  7041. * all the retry and error correction code that follows. no
  7042. * matter what the error is, it is very likely to persist.
  7043. */
  7044. btrfs_debug(fs_info,
  7045. "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
  7046. num_copies, failrec->this_mirror, failed_mirror);
  7047. return 0;
  7048. }
  7049. failrec->failed_mirror = failed_mirror;
  7050. failrec->this_mirror++;
  7051. if (failrec->this_mirror == failed_mirror)
  7052. failrec->this_mirror++;
  7053. if (failrec->this_mirror > num_copies) {
  7054. btrfs_debug(fs_info,
  7055. "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
  7056. num_copies, failrec->this_mirror, failed_mirror);
  7057. return 0;
  7058. }
  7059. return 1;
  7060. }
  7061. static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
  7062. struct page *page, unsigned int pgoff,
  7063. u64 start, u64 end, int failed_mirror,
  7064. bio_end_io_t *repair_endio, void *repair_arg)
  7065. {
  7066. struct io_failure_record *failrec;
  7067. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  7068. struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
  7069. struct bio *bio;
  7070. int isector;
  7071. unsigned int read_mode = 0;
  7072. int segs;
  7073. int ret;
  7074. blk_status_t status;
  7075. BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
  7076. ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
  7077. if (ret)
  7078. return errno_to_blk_status(ret);
  7079. ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
  7080. failed_mirror);
  7081. if (!ret) {
  7082. free_io_failure(failure_tree, io_tree, failrec);
  7083. return BLK_STS_IOERR;
  7084. }
  7085. segs = bio_segments(failed_bio);
  7086. if (segs > 1 ||
  7087. (failed_bio->bi_io_vec->bv_len > btrfs_inode_sectorsize(inode)))
  7088. read_mode |= REQ_FAILFAST_DEV;
  7089. isector = start - btrfs_io_bio(failed_bio)->logical;
  7090. isector >>= inode->i_sb->s_blocksize_bits;
  7091. bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
  7092. pgoff, isector, repair_endio, repair_arg);
  7093. bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
  7094. btrfs_debug(BTRFS_I(inode)->root->fs_info,
  7095. "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
  7096. read_mode, failrec->this_mirror, failrec->in_validation);
  7097. status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
  7098. if (status) {
  7099. free_io_failure(failure_tree, io_tree, failrec);
  7100. bio_put(bio);
  7101. }
  7102. return status;
  7103. }
  7104. struct btrfs_retry_complete {
  7105. struct completion done;
  7106. struct inode *inode;
  7107. u64 start;
  7108. int uptodate;
  7109. };
  7110. static void btrfs_retry_endio_nocsum(struct bio *bio)
  7111. {
  7112. struct btrfs_retry_complete *done = bio->bi_private;
  7113. struct inode *inode = done->inode;
  7114. struct bio_vec *bvec;
  7115. struct extent_io_tree *io_tree, *failure_tree;
  7116. int i;
  7117. if (bio->bi_status)
  7118. goto end;
  7119. ASSERT(bio->bi_vcnt == 1);
  7120. io_tree = &BTRFS_I(inode)->io_tree;
  7121. failure_tree = &BTRFS_I(inode)->io_failure_tree;
  7122. ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(inode));
  7123. done->uptodate = 1;
  7124. ASSERT(!bio_flagged(bio, BIO_CLONED));
  7125. bio_for_each_segment_all(bvec, bio, i)
  7126. clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
  7127. io_tree, done->start, bvec->bv_page,
  7128. btrfs_ino(BTRFS_I(inode)), 0);
  7129. end:
  7130. complete(&done->done);
  7131. bio_put(bio);
  7132. }
  7133. static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
  7134. struct btrfs_io_bio *io_bio)
  7135. {
  7136. struct btrfs_fs_info *fs_info;
  7137. struct bio_vec bvec;
  7138. struct bvec_iter iter;
  7139. struct btrfs_retry_complete done;
  7140. u64 start;
  7141. unsigned int pgoff;
  7142. u32 sectorsize;
  7143. int nr_sectors;
  7144. blk_status_t ret;
  7145. blk_status_t err = BLK_STS_OK;
  7146. fs_info = BTRFS_I(inode)->root->fs_info;
  7147. sectorsize = fs_info->sectorsize;
  7148. start = io_bio->logical;
  7149. done.inode = inode;
  7150. io_bio->bio.bi_iter = io_bio->iter;
  7151. bio_for_each_segment(bvec, &io_bio->bio, iter) {
  7152. nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
  7153. pgoff = bvec.bv_offset;
  7154. next_block_or_try_again:
  7155. done.uptodate = 0;
  7156. done.start = start;
  7157. init_completion(&done.done);
  7158. ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
  7159. pgoff, start, start + sectorsize - 1,
  7160. io_bio->mirror_num,
  7161. btrfs_retry_endio_nocsum, &done);
  7162. if (ret) {
  7163. err = ret;
  7164. goto next;
  7165. }
  7166. wait_for_completion_io(&done.done);
  7167. if (!done.uptodate) {
  7168. /* We might have another mirror, so try again */
  7169. goto next_block_or_try_again;
  7170. }
  7171. next:
  7172. start += sectorsize;
  7173. nr_sectors--;
  7174. if (nr_sectors) {
  7175. pgoff += sectorsize;
  7176. ASSERT(pgoff < PAGE_SIZE);
  7177. goto next_block_or_try_again;
  7178. }
  7179. }
  7180. return err;
  7181. }
  7182. static void btrfs_retry_endio(struct bio *bio)
  7183. {
  7184. struct btrfs_retry_complete *done = bio->bi_private;
  7185. struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
  7186. struct extent_io_tree *io_tree, *failure_tree;
  7187. struct inode *inode = done->inode;
  7188. struct bio_vec *bvec;
  7189. int uptodate;
  7190. int ret;
  7191. int i;
  7192. if (bio->bi_status)
  7193. goto end;
  7194. uptodate = 1;
  7195. ASSERT(bio->bi_vcnt == 1);
  7196. ASSERT(bio->bi_io_vec->bv_len == btrfs_inode_sectorsize(done->inode));
  7197. io_tree = &BTRFS_I(inode)->io_tree;
  7198. failure_tree = &BTRFS_I(inode)->io_failure_tree;
  7199. ASSERT(!bio_flagged(bio, BIO_CLONED));
  7200. bio_for_each_segment_all(bvec, bio, i) {
  7201. ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
  7202. bvec->bv_offset, done->start,
  7203. bvec->bv_len);
  7204. if (!ret)
  7205. clean_io_failure(BTRFS_I(inode)->root->fs_info,
  7206. failure_tree, io_tree, done->start,
  7207. bvec->bv_page,
  7208. btrfs_ino(BTRFS_I(inode)),
  7209. bvec->bv_offset);
  7210. else
  7211. uptodate = 0;
  7212. }
  7213. done->uptodate = uptodate;
  7214. end:
  7215. complete(&done->done);
  7216. bio_put(bio);
  7217. }
  7218. static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
  7219. struct btrfs_io_bio *io_bio, blk_status_t err)
  7220. {
  7221. struct btrfs_fs_info *fs_info;
  7222. struct bio_vec bvec;
  7223. struct bvec_iter iter;
  7224. struct btrfs_retry_complete done;
  7225. u64 start;
  7226. u64 offset = 0;
  7227. u32 sectorsize;
  7228. int nr_sectors;
  7229. unsigned int pgoff;
  7230. int csum_pos;
  7231. bool uptodate = (err == 0);
  7232. int ret;
  7233. blk_status_t status;
  7234. fs_info = BTRFS_I(inode)->root->fs_info;
  7235. sectorsize = fs_info->sectorsize;
  7236. err = BLK_STS_OK;
  7237. start = io_bio->logical;
  7238. done.inode = inode;
  7239. io_bio->bio.bi_iter = io_bio->iter;
  7240. bio_for_each_segment(bvec, &io_bio->bio, iter) {
  7241. nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
  7242. pgoff = bvec.bv_offset;
  7243. next_block:
  7244. if (uptodate) {
  7245. csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
  7246. ret = __readpage_endio_check(inode, io_bio, csum_pos,
  7247. bvec.bv_page, pgoff, start, sectorsize);
  7248. if (likely(!ret))
  7249. goto next;
  7250. }
  7251. try_again:
  7252. done.uptodate = 0;
  7253. done.start = start;
  7254. init_completion(&done.done);
  7255. status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
  7256. pgoff, start, start + sectorsize - 1,
  7257. io_bio->mirror_num, btrfs_retry_endio,
  7258. &done);
  7259. if (status) {
  7260. err = status;
  7261. goto next;
  7262. }
  7263. wait_for_completion_io(&done.done);
  7264. if (!done.uptodate) {
  7265. /* We might have another mirror, so try again */
  7266. goto try_again;
  7267. }
  7268. next:
  7269. offset += sectorsize;
  7270. start += sectorsize;
  7271. ASSERT(nr_sectors);
  7272. nr_sectors--;
  7273. if (nr_sectors) {
  7274. pgoff += sectorsize;
  7275. ASSERT(pgoff < PAGE_SIZE);
  7276. goto next_block;
  7277. }
  7278. }
  7279. return err;
  7280. }
  7281. static blk_status_t btrfs_subio_endio_read(struct inode *inode,
  7282. struct btrfs_io_bio *io_bio, blk_status_t err)
  7283. {
  7284. bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
  7285. if (skip_csum) {
  7286. if (unlikely(err))
  7287. return __btrfs_correct_data_nocsum(inode, io_bio);
  7288. else
  7289. return BLK_STS_OK;
  7290. } else {
  7291. return __btrfs_subio_endio_read(inode, io_bio, err);
  7292. }
  7293. }
  7294. static void btrfs_endio_direct_read(struct bio *bio)
  7295. {
  7296. struct btrfs_dio_private *dip = bio->bi_private;
  7297. struct inode *inode = dip->inode;
  7298. struct bio *dio_bio;
  7299. struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
  7300. blk_status_t err = bio->bi_status;
  7301. if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
  7302. err = btrfs_subio_endio_read(inode, io_bio, err);
  7303. unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
  7304. dip->logical_offset + dip->bytes - 1);
  7305. dio_bio = dip->dio_bio;
  7306. kfree(dip);
  7307. dio_bio->bi_status = err;
  7308. dio_end_io(dio_bio);
  7309. if (io_bio->end_io)
  7310. io_bio->end_io(io_bio, blk_status_to_errno(err));
  7311. bio_put(bio);
  7312. }
  7313. static void __endio_write_update_ordered(struct inode *inode,
  7314. const u64 offset, const u64 bytes,
  7315. const bool uptodate)
  7316. {
  7317. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  7318. struct btrfs_ordered_extent *ordered = NULL;
  7319. struct btrfs_workqueue *wq;
  7320. btrfs_work_func_t func;
  7321. u64 ordered_offset = offset;
  7322. u64 ordered_bytes = bytes;
  7323. u64 last_offset;
  7324. int ret;
  7325. if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
  7326. wq = fs_info->endio_freespace_worker;
  7327. func = btrfs_freespace_write_helper;
  7328. } else {
  7329. wq = fs_info->endio_write_workers;
  7330. func = btrfs_endio_write_helper;
  7331. }
  7332. again:
  7333. last_offset = ordered_offset;
  7334. ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
  7335. &ordered_offset,
  7336. ordered_bytes,
  7337. uptodate);
  7338. if (!ret)
  7339. goto out_test;
  7340. btrfs_init_work(&ordered->work, func, finish_ordered_fn, NULL, NULL);
  7341. btrfs_queue_work(wq, &ordered->work);
  7342. out_test:
  7343. /*
  7344. * If btrfs_dec_test_ordered_pending does not find any ordered extent
  7345. * in the range, we can exit.
  7346. */
  7347. if (ordered_offset == last_offset)
  7348. return;
  7349. /*
  7350. * our bio might span multiple ordered extents. If we haven't
  7351. * completed the accounting for the whole dio, go back and try again
  7352. */
  7353. if (ordered_offset < offset + bytes) {
  7354. ordered_bytes = offset + bytes - ordered_offset;
  7355. ordered = NULL;
  7356. goto again;
  7357. }
  7358. }
  7359. static void btrfs_endio_direct_write(struct bio *bio)
  7360. {
  7361. struct btrfs_dio_private *dip = bio->bi_private;
  7362. struct bio *dio_bio = dip->dio_bio;
  7363. __endio_write_update_ordered(dip->inode, dip->logical_offset,
  7364. dip->bytes, !bio->bi_status);
  7365. kfree(dip);
  7366. dio_bio->bi_status = bio->bi_status;
  7367. dio_end_io(dio_bio);
  7368. bio_put(bio);
  7369. }
  7370. static blk_status_t __btrfs_submit_bio_start_direct_io(void *private_data,
  7371. struct bio *bio, int mirror_num,
  7372. unsigned long bio_flags, u64 offset)
  7373. {
  7374. struct inode *inode = private_data;
  7375. blk_status_t ret;
  7376. ret = btrfs_csum_one_bio(inode, bio, offset, 1);
  7377. BUG_ON(ret); /* -ENOMEM */
  7378. return 0;
  7379. }
  7380. static void btrfs_end_dio_bio(struct bio *bio)
  7381. {
  7382. struct btrfs_dio_private *dip = bio->bi_private;
  7383. blk_status_t err = bio->bi_status;
  7384. if (err)
  7385. btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
  7386. "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
  7387. btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
  7388. bio->bi_opf,
  7389. (unsigned long long)bio->bi_iter.bi_sector,
  7390. bio->bi_iter.bi_size, err);
  7391. if (dip->subio_endio)
  7392. err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
  7393. if (err) {
  7394. dip->errors = 1;
  7395. /*
  7396. * before atomic variable goto zero, we must make sure
  7397. * dip->errors is perceived to be set.
  7398. */
  7399. smp_mb__before_atomic();
  7400. }
  7401. /* if there are more bios still pending for this dio, just exit */
  7402. if (!atomic_dec_and_test(&dip->pending_bios))
  7403. goto out;
  7404. if (dip->errors) {
  7405. bio_io_error(dip->orig_bio);
  7406. } else {
  7407. dip->dio_bio->bi_status = BLK_STS_OK;
  7408. bio_endio(dip->orig_bio);
  7409. }
  7410. out:
  7411. bio_put(bio);
  7412. }
  7413. static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
  7414. struct btrfs_dio_private *dip,
  7415. struct bio *bio,
  7416. u64 file_offset)
  7417. {
  7418. struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
  7419. struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
  7420. blk_status_t ret;
  7421. /*
  7422. * We load all the csum data we need when we submit
  7423. * the first bio to reduce the csum tree search and
  7424. * contention.
  7425. */
  7426. if (dip->logical_offset == file_offset) {
  7427. ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
  7428. file_offset);
  7429. if (ret)
  7430. return ret;
  7431. }
  7432. if (bio == dip->orig_bio)
  7433. return 0;
  7434. file_offset -= dip->logical_offset;
  7435. file_offset >>= inode->i_sb->s_blocksize_bits;
  7436. io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
  7437. return 0;
  7438. }
  7439. static inline blk_status_t
  7440. __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode, u64 file_offset,
  7441. int async_submit)
  7442. {
  7443. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  7444. struct btrfs_dio_private *dip = bio->bi_private;
  7445. bool write = bio_op(bio) == REQ_OP_WRITE;
  7446. blk_status_t ret;
  7447. /* Check btrfs_submit_bio_hook() for rules about async submit. */
  7448. if (async_submit)
  7449. async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
  7450. bio_get(bio);
  7451. if (!write) {
  7452. ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
  7453. if (ret)
  7454. goto err;
  7455. }
  7456. if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
  7457. goto map;
  7458. if (write && async_submit) {
  7459. ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
  7460. file_offset, inode,
  7461. __btrfs_submit_bio_start_direct_io,
  7462. __btrfs_submit_bio_done);
  7463. goto err;
  7464. } else if (write) {
  7465. /*
  7466. * If we aren't doing async submit, calculate the csum of the
  7467. * bio now.
  7468. */
  7469. ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
  7470. if (ret)
  7471. goto err;
  7472. } else {
  7473. ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
  7474. file_offset);
  7475. if (ret)
  7476. goto err;
  7477. }
  7478. map:
  7479. ret = btrfs_map_bio(fs_info, bio, 0, 0);
  7480. err:
  7481. bio_put(bio);
  7482. return ret;
  7483. }
  7484. static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
  7485. {
  7486. struct inode *inode = dip->inode;
  7487. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  7488. struct bio *bio;
  7489. struct bio *orig_bio = dip->orig_bio;
  7490. u64 start_sector = orig_bio->bi_iter.bi_sector;
  7491. u64 file_offset = dip->logical_offset;
  7492. u64 map_length;
  7493. int async_submit = 0;
  7494. u64 submit_len;
  7495. int clone_offset = 0;
  7496. int clone_len;
  7497. int ret;
  7498. blk_status_t status;
  7499. map_length = orig_bio->bi_iter.bi_size;
  7500. submit_len = map_length;
  7501. ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
  7502. &map_length, NULL, 0);
  7503. if (ret)
  7504. return -EIO;
  7505. if (map_length >= submit_len) {
  7506. bio = orig_bio;
  7507. dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
  7508. goto submit;
  7509. }
  7510. /* async crcs make it difficult to collect full stripe writes. */
  7511. if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
  7512. async_submit = 0;
  7513. else
  7514. async_submit = 1;
  7515. /* bio split */
  7516. ASSERT(map_length <= INT_MAX);
  7517. atomic_inc(&dip->pending_bios);
  7518. do {
  7519. clone_len = min_t(int, submit_len, map_length);
  7520. /*
  7521. * This will never fail as it's passing GPF_NOFS and
  7522. * the allocation is backed by btrfs_bioset.
  7523. */
  7524. bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
  7525. clone_len);
  7526. bio->bi_private = dip;
  7527. bio->bi_end_io = btrfs_end_dio_bio;
  7528. btrfs_io_bio(bio)->logical = file_offset;
  7529. ASSERT(submit_len >= clone_len);
  7530. submit_len -= clone_len;
  7531. if (submit_len == 0)
  7532. break;
  7533. /*
  7534. * Increase the count before we submit the bio so we know
  7535. * the end IO handler won't happen before we increase the
  7536. * count. Otherwise, the dip might get freed before we're
  7537. * done setting it up.
  7538. */
  7539. atomic_inc(&dip->pending_bios);
  7540. status = __btrfs_submit_dio_bio(bio, inode, file_offset,
  7541. async_submit);
  7542. if (status) {
  7543. bio_put(bio);
  7544. atomic_dec(&dip->pending_bios);
  7545. goto out_err;
  7546. }
  7547. clone_offset += clone_len;
  7548. start_sector += clone_len >> 9;
  7549. file_offset += clone_len;
  7550. map_length = submit_len;
  7551. ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
  7552. start_sector << 9, &map_length, NULL, 0);
  7553. if (ret)
  7554. goto out_err;
  7555. } while (submit_len > 0);
  7556. submit:
  7557. status = __btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
  7558. if (!status)
  7559. return 0;
  7560. bio_put(bio);
  7561. out_err:
  7562. dip->errors = 1;
  7563. /*
  7564. * before atomic variable goto zero, we must
  7565. * make sure dip->errors is perceived to be set.
  7566. */
  7567. smp_mb__before_atomic();
  7568. if (atomic_dec_and_test(&dip->pending_bios))
  7569. bio_io_error(dip->orig_bio);
  7570. /* bio_end_io() will handle error, so we needn't return it */
  7571. return 0;
  7572. }
  7573. static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
  7574. loff_t file_offset)
  7575. {
  7576. struct btrfs_dio_private *dip = NULL;
  7577. struct bio *bio = NULL;
  7578. struct btrfs_io_bio *io_bio;
  7579. bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
  7580. int ret = 0;
  7581. bio = btrfs_bio_clone(dio_bio);
  7582. dip = kzalloc(sizeof(*dip), GFP_NOFS);
  7583. if (!dip) {
  7584. ret = -ENOMEM;
  7585. goto free_ordered;
  7586. }
  7587. dip->private = dio_bio->bi_private;
  7588. dip->inode = inode;
  7589. dip->logical_offset = file_offset;
  7590. dip->bytes = dio_bio->bi_iter.bi_size;
  7591. dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
  7592. bio->bi_private = dip;
  7593. dip->orig_bio = bio;
  7594. dip->dio_bio = dio_bio;
  7595. atomic_set(&dip->pending_bios, 0);
  7596. io_bio = btrfs_io_bio(bio);
  7597. io_bio->logical = file_offset;
  7598. if (write) {
  7599. bio->bi_end_io = btrfs_endio_direct_write;
  7600. } else {
  7601. bio->bi_end_io = btrfs_endio_direct_read;
  7602. dip->subio_endio = btrfs_subio_endio_read;
  7603. }
  7604. /*
  7605. * Reset the range for unsubmitted ordered extents (to a 0 length range)
  7606. * even if we fail to submit a bio, because in such case we do the
  7607. * corresponding error handling below and it must not be done a second
  7608. * time by btrfs_direct_IO().
  7609. */
  7610. if (write) {
  7611. struct btrfs_dio_data *dio_data = current->journal_info;
  7612. dio_data->unsubmitted_oe_range_end = dip->logical_offset +
  7613. dip->bytes;
  7614. dio_data->unsubmitted_oe_range_start =
  7615. dio_data->unsubmitted_oe_range_end;
  7616. }
  7617. ret = btrfs_submit_direct_hook(dip);
  7618. if (!ret)
  7619. return;
  7620. if (io_bio->end_io)
  7621. io_bio->end_io(io_bio, ret);
  7622. free_ordered:
  7623. /*
  7624. * If we arrived here it means either we failed to submit the dip
  7625. * or we either failed to clone the dio_bio or failed to allocate the
  7626. * dip. If we cloned the dio_bio and allocated the dip, we can just
  7627. * call bio_endio against our io_bio so that we get proper resource
  7628. * cleanup if we fail to submit the dip, otherwise, we must do the
  7629. * same as btrfs_endio_direct_[write|read] because we can't call these
  7630. * callbacks - they require an allocated dip and a clone of dio_bio.
  7631. */
  7632. if (bio && dip) {
  7633. bio_io_error(bio);
  7634. /*
  7635. * The end io callbacks free our dip, do the final put on bio
  7636. * and all the cleanup and final put for dio_bio (through
  7637. * dio_end_io()).
  7638. */
  7639. dip = NULL;
  7640. bio = NULL;
  7641. } else {
  7642. if (write)
  7643. __endio_write_update_ordered(inode,
  7644. file_offset,
  7645. dio_bio->bi_iter.bi_size,
  7646. false);
  7647. else
  7648. unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
  7649. file_offset + dio_bio->bi_iter.bi_size - 1);
  7650. dio_bio->bi_status = BLK_STS_IOERR;
  7651. /*
  7652. * Releases and cleans up our dio_bio, no need to bio_put()
  7653. * nor bio_endio()/bio_io_error() against dio_bio.
  7654. */
  7655. dio_end_io(dio_bio);
  7656. }
  7657. if (bio)
  7658. bio_put(bio);
  7659. kfree(dip);
  7660. }
  7661. static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
  7662. const struct iov_iter *iter, loff_t offset)
  7663. {
  7664. int seg;
  7665. int i;
  7666. unsigned int blocksize_mask = fs_info->sectorsize - 1;
  7667. ssize_t retval = -EINVAL;
  7668. if (offset & blocksize_mask)
  7669. goto out;
  7670. if (iov_iter_alignment(iter) & blocksize_mask)
  7671. goto out;
  7672. /* If this is a write we don't need to check anymore */
  7673. if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
  7674. return 0;
  7675. /*
  7676. * Check to make sure we don't have duplicate iov_base's in this
  7677. * iovec, if so return EINVAL, otherwise we'll get csum errors
  7678. * when reading back.
  7679. */
  7680. for (seg = 0; seg < iter->nr_segs; seg++) {
  7681. for (i = seg + 1; i < iter->nr_segs; i++) {
  7682. if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
  7683. goto out;
  7684. }
  7685. }
  7686. retval = 0;
  7687. out:
  7688. return retval;
  7689. }
  7690. static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
  7691. {
  7692. struct file *file = iocb->ki_filp;
  7693. struct inode *inode = file->f_mapping->host;
  7694. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  7695. struct btrfs_dio_data dio_data = { 0 };
  7696. struct extent_changeset *data_reserved = NULL;
  7697. loff_t offset = iocb->ki_pos;
  7698. size_t count = 0;
  7699. int flags = 0;
  7700. bool wakeup = true;
  7701. bool relock = false;
  7702. ssize_t ret;
  7703. if (check_direct_IO(fs_info, iter, offset))
  7704. return 0;
  7705. inode_dio_begin(inode);
  7706. /*
  7707. * The generic stuff only does filemap_write_and_wait_range, which
  7708. * isn't enough if we've written compressed pages to this area, so
  7709. * we need to flush the dirty pages again to make absolutely sure
  7710. * that any outstanding dirty pages are on disk.
  7711. */
  7712. count = iov_iter_count(iter);
  7713. if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
  7714. &BTRFS_I(inode)->runtime_flags))
  7715. filemap_fdatawrite_range(inode->i_mapping, offset,
  7716. offset + count - 1);
  7717. if (iov_iter_rw(iter) == WRITE) {
  7718. /*
  7719. * If the write DIO is beyond the EOF, we need update
  7720. * the isize, but it is protected by i_mutex. So we can
  7721. * not unlock the i_mutex at this case.
  7722. */
  7723. if (offset + count <= inode->i_size) {
  7724. dio_data.overwrite = 1;
  7725. inode_unlock(inode);
  7726. relock = true;
  7727. } else if (iocb->ki_flags & IOCB_NOWAIT) {
  7728. ret = -EAGAIN;
  7729. goto out;
  7730. }
  7731. ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
  7732. offset, count);
  7733. if (ret)
  7734. goto out;
  7735. /*
  7736. * We need to know how many extents we reserved so that we can
  7737. * do the accounting properly if we go over the number we
  7738. * originally calculated. Abuse current->journal_info for this.
  7739. */
  7740. dio_data.reserve = round_up(count,
  7741. fs_info->sectorsize);
  7742. dio_data.unsubmitted_oe_range_start = (u64)offset;
  7743. dio_data.unsubmitted_oe_range_end = (u64)offset;
  7744. current->journal_info = &dio_data;
  7745. down_read(&BTRFS_I(inode)->dio_sem);
  7746. } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
  7747. &BTRFS_I(inode)->runtime_flags)) {
  7748. inode_dio_end(inode);
  7749. flags = DIO_LOCKING | DIO_SKIP_HOLES;
  7750. wakeup = false;
  7751. }
  7752. ret = __blockdev_direct_IO(iocb, inode,
  7753. fs_info->fs_devices->latest_bdev,
  7754. iter, btrfs_get_blocks_direct, NULL,
  7755. btrfs_submit_direct, flags);
  7756. if (iov_iter_rw(iter) == WRITE) {
  7757. up_read(&BTRFS_I(inode)->dio_sem);
  7758. current->journal_info = NULL;
  7759. if (ret < 0 && ret != -EIOCBQUEUED) {
  7760. if (dio_data.reserve)
  7761. btrfs_delalloc_release_space(inode, data_reserved,
  7762. offset, dio_data.reserve);
  7763. /*
  7764. * On error we might have left some ordered extents
  7765. * without submitting corresponding bios for them, so
  7766. * cleanup them up to avoid other tasks getting them
  7767. * and waiting for them to complete forever.
  7768. */
  7769. if (dio_data.unsubmitted_oe_range_start <
  7770. dio_data.unsubmitted_oe_range_end)
  7771. __endio_write_update_ordered(inode,
  7772. dio_data.unsubmitted_oe_range_start,
  7773. dio_data.unsubmitted_oe_range_end -
  7774. dio_data.unsubmitted_oe_range_start,
  7775. false);
  7776. } else if (ret >= 0 && (size_t)ret < count)
  7777. btrfs_delalloc_release_space(inode, data_reserved,
  7778. offset, count - (size_t)ret);
  7779. btrfs_delalloc_release_extents(BTRFS_I(inode), count);
  7780. }
  7781. out:
  7782. if (wakeup)
  7783. inode_dio_end(inode);
  7784. if (relock)
  7785. inode_lock(inode);
  7786. extent_changeset_free(data_reserved);
  7787. return ret;
  7788. }
  7789. #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
  7790. static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
  7791. __u64 start, __u64 len)
  7792. {
  7793. int ret;
  7794. ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
  7795. if (ret)
  7796. return ret;
  7797. return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
  7798. }
  7799. int btrfs_readpage(struct file *file, struct page *page)
  7800. {
  7801. struct extent_io_tree *tree;
  7802. tree = &BTRFS_I(page->mapping->host)->io_tree;
  7803. return extent_read_full_page(tree, page, btrfs_get_extent, 0);
  7804. }
  7805. static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
  7806. {
  7807. struct extent_io_tree *tree;
  7808. struct inode *inode = page->mapping->host;
  7809. int ret;
  7810. if (current->flags & PF_MEMALLOC) {
  7811. redirty_page_for_writepage(wbc, page);
  7812. unlock_page(page);
  7813. return 0;
  7814. }
  7815. /*
  7816. * If we are under memory pressure we will call this directly from the
  7817. * VM, we need to make sure we have the inode referenced for the ordered
  7818. * extent. If not just return like we didn't do anything.
  7819. */
  7820. if (!igrab(inode)) {
  7821. redirty_page_for_writepage(wbc, page);
  7822. return AOP_WRITEPAGE_ACTIVATE;
  7823. }
  7824. tree = &BTRFS_I(page->mapping->host)->io_tree;
  7825. ret = extent_write_full_page(tree, page, btrfs_get_extent, wbc);
  7826. btrfs_add_delayed_iput(inode);
  7827. return ret;
  7828. }
  7829. static int btrfs_writepages(struct address_space *mapping,
  7830. struct writeback_control *wbc)
  7831. {
  7832. struct extent_io_tree *tree;
  7833. tree = &BTRFS_I(mapping->host)->io_tree;
  7834. return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
  7835. }
  7836. static int
  7837. btrfs_readpages(struct file *file, struct address_space *mapping,
  7838. struct list_head *pages, unsigned nr_pages)
  7839. {
  7840. struct extent_io_tree *tree;
  7841. tree = &BTRFS_I(mapping->host)->io_tree;
  7842. return extent_readpages(tree, mapping, pages, nr_pages,
  7843. btrfs_get_extent);
  7844. }
  7845. static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
  7846. {
  7847. struct extent_io_tree *tree;
  7848. struct extent_map_tree *map;
  7849. int ret;
  7850. tree = &BTRFS_I(page->mapping->host)->io_tree;
  7851. map = &BTRFS_I(page->mapping->host)->extent_tree;
  7852. ret = try_release_extent_mapping(map, tree, page, gfp_flags);
  7853. if (ret == 1) {
  7854. ClearPagePrivate(page);
  7855. set_page_private(page, 0);
  7856. put_page(page);
  7857. }
  7858. return ret;
  7859. }
  7860. static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
  7861. {
  7862. if (PageWriteback(page) || PageDirty(page))
  7863. return 0;
  7864. return __btrfs_releasepage(page, gfp_flags);
  7865. }
  7866. static void btrfs_invalidatepage(struct page *page, unsigned int offset,
  7867. unsigned int length)
  7868. {
  7869. struct inode *inode = page->mapping->host;
  7870. struct extent_io_tree *tree;
  7871. struct btrfs_ordered_extent *ordered;
  7872. struct extent_state *cached_state = NULL;
  7873. u64 page_start = page_offset(page);
  7874. u64 page_end = page_start + PAGE_SIZE - 1;
  7875. u64 start;
  7876. u64 end;
  7877. int inode_evicting = inode->i_state & I_FREEING;
  7878. /*
  7879. * we have the page locked, so new writeback can't start,
  7880. * and the dirty bit won't be cleared while we are here.
  7881. *
  7882. * Wait for IO on this page so that we can safely clear
  7883. * the PagePrivate2 bit and do ordered accounting
  7884. */
  7885. wait_on_page_writeback(page);
  7886. tree = &BTRFS_I(inode)->io_tree;
  7887. if (offset) {
  7888. btrfs_releasepage(page, GFP_NOFS);
  7889. return;
  7890. }
  7891. if (!inode_evicting)
  7892. lock_extent_bits(tree, page_start, page_end, &cached_state);
  7893. again:
  7894. start = page_start;
  7895. ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
  7896. page_end - start + 1);
  7897. if (ordered) {
  7898. end = min(page_end, ordered->file_offset + ordered->len - 1);
  7899. /*
  7900. * IO on this page will never be started, so we need
  7901. * to account for any ordered extents now
  7902. */
  7903. if (!inode_evicting)
  7904. clear_extent_bit(tree, start, end,
  7905. EXTENT_DIRTY | EXTENT_DELALLOC |
  7906. EXTENT_DELALLOC_NEW |
  7907. EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
  7908. EXTENT_DEFRAG, 1, 0, &cached_state);
  7909. /*
  7910. * whoever cleared the private bit is responsible
  7911. * for the finish_ordered_io
  7912. */
  7913. if (TestClearPagePrivate2(page)) {
  7914. struct btrfs_ordered_inode_tree *tree;
  7915. u64 new_len;
  7916. tree = &BTRFS_I(inode)->ordered_tree;
  7917. spin_lock_irq(&tree->lock);
  7918. set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
  7919. new_len = start - ordered->file_offset;
  7920. if (new_len < ordered->truncated_len)
  7921. ordered->truncated_len = new_len;
  7922. spin_unlock_irq(&tree->lock);
  7923. if (btrfs_dec_test_ordered_pending(inode, &ordered,
  7924. start,
  7925. end - start + 1, 1))
  7926. btrfs_finish_ordered_io(ordered);
  7927. }
  7928. btrfs_put_ordered_extent(ordered);
  7929. if (!inode_evicting) {
  7930. cached_state = NULL;
  7931. lock_extent_bits(tree, start, end,
  7932. &cached_state);
  7933. }
  7934. start = end + 1;
  7935. if (start < page_end)
  7936. goto again;
  7937. }
  7938. /*
  7939. * Qgroup reserved space handler
  7940. * Page here will be either
  7941. * 1) Already written to disk
  7942. * In this case, its reserved space is released from data rsv map
  7943. * and will be freed by delayed_ref handler finally.
  7944. * So even we call qgroup_free_data(), it won't decrease reserved
  7945. * space.
  7946. * 2) Not written to disk
  7947. * This means the reserved space should be freed here. However,
  7948. * if a truncate invalidates the page (by clearing PageDirty)
  7949. * and the page is accounted for while allocating extent
  7950. * in btrfs_check_data_free_space() we let delayed_ref to
  7951. * free the entire extent.
  7952. */
  7953. if (PageDirty(page))
  7954. btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
  7955. if (!inode_evicting) {
  7956. clear_extent_bit(tree, page_start, page_end,
  7957. EXTENT_LOCKED | EXTENT_DIRTY |
  7958. EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
  7959. EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
  7960. &cached_state);
  7961. __btrfs_releasepage(page, GFP_NOFS);
  7962. }
  7963. ClearPageChecked(page);
  7964. if (PagePrivate(page)) {
  7965. ClearPagePrivate(page);
  7966. set_page_private(page, 0);
  7967. put_page(page);
  7968. }
  7969. }
  7970. /*
  7971. * btrfs_page_mkwrite() is not allowed to change the file size as it gets
  7972. * called from a page fault handler when a page is first dirtied. Hence we must
  7973. * be careful to check for EOF conditions here. We set the page up correctly
  7974. * for a written page which means we get ENOSPC checking when writing into
  7975. * holes and correct delalloc and unwritten extent mapping on filesystems that
  7976. * support these features.
  7977. *
  7978. * We are not allowed to take the i_mutex here so we have to play games to
  7979. * protect against truncate races as the page could now be beyond EOF. Because
  7980. * vmtruncate() writes the inode size before removing pages, once we have the
  7981. * page lock we can determine safely if the page is beyond EOF. If it is not
  7982. * beyond EOF, then the page is guaranteed safe against truncation until we
  7983. * unlock the page.
  7984. */
  7985. int btrfs_page_mkwrite(struct vm_fault *vmf)
  7986. {
  7987. struct page *page = vmf->page;
  7988. struct inode *inode = file_inode(vmf->vma->vm_file);
  7989. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  7990. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  7991. struct btrfs_ordered_extent *ordered;
  7992. struct extent_state *cached_state = NULL;
  7993. struct extent_changeset *data_reserved = NULL;
  7994. char *kaddr;
  7995. unsigned long zero_start;
  7996. loff_t size;
  7997. int ret;
  7998. int reserved = 0;
  7999. u64 reserved_space;
  8000. u64 page_start;
  8001. u64 page_end;
  8002. u64 end;
  8003. reserved_space = PAGE_SIZE;
  8004. sb_start_pagefault(inode->i_sb);
  8005. page_start = page_offset(page);
  8006. page_end = page_start + PAGE_SIZE - 1;
  8007. end = page_end;
  8008. /*
  8009. * Reserving delalloc space after obtaining the page lock can lead to
  8010. * deadlock. For example, if a dirty page is locked by this function
  8011. * and the call to btrfs_delalloc_reserve_space() ends up triggering
  8012. * dirty page write out, then the btrfs_writepage() function could
  8013. * end up waiting indefinitely to get a lock on the page currently
  8014. * being processed by btrfs_page_mkwrite() function.
  8015. */
  8016. ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
  8017. reserved_space);
  8018. if (!ret) {
  8019. ret = file_update_time(vmf->vma->vm_file);
  8020. reserved = 1;
  8021. }
  8022. if (ret) {
  8023. if (ret == -ENOMEM)
  8024. ret = VM_FAULT_OOM;
  8025. else /* -ENOSPC, -EIO, etc */
  8026. ret = VM_FAULT_SIGBUS;
  8027. if (reserved)
  8028. goto out;
  8029. goto out_noreserve;
  8030. }
  8031. ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
  8032. again:
  8033. lock_page(page);
  8034. size = i_size_read(inode);
  8035. if ((page->mapping != inode->i_mapping) ||
  8036. (page_start >= size)) {
  8037. /* page got truncated out from underneath us */
  8038. goto out_unlock;
  8039. }
  8040. wait_on_page_writeback(page);
  8041. lock_extent_bits(io_tree, page_start, page_end, &cached_state);
  8042. set_page_extent_mapped(page);
  8043. /*
  8044. * we can't set the delalloc bits if there are pending ordered
  8045. * extents. Drop our locks and wait for them to finish
  8046. */
  8047. ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
  8048. PAGE_SIZE);
  8049. if (ordered) {
  8050. unlock_extent_cached(io_tree, page_start, page_end,
  8051. &cached_state, GFP_NOFS);
  8052. unlock_page(page);
  8053. btrfs_start_ordered_extent(inode, ordered, 1);
  8054. btrfs_put_ordered_extent(ordered);
  8055. goto again;
  8056. }
  8057. if (page->index == ((size - 1) >> PAGE_SHIFT)) {
  8058. reserved_space = round_up(size - page_start,
  8059. fs_info->sectorsize);
  8060. if (reserved_space < PAGE_SIZE) {
  8061. end = page_start + reserved_space - 1;
  8062. btrfs_delalloc_release_space(inode, data_reserved,
  8063. page_start, PAGE_SIZE - reserved_space);
  8064. }
  8065. }
  8066. /*
  8067. * page_mkwrite gets called when the page is firstly dirtied after it's
  8068. * faulted in, but write(2) could also dirty a page and set delalloc
  8069. * bits, thus in this case for space account reason, we still need to
  8070. * clear any delalloc bits within this page range since we have to
  8071. * reserve data&meta space before lock_page() (see above comments).
  8072. */
  8073. clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
  8074. EXTENT_DIRTY | EXTENT_DELALLOC |
  8075. EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
  8076. 0, 0, &cached_state);
  8077. ret = btrfs_set_extent_delalloc(inode, page_start, end, 0,
  8078. &cached_state, 0);
  8079. if (ret) {
  8080. unlock_extent_cached(io_tree, page_start, page_end,
  8081. &cached_state, GFP_NOFS);
  8082. ret = VM_FAULT_SIGBUS;
  8083. goto out_unlock;
  8084. }
  8085. ret = 0;
  8086. /* page is wholly or partially inside EOF */
  8087. if (page_start + PAGE_SIZE > size)
  8088. zero_start = size & ~PAGE_MASK;
  8089. else
  8090. zero_start = PAGE_SIZE;
  8091. if (zero_start != PAGE_SIZE) {
  8092. kaddr = kmap(page);
  8093. memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
  8094. flush_dcache_page(page);
  8095. kunmap(page);
  8096. }
  8097. ClearPageChecked(page);
  8098. set_page_dirty(page);
  8099. SetPageUptodate(page);
  8100. BTRFS_I(inode)->last_trans = fs_info->generation;
  8101. BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
  8102. BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
  8103. unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
  8104. out_unlock:
  8105. if (!ret) {
  8106. btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
  8107. sb_end_pagefault(inode->i_sb);
  8108. extent_changeset_free(data_reserved);
  8109. return VM_FAULT_LOCKED;
  8110. }
  8111. unlock_page(page);
  8112. out:
  8113. btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
  8114. btrfs_delalloc_release_space(inode, data_reserved, page_start,
  8115. reserved_space);
  8116. out_noreserve:
  8117. sb_end_pagefault(inode->i_sb);
  8118. extent_changeset_free(data_reserved);
  8119. return ret;
  8120. }
  8121. static int btrfs_truncate(struct inode *inode)
  8122. {
  8123. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  8124. struct btrfs_root *root = BTRFS_I(inode)->root;
  8125. struct btrfs_block_rsv *rsv;
  8126. int ret = 0;
  8127. int err = 0;
  8128. struct btrfs_trans_handle *trans;
  8129. u64 mask = fs_info->sectorsize - 1;
  8130. u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
  8131. ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
  8132. (u64)-1);
  8133. if (ret)
  8134. return ret;
  8135. /*
  8136. * Yes ladies and gentlemen, this is indeed ugly. The fact is we have
  8137. * 3 things going on here
  8138. *
  8139. * 1) We need to reserve space for our orphan item and the space to
  8140. * delete our orphan item. Lord knows we don't want to have a dangling
  8141. * orphan item because we didn't reserve space to remove it.
  8142. *
  8143. * 2) We need to reserve space to update our inode.
  8144. *
  8145. * 3) We need to have something to cache all the space that is going to
  8146. * be free'd up by the truncate operation, but also have some slack
  8147. * space reserved in case it uses space during the truncate (thank you
  8148. * very much snapshotting).
  8149. *
  8150. * And we need these to all be separate. The fact is we can use a lot of
  8151. * space doing the truncate, and we have no earthly idea how much space
  8152. * we will use, so we need the truncate reservation to be separate so it
  8153. * doesn't end up using space reserved for updating the inode or
  8154. * removing the orphan item. We also need to be able to stop the
  8155. * transaction and start a new one, which means we need to be able to
  8156. * update the inode several times, and we have no idea of knowing how
  8157. * many times that will be, so we can't just reserve 1 item for the
  8158. * entirety of the operation, so that has to be done separately as well.
  8159. * Then there is the orphan item, which does indeed need to be held on
  8160. * to for the whole operation, and we need nobody to touch this reserved
  8161. * space except the orphan code.
  8162. *
  8163. * So that leaves us with
  8164. *
  8165. * 1) root->orphan_block_rsv - for the orphan deletion.
  8166. * 2) rsv - for the truncate reservation, which we will steal from the
  8167. * transaction reservation.
  8168. * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
  8169. * updating the inode.
  8170. */
  8171. rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
  8172. if (!rsv)
  8173. return -ENOMEM;
  8174. rsv->size = min_size;
  8175. rsv->failfast = 1;
  8176. /*
  8177. * 1 for the truncate slack space
  8178. * 1 for updating the inode.
  8179. */
  8180. trans = btrfs_start_transaction(root, 2);
  8181. if (IS_ERR(trans)) {
  8182. err = PTR_ERR(trans);
  8183. goto out;
  8184. }
  8185. /* Migrate the slack space for the truncate to our reserve */
  8186. ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
  8187. min_size, 0);
  8188. BUG_ON(ret);
  8189. /*
  8190. * So if we truncate and then write and fsync we normally would just
  8191. * write the extents that changed, which is a problem if we need to
  8192. * first truncate that entire inode. So set this flag so we write out
  8193. * all of the extents in the inode to the sync log so we're completely
  8194. * safe.
  8195. */
  8196. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
  8197. trans->block_rsv = rsv;
  8198. while (1) {
  8199. ret = btrfs_truncate_inode_items(trans, root, inode,
  8200. inode->i_size,
  8201. BTRFS_EXTENT_DATA_KEY);
  8202. trans->block_rsv = &fs_info->trans_block_rsv;
  8203. if (ret != -ENOSPC && ret != -EAGAIN) {
  8204. err = ret;
  8205. break;
  8206. }
  8207. ret = btrfs_update_inode(trans, root, inode);
  8208. if (ret) {
  8209. err = ret;
  8210. break;
  8211. }
  8212. btrfs_end_transaction(trans);
  8213. btrfs_btree_balance_dirty(fs_info);
  8214. trans = btrfs_start_transaction(root, 2);
  8215. if (IS_ERR(trans)) {
  8216. ret = err = PTR_ERR(trans);
  8217. trans = NULL;
  8218. break;
  8219. }
  8220. btrfs_block_rsv_release(fs_info, rsv, -1);
  8221. ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
  8222. rsv, min_size, 0);
  8223. BUG_ON(ret); /* shouldn't happen */
  8224. trans->block_rsv = rsv;
  8225. }
  8226. /*
  8227. * We can't call btrfs_truncate_block inside a trans handle as we could
  8228. * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
  8229. * we've truncated everything except the last little bit, and can do
  8230. * btrfs_truncate_block and then update the disk_i_size.
  8231. */
  8232. if (ret == NEED_TRUNCATE_BLOCK) {
  8233. btrfs_end_transaction(trans);
  8234. btrfs_btree_balance_dirty(fs_info);
  8235. ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
  8236. if (ret)
  8237. goto out;
  8238. trans = btrfs_start_transaction(root, 1);
  8239. if (IS_ERR(trans)) {
  8240. ret = PTR_ERR(trans);
  8241. goto out;
  8242. }
  8243. btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
  8244. }
  8245. if (ret == 0 && inode->i_nlink > 0) {
  8246. trans->block_rsv = root->orphan_block_rsv;
  8247. ret = btrfs_orphan_del(trans, BTRFS_I(inode));
  8248. if (ret)
  8249. err = ret;
  8250. }
  8251. if (trans) {
  8252. trans->block_rsv = &fs_info->trans_block_rsv;
  8253. ret = btrfs_update_inode(trans, root, inode);
  8254. if (ret && !err)
  8255. err = ret;
  8256. ret = btrfs_end_transaction(trans);
  8257. btrfs_btree_balance_dirty(fs_info);
  8258. }
  8259. out:
  8260. btrfs_free_block_rsv(fs_info, rsv);
  8261. if (ret && !err)
  8262. err = ret;
  8263. return err;
  8264. }
  8265. /*
  8266. * create a new subvolume directory/inode (helper for the ioctl).
  8267. */
  8268. int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
  8269. struct btrfs_root *new_root,
  8270. struct btrfs_root *parent_root,
  8271. u64 new_dirid)
  8272. {
  8273. struct inode *inode;
  8274. int err;
  8275. u64 index = 0;
  8276. inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
  8277. new_dirid, new_dirid,
  8278. S_IFDIR | (~current_umask() & S_IRWXUGO),
  8279. &index);
  8280. if (IS_ERR(inode))
  8281. return PTR_ERR(inode);
  8282. inode->i_op = &btrfs_dir_inode_operations;
  8283. inode->i_fop = &btrfs_dir_file_operations;
  8284. set_nlink(inode, 1);
  8285. btrfs_i_size_write(BTRFS_I(inode), 0);
  8286. unlock_new_inode(inode);
  8287. err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
  8288. if (err)
  8289. btrfs_err(new_root->fs_info,
  8290. "error inheriting subvolume %llu properties: %d",
  8291. new_root->root_key.objectid, err);
  8292. err = btrfs_update_inode(trans, new_root, inode);
  8293. iput(inode);
  8294. return err;
  8295. }
  8296. struct inode *btrfs_alloc_inode(struct super_block *sb)
  8297. {
  8298. struct btrfs_fs_info *fs_info = btrfs_sb(sb);
  8299. struct btrfs_inode *ei;
  8300. struct inode *inode;
  8301. ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
  8302. if (!ei)
  8303. return NULL;
  8304. ei->root = NULL;
  8305. ei->generation = 0;
  8306. ei->last_trans = 0;
  8307. ei->last_sub_trans = 0;
  8308. ei->logged_trans = 0;
  8309. ei->delalloc_bytes = 0;
  8310. ei->new_delalloc_bytes = 0;
  8311. ei->defrag_bytes = 0;
  8312. ei->disk_i_size = 0;
  8313. ei->flags = 0;
  8314. ei->csum_bytes = 0;
  8315. ei->index_cnt = (u64)-1;
  8316. ei->dir_index = 0;
  8317. ei->last_unlink_trans = 0;
  8318. ei->last_log_commit = 0;
  8319. ei->delayed_iput_count = 0;
  8320. spin_lock_init(&ei->lock);
  8321. ei->outstanding_extents = 0;
  8322. if (sb->s_magic != BTRFS_TEST_MAGIC)
  8323. btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
  8324. BTRFS_BLOCK_RSV_DELALLOC);
  8325. ei->runtime_flags = 0;
  8326. ei->prop_compress = BTRFS_COMPRESS_NONE;
  8327. ei->defrag_compress = BTRFS_COMPRESS_NONE;
  8328. ei->delayed_node = NULL;
  8329. ei->i_otime.tv_sec = 0;
  8330. ei->i_otime.tv_nsec = 0;
  8331. inode = &ei->vfs_inode;
  8332. extent_map_tree_init(&ei->extent_tree);
  8333. extent_io_tree_init(&ei->io_tree, inode);
  8334. extent_io_tree_init(&ei->io_failure_tree, inode);
  8335. ei->io_tree.track_uptodate = 1;
  8336. ei->io_failure_tree.track_uptodate = 1;
  8337. atomic_set(&ei->sync_writers, 0);
  8338. mutex_init(&ei->log_mutex);
  8339. mutex_init(&ei->delalloc_mutex);
  8340. btrfs_ordered_inode_tree_init(&ei->ordered_tree);
  8341. INIT_LIST_HEAD(&ei->delalloc_inodes);
  8342. INIT_LIST_HEAD(&ei->delayed_iput);
  8343. RB_CLEAR_NODE(&ei->rb_node);
  8344. init_rwsem(&ei->dio_sem);
  8345. return inode;
  8346. }
  8347. #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
  8348. void btrfs_test_destroy_inode(struct inode *inode)
  8349. {
  8350. btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
  8351. kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
  8352. }
  8353. #endif
  8354. static void btrfs_i_callback(struct rcu_head *head)
  8355. {
  8356. struct inode *inode = container_of(head, struct inode, i_rcu);
  8357. kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
  8358. }
  8359. void btrfs_destroy_inode(struct inode *inode)
  8360. {
  8361. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  8362. struct btrfs_ordered_extent *ordered;
  8363. struct btrfs_root *root = BTRFS_I(inode)->root;
  8364. WARN_ON(!hlist_empty(&inode->i_dentry));
  8365. WARN_ON(inode->i_data.nrpages);
  8366. WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
  8367. WARN_ON(BTRFS_I(inode)->block_rsv.size);
  8368. WARN_ON(BTRFS_I(inode)->outstanding_extents);
  8369. WARN_ON(BTRFS_I(inode)->delalloc_bytes);
  8370. WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
  8371. WARN_ON(BTRFS_I(inode)->csum_bytes);
  8372. WARN_ON(BTRFS_I(inode)->defrag_bytes);
  8373. /*
  8374. * This can happen where we create an inode, but somebody else also
  8375. * created the same inode and we need to destroy the one we already
  8376. * created.
  8377. */
  8378. if (!root)
  8379. goto free;
  8380. if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
  8381. &BTRFS_I(inode)->runtime_flags)) {
  8382. btrfs_info(fs_info, "inode %llu still on the orphan list",
  8383. btrfs_ino(BTRFS_I(inode)));
  8384. atomic_dec(&root->orphan_inodes);
  8385. }
  8386. while (1) {
  8387. ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
  8388. if (!ordered)
  8389. break;
  8390. else {
  8391. btrfs_err(fs_info,
  8392. "found ordered extent %llu %llu on inode cleanup",
  8393. ordered->file_offset, ordered->len);
  8394. btrfs_remove_ordered_extent(inode, ordered);
  8395. btrfs_put_ordered_extent(ordered);
  8396. btrfs_put_ordered_extent(ordered);
  8397. }
  8398. }
  8399. btrfs_qgroup_check_reserved_leak(inode);
  8400. inode_tree_del(inode);
  8401. btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
  8402. free:
  8403. call_rcu(&inode->i_rcu, btrfs_i_callback);
  8404. }
  8405. int btrfs_drop_inode(struct inode *inode)
  8406. {
  8407. struct btrfs_root *root = BTRFS_I(inode)->root;
  8408. if (root == NULL)
  8409. return 1;
  8410. /* the snap/subvol tree is on deleting */
  8411. if (btrfs_root_refs(&root->root_item) == 0)
  8412. return 1;
  8413. else
  8414. return generic_drop_inode(inode);
  8415. }
  8416. static void init_once(void *foo)
  8417. {
  8418. struct btrfs_inode *ei = (struct btrfs_inode *) foo;
  8419. inode_init_once(&ei->vfs_inode);
  8420. }
  8421. void btrfs_destroy_cachep(void)
  8422. {
  8423. /*
  8424. * Make sure all delayed rcu free inodes are flushed before we
  8425. * destroy cache.
  8426. */
  8427. rcu_barrier();
  8428. kmem_cache_destroy(btrfs_inode_cachep);
  8429. kmem_cache_destroy(btrfs_trans_handle_cachep);
  8430. kmem_cache_destroy(btrfs_path_cachep);
  8431. kmem_cache_destroy(btrfs_free_space_cachep);
  8432. }
  8433. int __init btrfs_init_cachep(void)
  8434. {
  8435. btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
  8436. sizeof(struct btrfs_inode), 0,
  8437. SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
  8438. init_once);
  8439. if (!btrfs_inode_cachep)
  8440. goto fail;
  8441. btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
  8442. sizeof(struct btrfs_trans_handle), 0,
  8443. SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
  8444. if (!btrfs_trans_handle_cachep)
  8445. goto fail;
  8446. btrfs_path_cachep = kmem_cache_create("btrfs_path",
  8447. sizeof(struct btrfs_path), 0,
  8448. SLAB_MEM_SPREAD, NULL);
  8449. if (!btrfs_path_cachep)
  8450. goto fail;
  8451. btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
  8452. sizeof(struct btrfs_free_space), 0,
  8453. SLAB_MEM_SPREAD, NULL);
  8454. if (!btrfs_free_space_cachep)
  8455. goto fail;
  8456. return 0;
  8457. fail:
  8458. btrfs_destroy_cachep();
  8459. return -ENOMEM;
  8460. }
  8461. static int btrfs_getattr(const struct path *path, struct kstat *stat,
  8462. u32 request_mask, unsigned int flags)
  8463. {
  8464. u64 delalloc_bytes;
  8465. struct inode *inode = d_inode(path->dentry);
  8466. u32 blocksize = inode->i_sb->s_blocksize;
  8467. u32 bi_flags = BTRFS_I(inode)->flags;
  8468. stat->result_mask |= STATX_BTIME;
  8469. stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
  8470. stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
  8471. if (bi_flags & BTRFS_INODE_APPEND)
  8472. stat->attributes |= STATX_ATTR_APPEND;
  8473. if (bi_flags & BTRFS_INODE_COMPRESS)
  8474. stat->attributes |= STATX_ATTR_COMPRESSED;
  8475. if (bi_flags & BTRFS_INODE_IMMUTABLE)
  8476. stat->attributes |= STATX_ATTR_IMMUTABLE;
  8477. if (bi_flags & BTRFS_INODE_NODUMP)
  8478. stat->attributes |= STATX_ATTR_NODUMP;
  8479. stat->attributes_mask |= (STATX_ATTR_APPEND |
  8480. STATX_ATTR_COMPRESSED |
  8481. STATX_ATTR_IMMUTABLE |
  8482. STATX_ATTR_NODUMP);
  8483. generic_fillattr(inode, stat);
  8484. stat->dev = BTRFS_I(inode)->root->anon_dev;
  8485. spin_lock(&BTRFS_I(inode)->lock);
  8486. delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
  8487. spin_unlock(&BTRFS_I(inode)->lock);
  8488. stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
  8489. ALIGN(delalloc_bytes, blocksize)) >> 9;
  8490. return 0;
  8491. }
  8492. static int btrfs_rename_exchange(struct inode *old_dir,
  8493. struct dentry *old_dentry,
  8494. struct inode *new_dir,
  8495. struct dentry *new_dentry)
  8496. {
  8497. struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
  8498. struct btrfs_trans_handle *trans;
  8499. struct btrfs_root *root = BTRFS_I(old_dir)->root;
  8500. struct btrfs_root *dest = BTRFS_I(new_dir)->root;
  8501. struct inode *new_inode = new_dentry->d_inode;
  8502. struct inode *old_inode = old_dentry->d_inode;
  8503. struct timespec ctime = current_time(old_inode);
  8504. struct dentry *parent;
  8505. u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
  8506. u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
  8507. u64 old_idx = 0;
  8508. u64 new_idx = 0;
  8509. u64 root_objectid;
  8510. int ret;
  8511. bool root_log_pinned = false;
  8512. bool dest_log_pinned = false;
  8513. /* we only allow rename subvolume link between subvolumes */
  8514. if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
  8515. return -EXDEV;
  8516. /* close the race window with snapshot create/destroy ioctl */
  8517. if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
  8518. down_read(&fs_info->subvol_sem);
  8519. if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
  8520. down_read(&fs_info->subvol_sem);
  8521. /*
  8522. * We want to reserve the absolute worst case amount of items. So if
  8523. * both inodes are subvols and we need to unlink them then that would
  8524. * require 4 item modifications, but if they are both normal inodes it
  8525. * would require 5 item modifications, so we'll assume their normal
  8526. * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
  8527. * should cover the worst case number of items we'll modify.
  8528. */
  8529. trans = btrfs_start_transaction(root, 12);
  8530. if (IS_ERR(trans)) {
  8531. ret = PTR_ERR(trans);
  8532. goto out_notrans;
  8533. }
  8534. /*
  8535. * We need to find a free sequence number both in the source and
  8536. * in the destination directory for the exchange.
  8537. */
  8538. ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
  8539. if (ret)
  8540. goto out_fail;
  8541. ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
  8542. if (ret)
  8543. goto out_fail;
  8544. BTRFS_I(old_inode)->dir_index = 0ULL;
  8545. BTRFS_I(new_inode)->dir_index = 0ULL;
  8546. /* Reference for the source. */
  8547. if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
  8548. /* force full log commit if subvolume involved. */
  8549. btrfs_set_log_full_commit(fs_info, trans);
  8550. } else {
  8551. btrfs_pin_log_trans(root);
  8552. root_log_pinned = true;
  8553. ret = btrfs_insert_inode_ref(trans, dest,
  8554. new_dentry->d_name.name,
  8555. new_dentry->d_name.len,
  8556. old_ino,
  8557. btrfs_ino(BTRFS_I(new_dir)),
  8558. old_idx);
  8559. if (ret)
  8560. goto out_fail;
  8561. }
  8562. /* And now for the dest. */
  8563. if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
  8564. /* force full log commit if subvolume involved. */
  8565. btrfs_set_log_full_commit(fs_info, trans);
  8566. } else {
  8567. btrfs_pin_log_trans(dest);
  8568. dest_log_pinned = true;
  8569. ret = btrfs_insert_inode_ref(trans, root,
  8570. old_dentry->d_name.name,
  8571. old_dentry->d_name.len,
  8572. new_ino,
  8573. btrfs_ino(BTRFS_I(old_dir)),
  8574. new_idx);
  8575. if (ret)
  8576. goto out_fail;
  8577. }
  8578. /* Update inode version and ctime/mtime. */
  8579. inode_inc_iversion(old_dir);
  8580. inode_inc_iversion(new_dir);
  8581. inode_inc_iversion(old_inode);
  8582. inode_inc_iversion(new_inode);
  8583. old_dir->i_ctime = old_dir->i_mtime = ctime;
  8584. new_dir->i_ctime = new_dir->i_mtime = ctime;
  8585. old_inode->i_ctime = ctime;
  8586. new_inode->i_ctime = ctime;
  8587. if (old_dentry->d_parent != new_dentry->d_parent) {
  8588. btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
  8589. BTRFS_I(old_inode), 1);
  8590. btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
  8591. BTRFS_I(new_inode), 1);
  8592. }
  8593. /* src is a subvolume */
  8594. if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
  8595. root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
  8596. ret = btrfs_unlink_subvol(trans, root, old_dir,
  8597. root_objectid,
  8598. old_dentry->d_name.name,
  8599. old_dentry->d_name.len);
  8600. } else { /* src is an inode */
  8601. ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
  8602. BTRFS_I(old_dentry->d_inode),
  8603. old_dentry->d_name.name,
  8604. old_dentry->d_name.len);
  8605. if (!ret)
  8606. ret = btrfs_update_inode(trans, root, old_inode);
  8607. }
  8608. if (ret) {
  8609. btrfs_abort_transaction(trans, ret);
  8610. goto out_fail;
  8611. }
  8612. /* dest is a subvolume */
  8613. if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
  8614. root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
  8615. ret = btrfs_unlink_subvol(trans, dest, new_dir,
  8616. root_objectid,
  8617. new_dentry->d_name.name,
  8618. new_dentry->d_name.len);
  8619. } else { /* dest is an inode */
  8620. ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
  8621. BTRFS_I(new_dentry->d_inode),
  8622. new_dentry->d_name.name,
  8623. new_dentry->d_name.len);
  8624. if (!ret)
  8625. ret = btrfs_update_inode(trans, dest, new_inode);
  8626. }
  8627. if (ret) {
  8628. btrfs_abort_transaction(trans, ret);
  8629. goto out_fail;
  8630. }
  8631. ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
  8632. new_dentry->d_name.name,
  8633. new_dentry->d_name.len, 0, old_idx);
  8634. if (ret) {
  8635. btrfs_abort_transaction(trans, ret);
  8636. goto out_fail;
  8637. }
  8638. ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
  8639. old_dentry->d_name.name,
  8640. old_dentry->d_name.len, 0, new_idx);
  8641. if (ret) {
  8642. btrfs_abort_transaction(trans, ret);
  8643. goto out_fail;
  8644. }
  8645. if (old_inode->i_nlink == 1)
  8646. BTRFS_I(old_inode)->dir_index = old_idx;
  8647. if (new_inode->i_nlink == 1)
  8648. BTRFS_I(new_inode)->dir_index = new_idx;
  8649. if (root_log_pinned) {
  8650. parent = new_dentry->d_parent;
  8651. btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
  8652. parent);
  8653. btrfs_end_log_trans(root);
  8654. root_log_pinned = false;
  8655. }
  8656. if (dest_log_pinned) {
  8657. parent = old_dentry->d_parent;
  8658. btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
  8659. parent);
  8660. btrfs_end_log_trans(dest);
  8661. dest_log_pinned = false;
  8662. }
  8663. out_fail:
  8664. /*
  8665. * If we have pinned a log and an error happened, we unpin tasks
  8666. * trying to sync the log and force them to fallback to a transaction
  8667. * commit if the log currently contains any of the inodes involved in
  8668. * this rename operation (to ensure we do not persist a log with an
  8669. * inconsistent state for any of these inodes or leading to any
  8670. * inconsistencies when replayed). If the transaction was aborted, the
  8671. * abortion reason is propagated to userspace when attempting to commit
  8672. * the transaction. If the log does not contain any of these inodes, we
  8673. * allow the tasks to sync it.
  8674. */
  8675. if (ret && (root_log_pinned || dest_log_pinned)) {
  8676. if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
  8677. btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
  8678. btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
  8679. (new_inode &&
  8680. btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
  8681. btrfs_set_log_full_commit(fs_info, trans);
  8682. if (root_log_pinned) {
  8683. btrfs_end_log_trans(root);
  8684. root_log_pinned = false;
  8685. }
  8686. if (dest_log_pinned) {
  8687. btrfs_end_log_trans(dest);
  8688. dest_log_pinned = false;
  8689. }
  8690. }
  8691. ret = btrfs_end_transaction(trans);
  8692. out_notrans:
  8693. if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
  8694. up_read(&fs_info->subvol_sem);
  8695. if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
  8696. up_read(&fs_info->subvol_sem);
  8697. return ret;
  8698. }
  8699. static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
  8700. struct btrfs_root *root,
  8701. struct inode *dir,
  8702. struct dentry *dentry)
  8703. {
  8704. int ret;
  8705. struct inode *inode;
  8706. u64 objectid;
  8707. u64 index;
  8708. ret = btrfs_find_free_ino(root, &objectid);
  8709. if (ret)
  8710. return ret;
  8711. inode = btrfs_new_inode(trans, root, dir,
  8712. dentry->d_name.name,
  8713. dentry->d_name.len,
  8714. btrfs_ino(BTRFS_I(dir)),
  8715. objectid,
  8716. S_IFCHR | WHITEOUT_MODE,
  8717. &index);
  8718. if (IS_ERR(inode)) {
  8719. ret = PTR_ERR(inode);
  8720. return ret;
  8721. }
  8722. inode->i_op = &btrfs_special_inode_operations;
  8723. init_special_inode(inode, inode->i_mode,
  8724. WHITEOUT_DEV);
  8725. ret = btrfs_init_inode_security(trans, inode, dir,
  8726. &dentry->d_name);
  8727. if (ret)
  8728. goto out;
  8729. ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
  8730. BTRFS_I(inode), 0, index);
  8731. if (ret)
  8732. goto out;
  8733. ret = btrfs_update_inode(trans, root, inode);
  8734. out:
  8735. unlock_new_inode(inode);
  8736. if (ret)
  8737. inode_dec_link_count(inode);
  8738. iput(inode);
  8739. return ret;
  8740. }
  8741. static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
  8742. struct inode *new_dir, struct dentry *new_dentry,
  8743. unsigned int flags)
  8744. {
  8745. struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
  8746. struct btrfs_trans_handle *trans;
  8747. unsigned int trans_num_items;
  8748. struct btrfs_root *root = BTRFS_I(old_dir)->root;
  8749. struct btrfs_root *dest = BTRFS_I(new_dir)->root;
  8750. struct inode *new_inode = d_inode(new_dentry);
  8751. struct inode *old_inode = d_inode(old_dentry);
  8752. u64 index = 0;
  8753. u64 root_objectid;
  8754. int ret;
  8755. u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
  8756. bool log_pinned = false;
  8757. if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
  8758. return -EPERM;
  8759. /* we only allow rename subvolume link between subvolumes */
  8760. if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
  8761. return -EXDEV;
  8762. if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
  8763. (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
  8764. return -ENOTEMPTY;
  8765. if (S_ISDIR(old_inode->i_mode) && new_inode &&
  8766. new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
  8767. return -ENOTEMPTY;
  8768. /* check for collisions, even if the name isn't there */
  8769. ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
  8770. new_dentry->d_name.name,
  8771. new_dentry->d_name.len);
  8772. if (ret) {
  8773. if (ret == -EEXIST) {
  8774. /* we shouldn't get
  8775. * eexist without a new_inode */
  8776. if (WARN_ON(!new_inode)) {
  8777. return ret;
  8778. }
  8779. } else {
  8780. /* maybe -EOVERFLOW */
  8781. return ret;
  8782. }
  8783. }
  8784. ret = 0;
  8785. /*
  8786. * we're using rename to replace one file with another. Start IO on it
  8787. * now so we don't add too much work to the end of the transaction
  8788. */
  8789. if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
  8790. filemap_flush(old_inode->i_mapping);
  8791. /* close the racy window with snapshot create/destroy ioctl */
  8792. if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
  8793. down_read(&fs_info->subvol_sem);
  8794. /*
  8795. * We want to reserve the absolute worst case amount of items. So if
  8796. * both inodes are subvols and we need to unlink them then that would
  8797. * require 4 item modifications, but if they are both normal inodes it
  8798. * would require 5 item modifications, so we'll assume they are normal
  8799. * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
  8800. * should cover the worst case number of items we'll modify.
  8801. * If our rename has the whiteout flag, we need more 5 units for the
  8802. * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
  8803. * when selinux is enabled).
  8804. */
  8805. trans_num_items = 11;
  8806. if (flags & RENAME_WHITEOUT)
  8807. trans_num_items += 5;
  8808. trans = btrfs_start_transaction(root, trans_num_items);
  8809. if (IS_ERR(trans)) {
  8810. ret = PTR_ERR(trans);
  8811. goto out_notrans;
  8812. }
  8813. if (dest != root)
  8814. btrfs_record_root_in_trans(trans, dest);
  8815. ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
  8816. if (ret)
  8817. goto out_fail;
  8818. BTRFS_I(old_inode)->dir_index = 0ULL;
  8819. if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
  8820. /* force full log commit if subvolume involved. */
  8821. btrfs_set_log_full_commit(fs_info, trans);
  8822. } else {
  8823. btrfs_pin_log_trans(root);
  8824. log_pinned = true;
  8825. ret = btrfs_insert_inode_ref(trans, dest,
  8826. new_dentry->d_name.name,
  8827. new_dentry->d_name.len,
  8828. old_ino,
  8829. btrfs_ino(BTRFS_I(new_dir)), index);
  8830. if (ret)
  8831. goto out_fail;
  8832. }
  8833. inode_inc_iversion(old_dir);
  8834. inode_inc_iversion(new_dir);
  8835. inode_inc_iversion(old_inode);
  8836. old_dir->i_ctime = old_dir->i_mtime =
  8837. new_dir->i_ctime = new_dir->i_mtime =
  8838. old_inode->i_ctime = current_time(old_dir);
  8839. if (old_dentry->d_parent != new_dentry->d_parent)
  8840. btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
  8841. BTRFS_I(old_inode), 1);
  8842. if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
  8843. root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
  8844. ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
  8845. old_dentry->d_name.name,
  8846. old_dentry->d_name.len);
  8847. } else {
  8848. ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
  8849. BTRFS_I(d_inode(old_dentry)),
  8850. old_dentry->d_name.name,
  8851. old_dentry->d_name.len);
  8852. if (!ret)
  8853. ret = btrfs_update_inode(trans, root, old_inode);
  8854. }
  8855. if (ret) {
  8856. btrfs_abort_transaction(trans, ret);
  8857. goto out_fail;
  8858. }
  8859. if (new_inode) {
  8860. inode_inc_iversion(new_inode);
  8861. new_inode->i_ctime = current_time(new_inode);
  8862. if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
  8863. BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
  8864. root_objectid = BTRFS_I(new_inode)->location.objectid;
  8865. ret = btrfs_unlink_subvol(trans, dest, new_dir,
  8866. root_objectid,
  8867. new_dentry->d_name.name,
  8868. new_dentry->d_name.len);
  8869. BUG_ON(new_inode->i_nlink == 0);
  8870. } else {
  8871. ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
  8872. BTRFS_I(d_inode(new_dentry)),
  8873. new_dentry->d_name.name,
  8874. new_dentry->d_name.len);
  8875. }
  8876. if (!ret && new_inode->i_nlink == 0)
  8877. ret = btrfs_orphan_add(trans,
  8878. BTRFS_I(d_inode(new_dentry)));
  8879. if (ret) {
  8880. btrfs_abort_transaction(trans, ret);
  8881. goto out_fail;
  8882. }
  8883. }
  8884. ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
  8885. new_dentry->d_name.name,
  8886. new_dentry->d_name.len, 0, index);
  8887. if (ret) {
  8888. btrfs_abort_transaction(trans, ret);
  8889. goto out_fail;
  8890. }
  8891. if (old_inode->i_nlink == 1)
  8892. BTRFS_I(old_inode)->dir_index = index;
  8893. if (log_pinned) {
  8894. struct dentry *parent = new_dentry->d_parent;
  8895. btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
  8896. parent);
  8897. btrfs_end_log_trans(root);
  8898. log_pinned = false;
  8899. }
  8900. if (flags & RENAME_WHITEOUT) {
  8901. ret = btrfs_whiteout_for_rename(trans, root, old_dir,
  8902. old_dentry);
  8903. if (ret) {
  8904. btrfs_abort_transaction(trans, ret);
  8905. goto out_fail;
  8906. }
  8907. }
  8908. out_fail:
  8909. /*
  8910. * If we have pinned the log and an error happened, we unpin tasks
  8911. * trying to sync the log and force them to fallback to a transaction
  8912. * commit if the log currently contains any of the inodes involved in
  8913. * this rename operation (to ensure we do not persist a log with an
  8914. * inconsistent state for any of these inodes or leading to any
  8915. * inconsistencies when replayed). If the transaction was aborted, the
  8916. * abortion reason is propagated to userspace when attempting to commit
  8917. * the transaction. If the log does not contain any of these inodes, we
  8918. * allow the tasks to sync it.
  8919. */
  8920. if (ret && log_pinned) {
  8921. if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
  8922. btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
  8923. btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
  8924. (new_inode &&
  8925. btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
  8926. btrfs_set_log_full_commit(fs_info, trans);
  8927. btrfs_end_log_trans(root);
  8928. log_pinned = false;
  8929. }
  8930. btrfs_end_transaction(trans);
  8931. out_notrans:
  8932. if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
  8933. up_read(&fs_info->subvol_sem);
  8934. return ret;
  8935. }
  8936. static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
  8937. struct inode *new_dir, struct dentry *new_dentry,
  8938. unsigned int flags)
  8939. {
  8940. if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
  8941. return -EINVAL;
  8942. if (flags & RENAME_EXCHANGE)
  8943. return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
  8944. new_dentry);
  8945. return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
  8946. }
  8947. static void btrfs_run_delalloc_work(struct btrfs_work *work)
  8948. {
  8949. struct btrfs_delalloc_work *delalloc_work;
  8950. struct inode *inode;
  8951. delalloc_work = container_of(work, struct btrfs_delalloc_work,
  8952. work);
  8953. inode = delalloc_work->inode;
  8954. filemap_flush(inode->i_mapping);
  8955. if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
  8956. &BTRFS_I(inode)->runtime_flags))
  8957. filemap_flush(inode->i_mapping);
  8958. if (delalloc_work->delay_iput)
  8959. btrfs_add_delayed_iput(inode);
  8960. else
  8961. iput(inode);
  8962. complete(&delalloc_work->completion);
  8963. }
  8964. struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
  8965. int delay_iput)
  8966. {
  8967. struct btrfs_delalloc_work *work;
  8968. work = kmalloc(sizeof(*work), GFP_NOFS);
  8969. if (!work)
  8970. return NULL;
  8971. init_completion(&work->completion);
  8972. INIT_LIST_HEAD(&work->list);
  8973. work->inode = inode;
  8974. work->delay_iput = delay_iput;
  8975. WARN_ON_ONCE(!inode);
  8976. btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
  8977. btrfs_run_delalloc_work, NULL, NULL);
  8978. return work;
  8979. }
  8980. void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
  8981. {
  8982. wait_for_completion(&work->completion);
  8983. kfree(work);
  8984. }
  8985. /*
  8986. * some fairly slow code that needs optimization. This walks the list
  8987. * of all the inodes with pending delalloc and forces them to disk.
  8988. */
  8989. static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
  8990. int nr)
  8991. {
  8992. struct btrfs_inode *binode;
  8993. struct inode *inode;
  8994. struct btrfs_delalloc_work *work, *next;
  8995. struct list_head works;
  8996. struct list_head splice;
  8997. int ret = 0;
  8998. INIT_LIST_HEAD(&works);
  8999. INIT_LIST_HEAD(&splice);
  9000. mutex_lock(&root->delalloc_mutex);
  9001. spin_lock(&root->delalloc_lock);
  9002. list_splice_init(&root->delalloc_inodes, &splice);
  9003. while (!list_empty(&splice)) {
  9004. binode = list_entry(splice.next, struct btrfs_inode,
  9005. delalloc_inodes);
  9006. list_move_tail(&binode->delalloc_inodes,
  9007. &root->delalloc_inodes);
  9008. inode = igrab(&binode->vfs_inode);
  9009. if (!inode) {
  9010. cond_resched_lock(&root->delalloc_lock);
  9011. continue;
  9012. }
  9013. spin_unlock(&root->delalloc_lock);
  9014. work = btrfs_alloc_delalloc_work(inode, delay_iput);
  9015. if (!work) {
  9016. if (delay_iput)
  9017. btrfs_add_delayed_iput(inode);
  9018. else
  9019. iput(inode);
  9020. ret = -ENOMEM;
  9021. goto out;
  9022. }
  9023. list_add_tail(&work->list, &works);
  9024. btrfs_queue_work(root->fs_info->flush_workers,
  9025. &work->work);
  9026. ret++;
  9027. if (nr != -1 && ret >= nr)
  9028. goto out;
  9029. cond_resched();
  9030. spin_lock(&root->delalloc_lock);
  9031. }
  9032. spin_unlock(&root->delalloc_lock);
  9033. out:
  9034. list_for_each_entry_safe(work, next, &works, list) {
  9035. list_del_init(&work->list);
  9036. btrfs_wait_and_free_delalloc_work(work);
  9037. }
  9038. if (!list_empty_careful(&splice)) {
  9039. spin_lock(&root->delalloc_lock);
  9040. list_splice_tail(&splice, &root->delalloc_inodes);
  9041. spin_unlock(&root->delalloc_lock);
  9042. }
  9043. mutex_unlock(&root->delalloc_mutex);
  9044. return ret;
  9045. }
  9046. int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
  9047. {
  9048. struct btrfs_fs_info *fs_info = root->fs_info;
  9049. int ret;
  9050. if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
  9051. return -EROFS;
  9052. ret = __start_delalloc_inodes(root, delay_iput, -1);
  9053. if (ret > 0)
  9054. ret = 0;
  9055. return ret;
  9056. }
  9057. int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
  9058. int nr)
  9059. {
  9060. struct btrfs_root *root;
  9061. struct list_head splice;
  9062. int ret;
  9063. if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
  9064. return -EROFS;
  9065. INIT_LIST_HEAD(&splice);
  9066. mutex_lock(&fs_info->delalloc_root_mutex);
  9067. spin_lock(&fs_info->delalloc_root_lock);
  9068. list_splice_init(&fs_info->delalloc_roots, &splice);
  9069. while (!list_empty(&splice) && nr) {
  9070. root = list_first_entry(&splice, struct btrfs_root,
  9071. delalloc_root);
  9072. root = btrfs_grab_fs_root(root);
  9073. BUG_ON(!root);
  9074. list_move_tail(&root->delalloc_root,
  9075. &fs_info->delalloc_roots);
  9076. spin_unlock(&fs_info->delalloc_root_lock);
  9077. ret = __start_delalloc_inodes(root, delay_iput, nr);
  9078. btrfs_put_fs_root(root);
  9079. if (ret < 0)
  9080. goto out;
  9081. if (nr != -1) {
  9082. nr -= ret;
  9083. WARN_ON(nr < 0);
  9084. }
  9085. spin_lock(&fs_info->delalloc_root_lock);
  9086. }
  9087. spin_unlock(&fs_info->delalloc_root_lock);
  9088. ret = 0;
  9089. out:
  9090. if (!list_empty_careful(&splice)) {
  9091. spin_lock(&fs_info->delalloc_root_lock);
  9092. list_splice_tail(&splice, &fs_info->delalloc_roots);
  9093. spin_unlock(&fs_info->delalloc_root_lock);
  9094. }
  9095. mutex_unlock(&fs_info->delalloc_root_mutex);
  9096. return ret;
  9097. }
  9098. static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
  9099. const char *symname)
  9100. {
  9101. struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
  9102. struct btrfs_trans_handle *trans;
  9103. struct btrfs_root *root = BTRFS_I(dir)->root;
  9104. struct btrfs_path *path;
  9105. struct btrfs_key key;
  9106. struct inode *inode = NULL;
  9107. int err;
  9108. int drop_inode = 0;
  9109. u64 objectid;
  9110. u64 index = 0;
  9111. int name_len;
  9112. int datasize;
  9113. unsigned long ptr;
  9114. struct btrfs_file_extent_item *ei;
  9115. struct extent_buffer *leaf;
  9116. name_len = strlen(symname);
  9117. if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
  9118. return -ENAMETOOLONG;
  9119. /*
  9120. * 2 items for inode item and ref
  9121. * 2 items for dir items
  9122. * 1 item for updating parent inode item
  9123. * 1 item for the inline extent item
  9124. * 1 item for xattr if selinux is on
  9125. */
  9126. trans = btrfs_start_transaction(root, 7);
  9127. if (IS_ERR(trans))
  9128. return PTR_ERR(trans);
  9129. err = btrfs_find_free_ino(root, &objectid);
  9130. if (err)
  9131. goto out_unlock;
  9132. inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
  9133. dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
  9134. objectid, S_IFLNK|S_IRWXUGO, &index);
  9135. if (IS_ERR(inode)) {
  9136. err = PTR_ERR(inode);
  9137. goto out_unlock;
  9138. }
  9139. /*
  9140. * If the active LSM wants to access the inode during
  9141. * d_instantiate it needs these. Smack checks to see
  9142. * if the filesystem supports xattrs by looking at the
  9143. * ops vector.
  9144. */
  9145. inode->i_fop = &btrfs_file_operations;
  9146. inode->i_op = &btrfs_file_inode_operations;
  9147. inode->i_mapping->a_ops = &btrfs_aops;
  9148. BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
  9149. err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
  9150. if (err)
  9151. goto out_unlock_inode;
  9152. path = btrfs_alloc_path();
  9153. if (!path) {
  9154. err = -ENOMEM;
  9155. goto out_unlock_inode;
  9156. }
  9157. key.objectid = btrfs_ino(BTRFS_I(inode));
  9158. key.offset = 0;
  9159. key.type = BTRFS_EXTENT_DATA_KEY;
  9160. datasize = btrfs_file_extent_calc_inline_size(name_len);
  9161. err = btrfs_insert_empty_item(trans, root, path, &key,
  9162. datasize);
  9163. if (err) {
  9164. btrfs_free_path(path);
  9165. goto out_unlock_inode;
  9166. }
  9167. leaf = path->nodes[0];
  9168. ei = btrfs_item_ptr(leaf, path->slots[0],
  9169. struct btrfs_file_extent_item);
  9170. btrfs_set_file_extent_generation(leaf, ei, trans->transid);
  9171. btrfs_set_file_extent_type(leaf, ei,
  9172. BTRFS_FILE_EXTENT_INLINE);
  9173. btrfs_set_file_extent_encryption(leaf, ei, 0);
  9174. btrfs_set_file_extent_compression(leaf, ei, 0);
  9175. btrfs_set_file_extent_other_encoding(leaf, ei, 0);
  9176. btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
  9177. ptr = btrfs_file_extent_inline_start(ei);
  9178. write_extent_buffer(leaf, symname, ptr, name_len);
  9179. btrfs_mark_buffer_dirty(leaf);
  9180. btrfs_free_path(path);
  9181. inode->i_op = &btrfs_symlink_inode_operations;
  9182. inode_nohighmem(inode);
  9183. inode->i_mapping->a_ops = &btrfs_symlink_aops;
  9184. inode_set_bytes(inode, name_len);
  9185. btrfs_i_size_write(BTRFS_I(inode), name_len);
  9186. err = btrfs_update_inode(trans, root, inode);
  9187. /*
  9188. * Last step, add directory indexes for our symlink inode. This is the
  9189. * last step to avoid extra cleanup of these indexes if an error happens
  9190. * elsewhere above.
  9191. */
  9192. if (!err)
  9193. err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
  9194. BTRFS_I(inode), 0, index);
  9195. if (err) {
  9196. drop_inode = 1;
  9197. goto out_unlock_inode;
  9198. }
  9199. unlock_new_inode(inode);
  9200. d_instantiate(dentry, inode);
  9201. out_unlock:
  9202. btrfs_end_transaction(trans);
  9203. if (drop_inode) {
  9204. inode_dec_link_count(inode);
  9205. iput(inode);
  9206. }
  9207. btrfs_btree_balance_dirty(fs_info);
  9208. return err;
  9209. out_unlock_inode:
  9210. drop_inode = 1;
  9211. unlock_new_inode(inode);
  9212. goto out_unlock;
  9213. }
  9214. static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
  9215. u64 start, u64 num_bytes, u64 min_size,
  9216. loff_t actual_len, u64 *alloc_hint,
  9217. struct btrfs_trans_handle *trans)
  9218. {
  9219. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  9220. struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
  9221. struct extent_map *em;
  9222. struct btrfs_root *root = BTRFS_I(inode)->root;
  9223. struct btrfs_key ins;
  9224. u64 cur_offset = start;
  9225. u64 i_size;
  9226. u64 cur_bytes;
  9227. u64 last_alloc = (u64)-1;
  9228. int ret = 0;
  9229. bool own_trans = true;
  9230. u64 end = start + num_bytes - 1;
  9231. if (trans)
  9232. own_trans = false;
  9233. while (num_bytes > 0) {
  9234. if (own_trans) {
  9235. trans = btrfs_start_transaction(root, 3);
  9236. if (IS_ERR(trans)) {
  9237. ret = PTR_ERR(trans);
  9238. break;
  9239. }
  9240. }
  9241. cur_bytes = min_t(u64, num_bytes, SZ_256M);
  9242. cur_bytes = max(cur_bytes, min_size);
  9243. /*
  9244. * If we are severely fragmented we could end up with really
  9245. * small allocations, so if the allocator is returning small
  9246. * chunks lets make its job easier by only searching for those
  9247. * sized chunks.
  9248. */
  9249. cur_bytes = min(cur_bytes, last_alloc);
  9250. ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
  9251. min_size, 0, *alloc_hint, &ins, 1, 0);
  9252. if (ret) {
  9253. if (own_trans)
  9254. btrfs_end_transaction(trans);
  9255. break;
  9256. }
  9257. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  9258. last_alloc = ins.offset;
  9259. ret = insert_reserved_file_extent(trans, inode,
  9260. cur_offset, ins.objectid,
  9261. ins.offset, ins.offset,
  9262. ins.offset, 0, 0, 0,
  9263. BTRFS_FILE_EXTENT_PREALLOC);
  9264. if (ret) {
  9265. btrfs_free_reserved_extent(fs_info, ins.objectid,
  9266. ins.offset, 0);
  9267. btrfs_abort_transaction(trans, ret);
  9268. if (own_trans)
  9269. btrfs_end_transaction(trans);
  9270. break;
  9271. }
  9272. btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
  9273. cur_offset + ins.offset -1, 0);
  9274. em = alloc_extent_map();
  9275. if (!em) {
  9276. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  9277. &BTRFS_I(inode)->runtime_flags);
  9278. goto next;
  9279. }
  9280. em->start = cur_offset;
  9281. em->orig_start = cur_offset;
  9282. em->len = ins.offset;
  9283. em->block_start = ins.objectid;
  9284. em->block_len = ins.offset;
  9285. em->orig_block_len = ins.offset;
  9286. em->ram_bytes = ins.offset;
  9287. em->bdev = fs_info->fs_devices->latest_bdev;
  9288. set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
  9289. em->generation = trans->transid;
  9290. while (1) {
  9291. write_lock(&em_tree->lock);
  9292. ret = add_extent_mapping(em_tree, em, 1);
  9293. write_unlock(&em_tree->lock);
  9294. if (ret != -EEXIST)
  9295. break;
  9296. btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
  9297. cur_offset + ins.offset - 1,
  9298. 0);
  9299. }
  9300. free_extent_map(em);
  9301. next:
  9302. num_bytes -= ins.offset;
  9303. cur_offset += ins.offset;
  9304. *alloc_hint = ins.objectid + ins.offset;
  9305. inode_inc_iversion(inode);
  9306. inode->i_ctime = current_time(inode);
  9307. BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
  9308. if (!(mode & FALLOC_FL_KEEP_SIZE) &&
  9309. (actual_len > inode->i_size) &&
  9310. (cur_offset > inode->i_size)) {
  9311. if (cur_offset > actual_len)
  9312. i_size = actual_len;
  9313. else
  9314. i_size = cur_offset;
  9315. i_size_write(inode, i_size);
  9316. btrfs_ordered_update_i_size(inode, i_size, NULL);
  9317. }
  9318. ret = btrfs_update_inode(trans, root, inode);
  9319. if (ret) {
  9320. btrfs_abort_transaction(trans, ret);
  9321. if (own_trans)
  9322. btrfs_end_transaction(trans);
  9323. break;
  9324. }
  9325. if (own_trans)
  9326. btrfs_end_transaction(trans);
  9327. }
  9328. if (cur_offset < end)
  9329. btrfs_free_reserved_data_space(inode, NULL, cur_offset,
  9330. end - cur_offset + 1);
  9331. return ret;
  9332. }
  9333. int btrfs_prealloc_file_range(struct inode *inode, int mode,
  9334. u64 start, u64 num_bytes, u64 min_size,
  9335. loff_t actual_len, u64 *alloc_hint)
  9336. {
  9337. return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
  9338. min_size, actual_len, alloc_hint,
  9339. NULL);
  9340. }
  9341. int btrfs_prealloc_file_range_trans(struct inode *inode,
  9342. struct btrfs_trans_handle *trans, int mode,
  9343. u64 start, u64 num_bytes, u64 min_size,
  9344. loff_t actual_len, u64 *alloc_hint)
  9345. {
  9346. return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
  9347. min_size, actual_len, alloc_hint, trans);
  9348. }
  9349. static int btrfs_set_page_dirty(struct page *page)
  9350. {
  9351. return __set_page_dirty_nobuffers(page);
  9352. }
  9353. static int btrfs_permission(struct inode *inode, int mask)
  9354. {
  9355. struct btrfs_root *root = BTRFS_I(inode)->root;
  9356. umode_t mode = inode->i_mode;
  9357. if (mask & MAY_WRITE &&
  9358. (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
  9359. if (btrfs_root_readonly(root))
  9360. return -EROFS;
  9361. if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
  9362. return -EACCES;
  9363. }
  9364. return generic_permission(inode, mask);
  9365. }
  9366. static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
  9367. {
  9368. struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
  9369. struct btrfs_trans_handle *trans;
  9370. struct btrfs_root *root = BTRFS_I(dir)->root;
  9371. struct inode *inode = NULL;
  9372. u64 objectid;
  9373. u64 index;
  9374. int ret = 0;
  9375. /*
  9376. * 5 units required for adding orphan entry
  9377. */
  9378. trans = btrfs_start_transaction(root, 5);
  9379. if (IS_ERR(trans))
  9380. return PTR_ERR(trans);
  9381. ret = btrfs_find_free_ino(root, &objectid);
  9382. if (ret)
  9383. goto out;
  9384. inode = btrfs_new_inode(trans, root, dir, NULL, 0,
  9385. btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
  9386. if (IS_ERR(inode)) {
  9387. ret = PTR_ERR(inode);
  9388. inode = NULL;
  9389. goto out;
  9390. }
  9391. inode->i_fop = &btrfs_file_operations;
  9392. inode->i_op = &btrfs_file_inode_operations;
  9393. inode->i_mapping->a_ops = &btrfs_aops;
  9394. BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
  9395. ret = btrfs_init_inode_security(trans, inode, dir, NULL);
  9396. if (ret)
  9397. goto out_inode;
  9398. ret = btrfs_update_inode(trans, root, inode);
  9399. if (ret)
  9400. goto out_inode;
  9401. ret = btrfs_orphan_add(trans, BTRFS_I(inode));
  9402. if (ret)
  9403. goto out_inode;
  9404. /*
  9405. * We set number of links to 0 in btrfs_new_inode(), and here we set
  9406. * it to 1 because d_tmpfile() will issue a warning if the count is 0,
  9407. * through:
  9408. *
  9409. * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
  9410. */
  9411. set_nlink(inode, 1);
  9412. unlock_new_inode(inode);
  9413. d_tmpfile(dentry, inode);
  9414. mark_inode_dirty(inode);
  9415. out:
  9416. btrfs_end_transaction(trans);
  9417. if (ret)
  9418. iput(inode);
  9419. btrfs_btree_balance_dirty(fs_info);
  9420. return ret;
  9421. out_inode:
  9422. unlock_new_inode(inode);
  9423. goto out;
  9424. }
  9425. __attribute__((const))
  9426. static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
  9427. {
  9428. return -EAGAIN;
  9429. }
  9430. static struct btrfs_fs_info *iotree_fs_info(void *private_data)
  9431. {
  9432. struct inode *inode = private_data;
  9433. return btrfs_sb(inode->i_sb);
  9434. }
  9435. static void btrfs_check_extent_io_range(void *private_data, const char *caller,
  9436. u64 start, u64 end)
  9437. {
  9438. struct inode *inode = private_data;
  9439. u64 isize;
  9440. isize = i_size_read(inode);
  9441. if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
  9442. btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
  9443. "%s: ino %llu isize %llu odd range [%llu,%llu]",
  9444. caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
  9445. }
  9446. }
  9447. void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
  9448. {
  9449. struct inode *inode = private_data;
  9450. unsigned long index = start >> PAGE_SHIFT;
  9451. unsigned long end_index = end >> PAGE_SHIFT;
  9452. struct page *page;
  9453. while (index <= end_index) {
  9454. page = find_get_page(inode->i_mapping, index);
  9455. ASSERT(page); /* Pages should be in the extent_io_tree */
  9456. set_page_writeback(page);
  9457. put_page(page);
  9458. index++;
  9459. }
  9460. }
  9461. static const struct inode_operations btrfs_dir_inode_operations = {
  9462. .getattr = btrfs_getattr,
  9463. .lookup = btrfs_lookup,
  9464. .create = btrfs_create,
  9465. .unlink = btrfs_unlink,
  9466. .link = btrfs_link,
  9467. .mkdir = btrfs_mkdir,
  9468. .rmdir = btrfs_rmdir,
  9469. .rename = btrfs_rename2,
  9470. .symlink = btrfs_symlink,
  9471. .setattr = btrfs_setattr,
  9472. .mknod = btrfs_mknod,
  9473. .listxattr = btrfs_listxattr,
  9474. .permission = btrfs_permission,
  9475. .get_acl = btrfs_get_acl,
  9476. .set_acl = btrfs_set_acl,
  9477. .update_time = btrfs_update_time,
  9478. .tmpfile = btrfs_tmpfile,
  9479. };
  9480. static const struct inode_operations btrfs_dir_ro_inode_operations = {
  9481. .lookup = btrfs_lookup,
  9482. .permission = btrfs_permission,
  9483. .update_time = btrfs_update_time,
  9484. };
  9485. static const struct file_operations btrfs_dir_file_operations = {
  9486. .llseek = generic_file_llseek,
  9487. .read = generic_read_dir,
  9488. .iterate_shared = btrfs_real_readdir,
  9489. .open = btrfs_opendir,
  9490. .unlocked_ioctl = btrfs_ioctl,
  9491. #ifdef CONFIG_COMPAT
  9492. .compat_ioctl = btrfs_compat_ioctl,
  9493. #endif
  9494. .release = btrfs_release_file,
  9495. .fsync = btrfs_sync_file,
  9496. };
  9497. static const struct extent_io_ops btrfs_extent_io_ops = {
  9498. /* mandatory callbacks */
  9499. .submit_bio_hook = btrfs_submit_bio_hook,
  9500. .readpage_end_io_hook = btrfs_readpage_end_io_hook,
  9501. .merge_bio_hook = btrfs_merge_bio_hook,
  9502. .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
  9503. .tree_fs_info = iotree_fs_info,
  9504. .set_range_writeback = btrfs_set_range_writeback,
  9505. /* optional callbacks */
  9506. .fill_delalloc = run_delalloc_range,
  9507. .writepage_end_io_hook = btrfs_writepage_end_io_hook,
  9508. .writepage_start_hook = btrfs_writepage_start_hook,
  9509. .set_bit_hook = btrfs_set_bit_hook,
  9510. .clear_bit_hook = btrfs_clear_bit_hook,
  9511. .merge_extent_hook = btrfs_merge_extent_hook,
  9512. .split_extent_hook = btrfs_split_extent_hook,
  9513. .check_extent_io_range = btrfs_check_extent_io_range,
  9514. };
  9515. /*
  9516. * btrfs doesn't support the bmap operation because swapfiles
  9517. * use bmap to make a mapping of extents in the file. They assume
  9518. * these extents won't change over the life of the file and they
  9519. * use the bmap result to do IO directly to the drive.
  9520. *
  9521. * the btrfs bmap call would return logical addresses that aren't
  9522. * suitable for IO and they also will change frequently as COW
  9523. * operations happen. So, swapfile + btrfs == corruption.
  9524. *
  9525. * For now we're avoiding this by dropping bmap.
  9526. */
  9527. static const struct address_space_operations btrfs_aops = {
  9528. .readpage = btrfs_readpage,
  9529. .writepage = btrfs_writepage,
  9530. .writepages = btrfs_writepages,
  9531. .readpages = btrfs_readpages,
  9532. .direct_IO = btrfs_direct_IO,
  9533. .invalidatepage = btrfs_invalidatepage,
  9534. .releasepage = btrfs_releasepage,
  9535. .set_page_dirty = btrfs_set_page_dirty,
  9536. .error_remove_page = generic_error_remove_page,
  9537. };
  9538. static const struct address_space_operations btrfs_symlink_aops = {
  9539. .readpage = btrfs_readpage,
  9540. .writepage = btrfs_writepage,
  9541. .invalidatepage = btrfs_invalidatepage,
  9542. .releasepage = btrfs_releasepage,
  9543. };
  9544. static const struct inode_operations btrfs_file_inode_operations = {
  9545. .getattr = btrfs_getattr,
  9546. .setattr = btrfs_setattr,
  9547. .listxattr = btrfs_listxattr,
  9548. .permission = btrfs_permission,
  9549. .fiemap = btrfs_fiemap,
  9550. .get_acl = btrfs_get_acl,
  9551. .set_acl = btrfs_set_acl,
  9552. .update_time = btrfs_update_time,
  9553. };
  9554. static const struct inode_operations btrfs_special_inode_operations = {
  9555. .getattr = btrfs_getattr,
  9556. .setattr = btrfs_setattr,
  9557. .permission = btrfs_permission,
  9558. .listxattr = btrfs_listxattr,
  9559. .get_acl = btrfs_get_acl,
  9560. .set_acl = btrfs_set_acl,
  9561. .update_time = btrfs_update_time,
  9562. };
  9563. static const struct inode_operations btrfs_symlink_inode_operations = {
  9564. .get_link = page_get_link,
  9565. .getattr = btrfs_getattr,
  9566. .setattr = btrfs_setattr,
  9567. .permission = btrfs_permission,
  9568. .listxattr = btrfs_listxattr,
  9569. .update_time = btrfs_update_time,
  9570. };
  9571. const struct dentry_operations btrfs_dentry_operations = {
  9572. .d_delete = btrfs_dentry_delete,
  9573. .d_release = btrfs_dentry_release,
  9574. };