inode.c 291 KB

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