inode.c 291 KB

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