inode.c 287 KB

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