inode.c 291 KB

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