inode.c 291 KB

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