inode.c 291 KB

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