inode.c 290 KB

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