inode.c 281 KB

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