inode.c 289 KB

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