extent-tree.c 262 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774
  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/sched.h>
  19. #include <linux/pagemap.h>
  20. #include <linux/writeback.h>
  21. #include <linux/blkdev.h>
  22. #include <linux/sort.h>
  23. #include <linux/rcupdate.h>
  24. #include <linux/kthread.h>
  25. #include <linux/slab.h>
  26. #include <linux/ratelimit.h>
  27. #include <linux/percpu_counter.h>
  28. #include "hash.h"
  29. #include "tree-log.h"
  30. #include "disk-io.h"
  31. #include "print-tree.h"
  32. #include "volumes.h"
  33. #include "raid56.h"
  34. #include "locking.h"
  35. #include "free-space-cache.h"
  36. #include "math.h"
  37. #include "sysfs.h"
  38. #include "qgroup.h"
  39. #undef SCRAMBLE_DELAYED_REFS
  40. /*
  41. * control flags for do_chunk_alloc's force field
  42. * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
  43. * if we really need one.
  44. *
  45. * CHUNK_ALLOC_LIMITED means to only try and allocate one
  46. * if we have very few chunks already allocated. This is
  47. * used as part of the clustering code to help make sure
  48. * we have a good pool of storage to cluster in, without
  49. * filling the FS with empty chunks
  50. *
  51. * CHUNK_ALLOC_FORCE means it must try to allocate one
  52. *
  53. */
  54. enum {
  55. CHUNK_ALLOC_NO_FORCE = 0,
  56. CHUNK_ALLOC_LIMITED = 1,
  57. CHUNK_ALLOC_FORCE = 2,
  58. };
  59. /*
  60. * Control how reservations are dealt with.
  61. *
  62. * RESERVE_FREE - freeing a reservation.
  63. * RESERVE_ALLOC - allocating space and we need to update bytes_may_use for
  64. * ENOSPC accounting
  65. * RESERVE_ALLOC_NO_ACCOUNT - allocating space and we should not update
  66. * bytes_may_use as the ENOSPC accounting is done elsewhere
  67. */
  68. enum {
  69. RESERVE_FREE = 0,
  70. RESERVE_ALLOC = 1,
  71. RESERVE_ALLOC_NO_ACCOUNT = 2,
  72. };
  73. static int update_block_group(struct btrfs_trans_handle *trans,
  74. struct btrfs_root *root, u64 bytenr,
  75. u64 num_bytes, int alloc);
  76. static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
  77. struct btrfs_root *root,
  78. u64 bytenr, u64 num_bytes, u64 parent,
  79. u64 root_objectid, u64 owner_objectid,
  80. u64 owner_offset, int refs_to_drop,
  81. struct btrfs_delayed_extent_op *extra_op,
  82. int no_quota);
  83. static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
  84. struct extent_buffer *leaf,
  85. struct btrfs_extent_item *ei);
  86. static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
  87. struct btrfs_root *root,
  88. u64 parent, u64 root_objectid,
  89. u64 flags, u64 owner, u64 offset,
  90. struct btrfs_key *ins, int ref_mod);
  91. static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
  92. struct btrfs_root *root,
  93. u64 parent, u64 root_objectid,
  94. u64 flags, struct btrfs_disk_key *key,
  95. int level, struct btrfs_key *ins,
  96. int no_quota);
  97. static int do_chunk_alloc(struct btrfs_trans_handle *trans,
  98. struct btrfs_root *extent_root, u64 flags,
  99. int force);
  100. static int find_next_key(struct btrfs_path *path, int level,
  101. struct btrfs_key *key);
  102. static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
  103. int dump_block_groups);
  104. static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
  105. u64 num_bytes, int reserve,
  106. int delalloc);
  107. static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
  108. u64 num_bytes);
  109. int btrfs_pin_extent(struct btrfs_root *root,
  110. u64 bytenr, u64 num_bytes, int reserved);
  111. static noinline int
  112. block_group_cache_done(struct btrfs_block_group_cache *cache)
  113. {
  114. smp_mb();
  115. return cache->cached == BTRFS_CACHE_FINISHED ||
  116. cache->cached == BTRFS_CACHE_ERROR;
  117. }
  118. static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
  119. {
  120. return (cache->flags & bits) == bits;
  121. }
  122. static void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
  123. {
  124. atomic_inc(&cache->count);
  125. }
  126. void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
  127. {
  128. if (atomic_dec_and_test(&cache->count)) {
  129. WARN_ON(cache->pinned > 0);
  130. WARN_ON(cache->reserved > 0);
  131. kfree(cache->free_space_ctl);
  132. kfree(cache);
  133. }
  134. }
  135. /*
  136. * this adds the block group to the fs_info rb tree for the block group
  137. * cache
  138. */
  139. static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
  140. struct btrfs_block_group_cache *block_group)
  141. {
  142. struct rb_node **p;
  143. struct rb_node *parent = NULL;
  144. struct btrfs_block_group_cache *cache;
  145. spin_lock(&info->block_group_cache_lock);
  146. p = &info->block_group_cache_tree.rb_node;
  147. while (*p) {
  148. parent = *p;
  149. cache = rb_entry(parent, struct btrfs_block_group_cache,
  150. cache_node);
  151. if (block_group->key.objectid < cache->key.objectid) {
  152. p = &(*p)->rb_left;
  153. } else if (block_group->key.objectid > cache->key.objectid) {
  154. p = &(*p)->rb_right;
  155. } else {
  156. spin_unlock(&info->block_group_cache_lock);
  157. return -EEXIST;
  158. }
  159. }
  160. rb_link_node(&block_group->cache_node, parent, p);
  161. rb_insert_color(&block_group->cache_node,
  162. &info->block_group_cache_tree);
  163. if (info->first_logical_byte > block_group->key.objectid)
  164. info->first_logical_byte = block_group->key.objectid;
  165. spin_unlock(&info->block_group_cache_lock);
  166. return 0;
  167. }
  168. /*
  169. * This will return the block group at or after bytenr if contains is 0, else
  170. * it will return the block group that contains the bytenr
  171. */
  172. static struct btrfs_block_group_cache *
  173. block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
  174. int contains)
  175. {
  176. struct btrfs_block_group_cache *cache, *ret = NULL;
  177. struct rb_node *n;
  178. u64 end, start;
  179. spin_lock(&info->block_group_cache_lock);
  180. n = info->block_group_cache_tree.rb_node;
  181. while (n) {
  182. cache = rb_entry(n, struct btrfs_block_group_cache,
  183. cache_node);
  184. end = cache->key.objectid + cache->key.offset - 1;
  185. start = cache->key.objectid;
  186. if (bytenr < start) {
  187. if (!contains && (!ret || start < ret->key.objectid))
  188. ret = cache;
  189. n = n->rb_left;
  190. } else if (bytenr > start) {
  191. if (contains && bytenr <= end) {
  192. ret = cache;
  193. break;
  194. }
  195. n = n->rb_right;
  196. } else {
  197. ret = cache;
  198. break;
  199. }
  200. }
  201. if (ret) {
  202. btrfs_get_block_group(ret);
  203. if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
  204. info->first_logical_byte = ret->key.objectid;
  205. }
  206. spin_unlock(&info->block_group_cache_lock);
  207. return ret;
  208. }
  209. static int add_excluded_extent(struct btrfs_root *root,
  210. u64 start, u64 num_bytes)
  211. {
  212. u64 end = start + num_bytes - 1;
  213. set_extent_bits(&root->fs_info->freed_extents[0],
  214. start, end, EXTENT_UPTODATE, GFP_NOFS);
  215. set_extent_bits(&root->fs_info->freed_extents[1],
  216. start, end, EXTENT_UPTODATE, GFP_NOFS);
  217. return 0;
  218. }
  219. static void free_excluded_extents(struct btrfs_root *root,
  220. struct btrfs_block_group_cache *cache)
  221. {
  222. u64 start, end;
  223. start = cache->key.objectid;
  224. end = start + cache->key.offset - 1;
  225. clear_extent_bits(&root->fs_info->freed_extents[0],
  226. start, end, EXTENT_UPTODATE, GFP_NOFS);
  227. clear_extent_bits(&root->fs_info->freed_extents[1],
  228. start, end, EXTENT_UPTODATE, GFP_NOFS);
  229. }
  230. static int exclude_super_stripes(struct btrfs_root *root,
  231. struct btrfs_block_group_cache *cache)
  232. {
  233. u64 bytenr;
  234. u64 *logical;
  235. int stripe_len;
  236. int i, nr, ret;
  237. if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
  238. stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
  239. cache->bytes_super += stripe_len;
  240. ret = add_excluded_extent(root, cache->key.objectid,
  241. stripe_len);
  242. if (ret)
  243. return ret;
  244. }
  245. for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
  246. bytenr = btrfs_sb_offset(i);
  247. ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
  248. cache->key.objectid, bytenr,
  249. 0, &logical, &nr, &stripe_len);
  250. if (ret)
  251. return ret;
  252. while (nr--) {
  253. u64 start, len;
  254. if (logical[nr] > cache->key.objectid +
  255. cache->key.offset)
  256. continue;
  257. if (logical[nr] + stripe_len <= cache->key.objectid)
  258. continue;
  259. start = logical[nr];
  260. if (start < cache->key.objectid) {
  261. start = cache->key.objectid;
  262. len = (logical[nr] + stripe_len) - start;
  263. } else {
  264. len = min_t(u64, stripe_len,
  265. cache->key.objectid +
  266. cache->key.offset - start);
  267. }
  268. cache->bytes_super += len;
  269. ret = add_excluded_extent(root, start, len);
  270. if (ret) {
  271. kfree(logical);
  272. return ret;
  273. }
  274. }
  275. kfree(logical);
  276. }
  277. return 0;
  278. }
  279. static struct btrfs_caching_control *
  280. get_caching_control(struct btrfs_block_group_cache *cache)
  281. {
  282. struct btrfs_caching_control *ctl;
  283. spin_lock(&cache->lock);
  284. if (!cache->caching_ctl) {
  285. spin_unlock(&cache->lock);
  286. return NULL;
  287. }
  288. ctl = cache->caching_ctl;
  289. atomic_inc(&ctl->count);
  290. spin_unlock(&cache->lock);
  291. return ctl;
  292. }
  293. static void put_caching_control(struct btrfs_caching_control *ctl)
  294. {
  295. if (atomic_dec_and_test(&ctl->count))
  296. kfree(ctl);
  297. }
  298. /*
  299. * this is only called by cache_block_group, since we could have freed extents
  300. * we need to check the pinned_extents for any extents that can't be used yet
  301. * since their free space will be released as soon as the transaction commits.
  302. */
  303. static u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
  304. struct btrfs_fs_info *info, u64 start, u64 end)
  305. {
  306. u64 extent_start, extent_end, size, total_added = 0;
  307. int ret;
  308. while (start < end) {
  309. ret = find_first_extent_bit(info->pinned_extents, start,
  310. &extent_start, &extent_end,
  311. EXTENT_DIRTY | EXTENT_UPTODATE,
  312. NULL);
  313. if (ret)
  314. break;
  315. if (extent_start <= start) {
  316. start = extent_end + 1;
  317. } else if (extent_start > start && extent_start < end) {
  318. size = extent_start - start;
  319. total_added += size;
  320. ret = btrfs_add_free_space(block_group, start,
  321. size);
  322. BUG_ON(ret); /* -ENOMEM or logic error */
  323. start = extent_end + 1;
  324. } else {
  325. break;
  326. }
  327. }
  328. if (start < end) {
  329. size = end - start;
  330. total_added += size;
  331. ret = btrfs_add_free_space(block_group, start, size);
  332. BUG_ON(ret); /* -ENOMEM or logic error */
  333. }
  334. return total_added;
  335. }
  336. static noinline void caching_thread(struct btrfs_work *work)
  337. {
  338. struct btrfs_block_group_cache *block_group;
  339. struct btrfs_fs_info *fs_info;
  340. struct btrfs_caching_control *caching_ctl;
  341. struct btrfs_root *extent_root;
  342. struct btrfs_path *path;
  343. struct extent_buffer *leaf;
  344. struct btrfs_key key;
  345. u64 total_found = 0;
  346. u64 last = 0;
  347. u32 nritems;
  348. int ret = -ENOMEM;
  349. caching_ctl = container_of(work, struct btrfs_caching_control, work);
  350. block_group = caching_ctl->block_group;
  351. fs_info = block_group->fs_info;
  352. extent_root = fs_info->extent_root;
  353. path = btrfs_alloc_path();
  354. if (!path)
  355. goto out;
  356. last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
  357. /*
  358. * We don't want to deadlock with somebody trying to allocate a new
  359. * extent for the extent root while also trying to search the extent
  360. * root to add free space. So we skip locking and search the commit
  361. * root, since its read-only
  362. */
  363. path->skip_locking = 1;
  364. path->search_commit_root = 1;
  365. path->reada = 1;
  366. key.objectid = last;
  367. key.offset = 0;
  368. key.type = BTRFS_EXTENT_ITEM_KEY;
  369. again:
  370. mutex_lock(&caching_ctl->mutex);
  371. /* need to make sure the commit_root doesn't disappear */
  372. down_read(&fs_info->commit_root_sem);
  373. next:
  374. ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
  375. if (ret < 0)
  376. goto err;
  377. leaf = path->nodes[0];
  378. nritems = btrfs_header_nritems(leaf);
  379. while (1) {
  380. if (btrfs_fs_closing(fs_info) > 1) {
  381. last = (u64)-1;
  382. break;
  383. }
  384. if (path->slots[0] < nritems) {
  385. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  386. } else {
  387. ret = find_next_key(path, 0, &key);
  388. if (ret)
  389. break;
  390. if (need_resched() ||
  391. rwsem_is_contended(&fs_info->commit_root_sem)) {
  392. caching_ctl->progress = last;
  393. btrfs_release_path(path);
  394. up_read(&fs_info->commit_root_sem);
  395. mutex_unlock(&caching_ctl->mutex);
  396. cond_resched();
  397. goto again;
  398. }
  399. ret = btrfs_next_leaf(extent_root, path);
  400. if (ret < 0)
  401. goto err;
  402. if (ret)
  403. break;
  404. leaf = path->nodes[0];
  405. nritems = btrfs_header_nritems(leaf);
  406. continue;
  407. }
  408. if (key.objectid < last) {
  409. key.objectid = last;
  410. key.offset = 0;
  411. key.type = BTRFS_EXTENT_ITEM_KEY;
  412. caching_ctl->progress = last;
  413. btrfs_release_path(path);
  414. goto next;
  415. }
  416. if (key.objectid < block_group->key.objectid) {
  417. path->slots[0]++;
  418. continue;
  419. }
  420. if (key.objectid >= block_group->key.objectid +
  421. block_group->key.offset)
  422. break;
  423. if (key.type == BTRFS_EXTENT_ITEM_KEY ||
  424. key.type == BTRFS_METADATA_ITEM_KEY) {
  425. total_found += add_new_free_space(block_group,
  426. fs_info, last,
  427. key.objectid);
  428. if (key.type == BTRFS_METADATA_ITEM_KEY)
  429. last = key.objectid +
  430. fs_info->tree_root->nodesize;
  431. else
  432. last = key.objectid + key.offset;
  433. if (total_found > (1024 * 1024 * 2)) {
  434. total_found = 0;
  435. wake_up(&caching_ctl->wait);
  436. }
  437. }
  438. path->slots[0]++;
  439. }
  440. ret = 0;
  441. total_found += add_new_free_space(block_group, fs_info, last,
  442. block_group->key.objectid +
  443. block_group->key.offset);
  444. caching_ctl->progress = (u64)-1;
  445. spin_lock(&block_group->lock);
  446. block_group->caching_ctl = NULL;
  447. block_group->cached = BTRFS_CACHE_FINISHED;
  448. spin_unlock(&block_group->lock);
  449. err:
  450. btrfs_free_path(path);
  451. up_read(&fs_info->commit_root_sem);
  452. free_excluded_extents(extent_root, block_group);
  453. mutex_unlock(&caching_ctl->mutex);
  454. out:
  455. if (ret) {
  456. spin_lock(&block_group->lock);
  457. block_group->caching_ctl = NULL;
  458. block_group->cached = BTRFS_CACHE_ERROR;
  459. spin_unlock(&block_group->lock);
  460. }
  461. wake_up(&caching_ctl->wait);
  462. put_caching_control(caching_ctl);
  463. btrfs_put_block_group(block_group);
  464. }
  465. static int cache_block_group(struct btrfs_block_group_cache *cache,
  466. int load_cache_only)
  467. {
  468. DEFINE_WAIT(wait);
  469. struct btrfs_fs_info *fs_info = cache->fs_info;
  470. struct btrfs_caching_control *caching_ctl;
  471. int ret = 0;
  472. caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
  473. if (!caching_ctl)
  474. return -ENOMEM;
  475. INIT_LIST_HEAD(&caching_ctl->list);
  476. mutex_init(&caching_ctl->mutex);
  477. init_waitqueue_head(&caching_ctl->wait);
  478. caching_ctl->block_group = cache;
  479. caching_ctl->progress = cache->key.objectid;
  480. atomic_set(&caching_ctl->count, 1);
  481. btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
  482. caching_thread, NULL, NULL);
  483. spin_lock(&cache->lock);
  484. /*
  485. * This should be a rare occasion, but this could happen I think in the
  486. * case where one thread starts to load the space cache info, and then
  487. * some other thread starts a transaction commit which tries to do an
  488. * allocation while the other thread is still loading the space cache
  489. * info. The previous loop should have kept us from choosing this block
  490. * group, but if we've moved to the state where we will wait on caching
  491. * block groups we need to first check if we're doing a fast load here,
  492. * so we can wait for it to finish, otherwise we could end up allocating
  493. * from a block group who's cache gets evicted for one reason or
  494. * another.
  495. */
  496. while (cache->cached == BTRFS_CACHE_FAST) {
  497. struct btrfs_caching_control *ctl;
  498. ctl = cache->caching_ctl;
  499. atomic_inc(&ctl->count);
  500. prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
  501. spin_unlock(&cache->lock);
  502. schedule();
  503. finish_wait(&ctl->wait, &wait);
  504. put_caching_control(ctl);
  505. spin_lock(&cache->lock);
  506. }
  507. if (cache->cached != BTRFS_CACHE_NO) {
  508. spin_unlock(&cache->lock);
  509. kfree(caching_ctl);
  510. return 0;
  511. }
  512. WARN_ON(cache->caching_ctl);
  513. cache->caching_ctl = caching_ctl;
  514. cache->cached = BTRFS_CACHE_FAST;
  515. spin_unlock(&cache->lock);
  516. if (fs_info->mount_opt & BTRFS_MOUNT_SPACE_CACHE) {
  517. mutex_lock(&caching_ctl->mutex);
  518. ret = load_free_space_cache(fs_info, cache);
  519. spin_lock(&cache->lock);
  520. if (ret == 1) {
  521. cache->caching_ctl = NULL;
  522. cache->cached = BTRFS_CACHE_FINISHED;
  523. cache->last_byte_to_unpin = (u64)-1;
  524. caching_ctl->progress = (u64)-1;
  525. } else {
  526. if (load_cache_only) {
  527. cache->caching_ctl = NULL;
  528. cache->cached = BTRFS_CACHE_NO;
  529. } else {
  530. cache->cached = BTRFS_CACHE_STARTED;
  531. cache->has_caching_ctl = 1;
  532. }
  533. }
  534. spin_unlock(&cache->lock);
  535. mutex_unlock(&caching_ctl->mutex);
  536. wake_up(&caching_ctl->wait);
  537. if (ret == 1) {
  538. put_caching_control(caching_ctl);
  539. free_excluded_extents(fs_info->extent_root, cache);
  540. return 0;
  541. }
  542. } else {
  543. /*
  544. * We are not going to do the fast caching, set cached to the
  545. * appropriate value and wakeup any waiters.
  546. */
  547. spin_lock(&cache->lock);
  548. if (load_cache_only) {
  549. cache->caching_ctl = NULL;
  550. cache->cached = BTRFS_CACHE_NO;
  551. } else {
  552. cache->cached = BTRFS_CACHE_STARTED;
  553. cache->has_caching_ctl = 1;
  554. }
  555. spin_unlock(&cache->lock);
  556. wake_up(&caching_ctl->wait);
  557. }
  558. if (load_cache_only) {
  559. put_caching_control(caching_ctl);
  560. return 0;
  561. }
  562. down_write(&fs_info->commit_root_sem);
  563. atomic_inc(&caching_ctl->count);
  564. list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
  565. up_write(&fs_info->commit_root_sem);
  566. btrfs_get_block_group(cache);
  567. btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
  568. return ret;
  569. }
  570. /*
  571. * return the block group that starts at or after bytenr
  572. */
  573. static struct btrfs_block_group_cache *
  574. btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
  575. {
  576. struct btrfs_block_group_cache *cache;
  577. cache = block_group_cache_tree_search(info, bytenr, 0);
  578. return cache;
  579. }
  580. /*
  581. * return the block group that contains the given bytenr
  582. */
  583. struct btrfs_block_group_cache *btrfs_lookup_block_group(
  584. struct btrfs_fs_info *info,
  585. u64 bytenr)
  586. {
  587. struct btrfs_block_group_cache *cache;
  588. cache = block_group_cache_tree_search(info, bytenr, 1);
  589. return cache;
  590. }
  591. static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
  592. u64 flags)
  593. {
  594. struct list_head *head = &info->space_info;
  595. struct btrfs_space_info *found;
  596. flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
  597. rcu_read_lock();
  598. list_for_each_entry_rcu(found, head, list) {
  599. if (found->flags & flags) {
  600. rcu_read_unlock();
  601. return found;
  602. }
  603. }
  604. rcu_read_unlock();
  605. return NULL;
  606. }
  607. /*
  608. * after adding space to the filesystem, we need to clear the full flags
  609. * on all the space infos.
  610. */
  611. void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
  612. {
  613. struct list_head *head = &info->space_info;
  614. struct btrfs_space_info *found;
  615. rcu_read_lock();
  616. list_for_each_entry_rcu(found, head, list)
  617. found->full = 0;
  618. rcu_read_unlock();
  619. }
  620. /* simple helper to search for an existing data extent at a given offset */
  621. int btrfs_lookup_data_extent(struct btrfs_root *root, u64 start, u64 len)
  622. {
  623. int ret;
  624. struct btrfs_key key;
  625. struct btrfs_path *path;
  626. path = btrfs_alloc_path();
  627. if (!path)
  628. return -ENOMEM;
  629. key.objectid = start;
  630. key.offset = len;
  631. key.type = BTRFS_EXTENT_ITEM_KEY;
  632. ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
  633. 0, 0);
  634. btrfs_free_path(path);
  635. return ret;
  636. }
  637. /*
  638. * helper function to lookup reference count and flags of a tree block.
  639. *
  640. * the head node for delayed ref is used to store the sum of all the
  641. * reference count modifications queued up in the rbtree. the head
  642. * node may also store the extent flags to set. This way you can check
  643. * to see what the reference count and extent flags would be if all of
  644. * the delayed refs are not processed.
  645. */
  646. int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
  647. struct btrfs_root *root, u64 bytenr,
  648. u64 offset, int metadata, u64 *refs, u64 *flags)
  649. {
  650. struct btrfs_delayed_ref_head *head;
  651. struct btrfs_delayed_ref_root *delayed_refs;
  652. struct btrfs_path *path;
  653. struct btrfs_extent_item *ei;
  654. struct extent_buffer *leaf;
  655. struct btrfs_key key;
  656. u32 item_size;
  657. u64 num_refs;
  658. u64 extent_flags;
  659. int ret;
  660. /*
  661. * If we don't have skinny metadata, don't bother doing anything
  662. * different
  663. */
  664. if (metadata && !btrfs_fs_incompat(root->fs_info, SKINNY_METADATA)) {
  665. offset = root->nodesize;
  666. metadata = 0;
  667. }
  668. path = btrfs_alloc_path();
  669. if (!path)
  670. return -ENOMEM;
  671. if (!trans) {
  672. path->skip_locking = 1;
  673. path->search_commit_root = 1;
  674. }
  675. search_again:
  676. key.objectid = bytenr;
  677. key.offset = offset;
  678. if (metadata)
  679. key.type = BTRFS_METADATA_ITEM_KEY;
  680. else
  681. key.type = BTRFS_EXTENT_ITEM_KEY;
  682. ret = btrfs_search_slot(trans, root->fs_info->extent_root,
  683. &key, path, 0, 0);
  684. if (ret < 0)
  685. goto out_free;
  686. if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
  687. if (path->slots[0]) {
  688. path->slots[0]--;
  689. btrfs_item_key_to_cpu(path->nodes[0], &key,
  690. path->slots[0]);
  691. if (key.objectid == bytenr &&
  692. key.type == BTRFS_EXTENT_ITEM_KEY &&
  693. key.offset == root->nodesize)
  694. ret = 0;
  695. }
  696. }
  697. if (ret == 0) {
  698. leaf = path->nodes[0];
  699. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  700. if (item_size >= sizeof(*ei)) {
  701. ei = btrfs_item_ptr(leaf, path->slots[0],
  702. struct btrfs_extent_item);
  703. num_refs = btrfs_extent_refs(leaf, ei);
  704. extent_flags = btrfs_extent_flags(leaf, ei);
  705. } else {
  706. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  707. struct btrfs_extent_item_v0 *ei0;
  708. BUG_ON(item_size != sizeof(*ei0));
  709. ei0 = btrfs_item_ptr(leaf, path->slots[0],
  710. struct btrfs_extent_item_v0);
  711. num_refs = btrfs_extent_refs_v0(leaf, ei0);
  712. /* FIXME: this isn't correct for data */
  713. extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  714. #else
  715. BUG();
  716. #endif
  717. }
  718. BUG_ON(num_refs == 0);
  719. } else {
  720. num_refs = 0;
  721. extent_flags = 0;
  722. ret = 0;
  723. }
  724. if (!trans)
  725. goto out;
  726. delayed_refs = &trans->transaction->delayed_refs;
  727. spin_lock(&delayed_refs->lock);
  728. head = btrfs_find_delayed_ref_head(trans, bytenr);
  729. if (head) {
  730. if (!mutex_trylock(&head->mutex)) {
  731. atomic_inc(&head->node.refs);
  732. spin_unlock(&delayed_refs->lock);
  733. btrfs_release_path(path);
  734. /*
  735. * Mutex was contended, block until it's released and try
  736. * again
  737. */
  738. mutex_lock(&head->mutex);
  739. mutex_unlock(&head->mutex);
  740. btrfs_put_delayed_ref(&head->node);
  741. goto search_again;
  742. }
  743. spin_lock(&head->lock);
  744. if (head->extent_op && head->extent_op->update_flags)
  745. extent_flags |= head->extent_op->flags_to_set;
  746. else
  747. BUG_ON(num_refs == 0);
  748. num_refs += head->node.ref_mod;
  749. spin_unlock(&head->lock);
  750. mutex_unlock(&head->mutex);
  751. }
  752. spin_unlock(&delayed_refs->lock);
  753. out:
  754. WARN_ON(num_refs == 0);
  755. if (refs)
  756. *refs = num_refs;
  757. if (flags)
  758. *flags = extent_flags;
  759. out_free:
  760. btrfs_free_path(path);
  761. return ret;
  762. }
  763. /*
  764. * Back reference rules. Back refs have three main goals:
  765. *
  766. * 1) differentiate between all holders of references to an extent so that
  767. * when a reference is dropped we can make sure it was a valid reference
  768. * before freeing the extent.
  769. *
  770. * 2) Provide enough information to quickly find the holders of an extent
  771. * if we notice a given block is corrupted or bad.
  772. *
  773. * 3) Make it easy to migrate blocks for FS shrinking or storage pool
  774. * maintenance. This is actually the same as #2, but with a slightly
  775. * different use case.
  776. *
  777. * There are two kinds of back refs. The implicit back refs is optimized
  778. * for pointers in non-shared tree blocks. For a given pointer in a block,
  779. * back refs of this kind provide information about the block's owner tree
  780. * and the pointer's key. These information allow us to find the block by
  781. * b-tree searching. The full back refs is for pointers in tree blocks not
  782. * referenced by their owner trees. The location of tree block is recorded
  783. * in the back refs. Actually the full back refs is generic, and can be
  784. * used in all cases the implicit back refs is used. The major shortcoming
  785. * of the full back refs is its overhead. Every time a tree block gets
  786. * COWed, we have to update back refs entry for all pointers in it.
  787. *
  788. * For a newly allocated tree block, we use implicit back refs for
  789. * pointers in it. This means most tree related operations only involve
  790. * implicit back refs. For a tree block created in old transaction, the
  791. * only way to drop a reference to it is COW it. So we can detect the
  792. * event that tree block loses its owner tree's reference and do the
  793. * back refs conversion.
  794. *
  795. * When a tree block is COW'd through a tree, there are four cases:
  796. *
  797. * The reference count of the block is one and the tree is the block's
  798. * owner tree. Nothing to do in this case.
  799. *
  800. * The reference count of the block is one and the tree is not the
  801. * block's owner tree. In this case, full back refs is used for pointers
  802. * in the block. Remove these full back refs, add implicit back refs for
  803. * every pointers in the new block.
  804. *
  805. * The reference count of the block is greater than one and the tree is
  806. * the block's owner tree. In this case, implicit back refs is used for
  807. * pointers in the block. Add full back refs for every pointers in the
  808. * block, increase lower level extents' reference counts. The original
  809. * implicit back refs are entailed to the new block.
  810. *
  811. * The reference count of the block is greater than one and the tree is
  812. * not the block's owner tree. Add implicit back refs for every pointer in
  813. * the new block, increase lower level extents' reference count.
  814. *
  815. * Back Reference Key composing:
  816. *
  817. * The key objectid corresponds to the first byte in the extent,
  818. * The key type is used to differentiate between types of back refs.
  819. * There are different meanings of the key offset for different types
  820. * of back refs.
  821. *
  822. * File extents can be referenced by:
  823. *
  824. * - multiple snapshots, subvolumes, or different generations in one subvol
  825. * - different files inside a single subvolume
  826. * - different offsets inside a file (bookend extents in file.c)
  827. *
  828. * The extent ref structure for the implicit back refs has fields for:
  829. *
  830. * - Objectid of the subvolume root
  831. * - objectid of the file holding the reference
  832. * - original offset in the file
  833. * - how many bookend extents
  834. *
  835. * The key offset for the implicit back refs is hash of the first
  836. * three fields.
  837. *
  838. * The extent ref structure for the full back refs has field for:
  839. *
  840. * - number of pointers in the tree leaf
  841. *
  842. * The key offset for the implicit back refs is the first byte of
  843. * the tree leaf
  844. *
  845. * When a file extent is allocated, The implicit back refs is used.
  846. * the fields are filled in:
  847. *
  848. * (root_key.objectid, inode objectid, offset in file, 1)
  849. *
  850. * When a file extent is removed file truncation, we find the
  851. * corresponding implicit back refs and check the following fields:
  852. *
  853. * (btrfs_header_owner(leaf), inode objectid, offset in file)
  854. *
  855. * Btree extents can be referenced by:
  856. *
  857. * - Different subvolumes
  858. *
  859. * Both the implicit back refs and the full back refs for tree blocks
  860. * only consist of key. The key offset for the implicit back refs is
  861. * objectid of block's owner tree. The key offset for the full back refs
  862. * is the first byte of parent block.
  863. *
  864. * When implicit back refs is used, information about the lowest key and
  865. * level of the tree block are required. These information are stored in
  866. * tree block info structure.
  867. */
  868. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  869. static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
  870. struct btrfs_root *root,
  871. struct btrfs_path *path,
  872. u64 owner, u32 extra_size)
  873. {
  874. struct btrfs_extent_item *item;
  875. struct btrfs_extent_item_v0 *ei0;
  876. struct btrfs_extent_ref_v0 *ref0;
  877. struct btrfs_tree_block_info *bi;
  878. struct extent_buffer *leaf;
  879. struct btrfs_key key;
  880. struct btrfs_key found_key;
  881. u32 new_size = sizeof(*item);
  882. u64 refs;
  883. int ret;
  884. leaf = path->nodes[0];
  885. BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
  886. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  887. ei0 = btrfs_item_ptr(leaf, path->slots[0],
  888. struct btrfs_extent_item_v0);
  889. refs = btrfs_extent_refs_v0(leaf, ei0);
  890. if (owner == (u64)-1) {
  891. while (1) {
  892. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  893. ret = btrfs_next_leaf(root, path);
  894. if (ret < 0)
  895. return ret;
  896. BUG_ON(ret > 0); /* Corruption */
  897. leaf = path->nodes[0];
  898. }
  899. btrfs_item_key_to_cpu(leaf, &found_key,
  900. path->slots[0]);
  901. BUG_ON(key.objectid != found_key.objectid);
  902. if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
  903. path->slots[0]++;
  904. continue;
  905. }
  906. ref0 = btrfs_item_ptr(leaf, path->slots[0],
  907. struct btrfs_extent_ref_v0);
  908. owner = btrfs_ref_objectid_v0(leaf, ref0);
  909. break;
  910. }
  911. }
  912. btrfs_release_path(path);
  913. if (owner < BTRFS_FIRST_FREE_OBJECTID)
  914. new_size += sizeof(*bi);
  915. new_size -= sizeof(*ei0);
  916. ret = btrfs_search_slot(trans, root, &key, path,
  917. new_size + extra_size, 1);
  918. if (ret < 0)
  919. return ret;
  920. BUG_ON(ret); /* Corruption */
  921. btrfs_extend_item(root, path, new_size);
  922. leaf = path->nodes[0];
  923. item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  924. btrfs_set_extent_refs(leaf, item, refs);
  925. /* FIXME: get real generation */
  926. btrfs_set_extent_generation(leaf, item, 0);
  927. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  928. btrfs_set_extent_flags(leaf, item,
  929. BTRFS_EXTENT_FLAG_TREE_BLOCK |
  930. BTRFS_BLOCK_FLAG_FULL_BACKREF);
  931. bi = (struct btrfs_tree_block_info *)(item + 1);
  932. /* FIXME: get first key of the block */
  933. memset_extent_buffer(leaf, 0, (unsigned long)bi, sizeof(*bi));
  934. btrfs_set_tree_block_level(leaf, bi, (int)owner);
  935. } else {
  936. btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
  937. }
  938. btrfs_mark_buffer_dirty(leaf);
  939. return 0;
  940. }
  941. #endif
  942. static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
  943. {
  944. u32 high_crc = ~(u32)0;
  945. u32 low_crc = ~(u32)0;
  946. __le64 lenum;
  947. lenum = cpu_to_le64(root_objectid);
  948. high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
  949. lenum = cpu_to_le64(owner);
  950. low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
  951. lenum = cpu_to_le64(offset);
  952. low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
  953. return ((u64)high_crc << 31) ^ (u64)low_crc;
  954. }
  955. static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
  956. struct btrfs_extent_data_ref *ref)
  957. {
  958. return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
  959. btrfs_extent_data_ref_objectid(leaf, ref),
  960. btrfs_extent_data_ref_offset(leaf, ref));
  961. }
  962. static int match_extent_data_ref(struct extent_buffer *leaf,
  963. struct btrfs_extent_data_ref *ref,
  964. u64 root_objectid, u64 owner, u64 offset)
  965. {
  966. if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
  967. btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
  968. btrfs_extent_data_ref_offset(leaf, ref) != offset)
  969. return 0;
  970. return 1;
  971. }
  972. static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
  973. struct btrfs_root *root,
  974. struct btrfs_path *path,
  975. u64 bytenr, u64 parent,
  976. u64 root_objectid,
  977. u64 owner, u64 offset)
  978. {
  979. struct btrfs_key key;
  980. struct btrfs_extent_data_ref *ref;
  981. struct extent_buffer *leaf;
  982. u32 nritems;
  983. int ret;
  984. int recow;
  985. int err = -ENOENT;
  986. key.objectid = bytenr;
  987. if (parent) {
  988. key.type = BTRFS_SHARED_DATA_REF_KEY;
  989. key.offset = parent;
  990. } else {
  991. key.type = BTRFS_EXTENT_DATA_REF_KEY;
  992. key.offset = hash_extent_data_ref(root_objectid,
  993. owner, offset);
  994. }
  995. again:
  996. recow = 0;
  997. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  998. if (ret < 0) {
  999. err = ret;
  1000. goto fail;
  1001. }
  1002. if (parent) {
  1003. if (!ret)
  1004. return 0;
  1005. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1006. key.type = BTRFS_EXTENT_REF_V0_KEY;
  1007. btrfs_release_path(path);
  1008. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1009. if (ret < 0) {
  1010. err = ret;
  1011. goto fail;
  1012. }
  1013. if (!ret)
  1014. return 0;
  1015. #endif
  1016. goto fail;
  1017. }
  1018. leaf = path->nodes[0];
  1019. nritems = btrfs_header_nritems(leaf);
  1020. while (1) {
  1021. if (path->slots[0] >= nritems) {
  1022. ret = btrfs_next_leaf(root, path);
  1023. if (ret < 0)
  1024. err = ret;
  1025. if (ret)
  1026. goto fail;
  1027. leaf = path->nodes[0];
  1028. nritems = btrfs_header_nritems(leaf);
  1029. recow = 1;
  1030. }
  1031. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1032. if (key.objectid != bytenr ||
  1033. key.type != BTRFS_EXTENT_DATA_REF_KEY)
  1034. goto fail;
  1035. ref = btrfs_item_ptr(leaf, path->slots[0],
  1036. struct btrfs_extent_data_ref);
  1037. if (match_extent_data_ref(leaf, ref, root_objectid,
  1038. owner, offset)) {
  1039. if (recow) {
  1040. btrfs_release_path(path);
  1041. goto again;
  1042. }
  1043. err = 0;
  1044. break;
  1045. }
  1046. path->slots[0]++;
  1047. }
  1048. fail:
  1049. return err;
  1050. }
  1051. static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
  1052. struct btrfs_root *root,
  1053. struct btrfs_path *path,
  1054. u64 bytenr, u64 parent,
  1055. u64 root_objectid, u64 owner,
  1056. u64 offset, int refs_to_add)
  1057. {
  1058. struct btrfs_key key;
  1059. struct extent_buffer *leaf;
  1060. u32 size;
  1061. u32 num_refs;
  1062. int ret;
  1063. key.objectid = bytenr;
  1064. if (parent) {
  1065. key.type = BTRFS_SHARED_DATA_REF_KEY;
  1066. key.offset = parent;
  1067. size = sizeof(struct btrfs_shared_data_ref);
  1068. } else {
  1069. key.type = BTRFS_EXTENT_DATA_REF_KEY;
  1070. key.offset = hash_extent_data_ref(root_objectid,
  1071. owner, offset);
  1072. size = sizeof(struct btrfs_extent_data_ref);
  1073. }
  1074. ret = btrfs_insert_empty_item(trans, root, path, &key, size);
  1075. if (ret && ret != -EEXIST)
  1076. goto fail;
  1077. leaf = path->nodes[0];
  1078. if (parent) {
  1079. struct btrfs_shared_data_ref *ref;
  1080. ref = btrfs_item_ptr(leaf, path->slots[0],
  1081. struct btrfs_shared_data_ref);
  1082. if (ret == 0) {
  1083. btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
  1084. } else {
  1085. num_refs = btrfs_shared_data_ref_count(leaf, ref);
  1086. num_refs += refs_to_add;
  1087. btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
  1088. }
  1089. } else {
  1090. struct btrfs_extent_data_ref *ref;
  1091. while (ret == -EEXIST) {
  1092. ref = btrfs_item_ptr(leaf, path->slots[0],
  1093. struct btrfs_extent_data_ref);
  1094. if (match_extent_data_ref(leaf, ref, root_objectid,
  1095. owner, offset))
  1096. break;
  1097. btrfs_release_path(path);
  1098. key.offset++;
  1099. ret = btrfs_insert_empty_item(trans, root, path, &key,
  1100. size);
  1101. if (ret && ret != -EEXIST)
  1102. goto fail;
  1103. leaf = path->nodes[0];
  1104. }
  1105. ref = btrfs_item_ptr(leaf, path->slots[0],
  1106. struct btrfs_extent_data_ref);
  1107. if (ret == 0) {
  1108. btrfs_set_extent_data_ref_root(leaf, ref,
  1109. root_objectid);
  1110. btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
  1111. btrfs_set_extent_data_ref_offset(leaf, ref, offset);
  1112. btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
  1113. } else {
  1114. num_refs = btrfs_extent_data_ref_count(leaf, ref);
  1115. num_refs += refs_to_add;
  1116. btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
  1117. }
  1118. }
  1119. btrfs_mark_buffer_dirty(leaf);
  1120. ret = 0;
  1121. fail:
  1122. btrfs_release_path(path);
  1123. return ret;
  1124. }
  1125. static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
  1126. struct btrfs_root *root,
  1127. struct btrfs_path *path,
  1128. int refs_to_drop, int *last_ref)
  1129. {
  1130. struct btrfs_key key;
  1131. struct btrfs_extent_data_ref *ref1 = NULL;
  1132. struct btrfs_shared_data_ref *ref2 = NULL;
  1133. struct extent_buffer *leaf;
  1134. u32 num_refs = 0;
  1135. int ret = 0;
  1136. leaf = path->nodes[0];
  1137. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1138. if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
  1139. ref1 = btrfs_item_ptr(leaf, path->slots[0],
  1140. struct btrfs_extent_data_ref);
  1141. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  1142. } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
  1143. ref2 = btrfs_item_ptr(leaf, path->slots[0],
  1144. struct btrfs_shared_data_ref);
  1145. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  1146. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1147. } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
  1148. struct btrfs_extent_ref_v0 *ref0;
  1149. ref0 = btrfs_item_ptr(leaf, path->slots[0],
  1150. struct btrfs_extent_ref_v0);
  1151. num_refs = btrfs_ref_count_v0(leaf, ref0);
  1152. #endif
  1153. } else {
  1154. BUG();
  1155. }
  1156. BUG_ON(num_refs < refs_to_drop);
  1157. num_refs -= refs_to_drop;
  1158. if (num_refs == 0) {
  1159. ret = btrfs_del_item(trans, root, path);
  1160. *last_ref = 1;
  1161. } else {
  1162. if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
  1163. btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
  1164. else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
  1165. btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
  1166. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1167. else {
  1168. struct btrfs_extent_ref_v0 *ref0;
  1169. ref0 = btrfs_item_ptr(leaf, path->slots[0],
  1170. struct btrfs_extent_ref_v0);
  1171. btrfs_set_ref_count_v0(leaf, ref0, num_refs);
  1172. }
  1173. #endif
  1174. btrfs_mark_buffer_dirty(leaf);
  1175. }
  1176. return ret;
  1177. }
  1178. static noinline u32 extent_data_ref_count(struct btrfs_root *root,
  1179. struct btrfs_path *path,
  1180. struct btrfs_extent_inline_ref *iref)
  1181. {
  1182. struct btrfs_key key;
  1183. struct extent_buffer *leaf;
  1184. struct btrfs_extent_data_ref *ref1;
  1185. struct btrfs_shared_data_ref *ref2;
  1186. u32 num_refs = 0;
  1187. leaf = path->nodes[0];
  1188. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1189. if (iref) {
  1190. if (btrfs_extent_inline_ref_type(leaf, iref) ==
  1191. BTRFS_EXTENT_DATA_REF_KEY) {
  1192. ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
  1193. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  1194. } else {
  1195. ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
  1196. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  1197. }
  1198. } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
  1199. ref1 = btrfs_item_ptr(leaf, path->slots[0],
  1200. struct btrfs_extent_data_ref);
  1201. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  1202. } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
  1203. ref2 = btrfs_item_ptr(leaf, path->slots[0],
  1204. struct btrfs_shared_data_ref);
  1205. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  1206. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1207. } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
  1208. struct btrfs_extent_ref_v0 *ref0;
  1209. ref0 = btrfs_item_ptr(leaf, path->slots[0],
  1210. struct btrfs_extent_ref_v0);
  1211. num_refs = btrfs_ref_count_v0(leaf, ref0);
  1212. #endif
  1213. } else {
  1214. WARN_ON(1);
  1215. }
  1216. return num_refs;
  1217. }
  1218. static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
  1219. struct btrfs_root *root,
  1220. struct btrfs_path *path,
  1221. u64 bytenr, u64 parent,
  1222. u64 root_objectid)
  1223. {
  1224. struct btrfs_key key;
  1225. int ret;
  1226. key.objectid = bytenr;
  1227. if (parent) {
  1228. key.type = BTRFS_SHARED_BLOCK_REF_KEY;
  1229. key.offset = parent;
  1230. } else {
  1231. key.type = BTRFS_TREE_BLOCK_REF_KEY;
  1232. key.offset = root_objectid;
  1233. }
  1234. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1235. if (ret > 0)
  1236. ret = -ENOENT;
  1237. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1238. if (ret == -ENOENT && parent) {
  1239. btrfs_release_path(path);
  1240. key.type = BTRFS_EXTENT_REF_V0_KEY;
  1241. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1242. if (ret > 0)
  1243. ret = -ENOENT;
  1244. }
  1245. #endif
  1246. return ret;
  1247. }
  1248. static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
  1249. struct btrfs_root *root,
  1250. struct btrfs_path *path,
  1251. u64 bytenr, u64 parent,
  1252. u64 root_objectid)
  1253. {
  1254. struct btrfs_key key;
  1255. int ret;
  1256. key.objectid = bytenr;
  1257. if (parent) {
  1258. key.type = BTRFS_SHARED_BLOCK_REF_KEY;
  1259. key.offset = parent;
  1260. } else {
  1261. key.type = BTRFS_TREE_BLOCK_REF_KEY;
  1262. key.offset = root_objectid;
  1263. }
  1264. ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
  1265. btrfs_release_path(path);
  1266. return ret;
  1267. }
  1268. static inline int extent_ref_type(u64 parent, u64 owner)
  1269. {
  1270. int type;
  1271. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1272. if (parent > 0)
  1273. type = BTRFS_SHARED_BLOCK_REF_KEY;
  1274. else
  1275. type = BTRFS_TREE_BLOCK_REF_KEY;
  1276. } else {
  1277. if (parent > 0)
  1278. type = BTRFS_SHARED_DATA_REF_KEY;
  1279. else
  1280. type = BTRFS_EXTENT_DATA_REF_KEY;
  1281. }
  1282. return type;
  1283. }
  1284. static int find_next_key(struct btrfs_path *path, int level,
  1285. struct btrfs_key *key)
  1286. {
  1287. for (; level < BTRFS_MAX_LEVEL; level++) {
  1288. if (!path->nodes[level])
  1289. break;
  1290. if (path->slots[level] + 1 >=
  1291. btrfs_header_nritems(path->nodes[level]))
  1292. continue;
  1293. if (level == 0)
  1294. btrfs_item_key_to_cpu(path->nodes[level], key,
  1295. path->slots[level] + 1);
  1296. else
  1297. btrfs_node_key_to_cpu(path->nodes[level], key,
  1298. path->slots[level] + 1);
  1299. return 0;
  1300. }
  1301. return 1;
  1302. }
  1303. /*
  1304. * look for inline back ref. if back ref is found, *ref_ret is set
  1305. * to the address of inline back ref, and 0 is returned.
  1306. *
  1307. * if back ref isn't found, *ref_ret is set to the address where it
  1308. * should be inserted, and -ENOENT is returned.
  1309. *
  1310. * if insert is true and there are too many inline back refs, the path
  1311. * points to the extent item, and -EAGAIN is returned.
  1312. *
  1313. * NOTE: inline back refs are ordered in the same way that back ref
  1314. * items in the tree are ordered.
  1315. */
  1316. static noinline_for_stack
  1317. int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
  1318. struct btrfs_root *root,
  1319. struct btrfs_path *path,
  1320. struct btrfs_extent_inline_ref **ref_ret,
  1321. u64 bytenr, u64 num_bytes,
  1322. u64 parent, u64 root_objectid,
  1323. u64 owner, u64 offset, int insert)
  1324. {
  1325. struct btrfs_key key;
  1326. struct extent_buffer *leaf;
  1327. struct btrfs_extent_item *ei;
  1328. struct btrfs_extent_inline_ref *iref;
  1329. u64 flags;
  1330. u64 item_size;
  1331. unsigned long ptr;
  1332. unsigned long end;
  1333. int extra_size;
  1334. int type;
  1335. int want;
  1336. int ret;
  1337. int err = 0;
  1338. bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
  1339. SKINNY_METADATA);
  1340. key.objectid = bytenr;
  1341. key.type = BTRFS_EXTENT_ITEM_KEY;
  1342. key.offset = num_bytes;
  1343. want = extent_ref_type(parent, owner);
  1344. if (insert) {
  1345. extra_size = btrfs_extent_inline_ref_size(want);
  1346. path->keep_locks = 1;
  1347. } else
  1348. extra_size = -1;
  1349. /*
  1350. * Owner is our parent level, so we can just add one to get the level
  1351. * for the block we are interested in.
  1352. */
  1353. if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
  1354. key.type = BTRFS_METADATA_ITEM_KEY;
  1355. key.offset = owner;
  1356. }
  1357. again:
  1358. ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
  1359. if (ret < 0) {
  1360. err = ret;
  1361. goto out;
  1362. }
  1363. /*
  1364. * We may be a newly converted file system which still has the old fat
  1365. * extent entries for metadata, so try and see if we have one of those.
  1366. */
  1367. if (ret > 0 && skinny_metadata) {
  1368. skinny_metadata = false;
  1369. if (path->slots[0]) {
  1370. path->slots[0]--;
  1371. btrfs_item_key_to_cpu(path->nodes[0], &key,
  1372. path->slots[0]);
  1373. if (key.objectid == bytenr &&
  1374. key.type == BTRFS_EXTENT_ITEM_KEY &&
  1375. key.offset == num_bytes)
  1376. ret = 0;
  1377. }
  1378. if (ret) {
  1379. key.objectid = bytenr;
  1380. key.type = BTRFS_EXTENT_ITEM_KEY;
  1381. key.offset = num_bytes;
  1382. btrfs_release_path(path);
  1383. goto again;
  1384. }
  1385. }
  1386. if (ret && !insert) {
  1387. err = -ENOENT;
  1388. goto out;
  1389. } else if (WARN_ON(ret)) {
  1390. err = -EIO;
  1391. goto out;
  1392. }
  1393. leaf = path->nodes[0];
  1394. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1395. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1396. if (item_size < sizeof(*ei)) {
  1397. if (!insert) {
  1398. err = -ENOENT;
  1399. goto out;
  1400. }
  1401. ret = convert_extent_item_v0(trans, root, path, owner,
  1402. extra_size);
  1403. if (ret < 0) {
  1404. err = ret;
  1405. goto out;
  1406. }
  1407. leaf = path->nodes[0];
  1408. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1409. }
  1410. #endif
  1411. BUG_ON(item_size < sizeof(*ei));
  1412. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1413. flags = btrfs_extent_flags(leaf, ei);
  1414. ptr = (unsigned long)(ei + 1);
  1415. end = (unsigned long)ei + item_size;
  1416. if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
  1417. ptr += sizeof(struct btrfs_tree_block_info);
  1418. BUG_ON(ptr > end);
  1419. }
  1420. err = -ENOENT;
  1421. while (1) {
  1422. if (ptr >= end) {
  1423. WARN_ON(ptr > end);
  1424. break;
  1425. }
  1426. iref = (struct btrfs_extent_inline_ref *)ptr;
  1427. type = btrfs_extent_inline_ref_type(leaf, iref);
  1428. if (want < type)
  1429. break;
  1430. if (want > type) {
  1431. ptr += btrfs_extent_inline_ref_size(type);
  1432. continue;
  1433. }
  1434. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1435. struct btrfs_extent_data_ref *dref;
  1436. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  1437. if (match_extent_data_ref(leaf, dref, root_objectid,
  1438. owner, offset)) {
  1439. err = 0;
  1440. break;
  1441. }
  1442. if (hash_extent_data_ref_item(leaf, dref) <
  1443. hash_extent_data_ref(root_objectid, owner, offset))
  1444. break;
  1445. } else {
  1446. u64 ref_offset;
  1447. ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
  1448. if (parent > 0) {
  1449. if (parent == ref_offset) {
  1450. err = 0;
  1451. break;
  1452. }
  1453. if (ref_offset < parent)
  1454. break;
  1455. } else {
  1456. if (root_objectid == ref_offset) {
  1457. err = 0;
  1458. break;
  1459. }
  1460. if (ref_offset < root_objectid)
  1461. break;
  1462. }
  1463. }
  1464. ptr += btrfs_extent_inline_ref_size(type);
  1465. }
  1466. if (err == -ENOENT && insert) {
  1467. if (item_size + extra_size >=
  1468. BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
  1469. err = -EAGAIN;
  1470. goto out;
  1471. }
  1472. /*
  1473. * To add new inline back ref, we have to make sure
  1474. * there is no corresponding back ref item.
  1475. * For simplicity, we just do not add new inline back
  1476. * ref if there is any kind of item for this block
  1477. */
  1478. if (find_next_key(path, 0, &key) == 0 &&
  1479. key.objectid == bytenr &&
  1480. key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
  1481. err = -EAGAIN;
  1482. goto out;
  1483. }
  1484. }
  1485. *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
  1486. out:
  1487. if (insert) {
  1488. path->keep_locks = 0;
  1489. btrfs_unlock_up_safe(path, 1);
  1490. }
  1491. return err;
  1492. }
  1493. /*
  1494. * helper to add new inline back ref
  1495. */
  1496. static noinline_for_stack
  1497. void setup_inline_extent_backref(struct btrfs_root *root,
  1498. struct btrfs_path *path,
  1499. struct btrfs_extent_inline_ref *iref,
  1500. u64 parent, u64 root_objectid,
  1501. u64 owner, u64 offset, int refs_to_add,
  1502. struct btrfs_delayed_extent_op *extent_op)
  1503. {
  1504. struct extent_buffer *leaf;
  1505. struct btrfs_extent_item *ei;
  1506. unsigned long ptr;
  1507. unsigned long end;
  1508. unsigned long item_offset;
  1509. u64 refs;
  1510. int size;
  1511. int type;
  1512. leaf = path->nodes[0];
  1513. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1514. item_offset = (unsigned long)iref - (unsigned long)ei;
  1515. type = extent_ref_type(parent, owner);
  1516. size = btrfs_extent_inline_ref_size(type);
  1517. btrfs_extend_item(root, path, size);
  1518. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1519. refs = btrfs_extent_refs(leaf, ei);
  1520. refs += refs_to_add;
  1521. btrfs_set_extent_refs(leaf, ei, refs);
  1522. if (extent_op)
  1523. __run_delayed_extent_op(extent_op, leaf, ei);
  1524. ptr = (unsigned long)ei + item_offset;
  1525. end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
  1526. if (ptr < end - size)
  1527. memmove_extent_buffer(leaf, ptr + size, ptr,
  1528. end - size - ptr);
  1529. iref = (struct btrfs_extent_inline_ref *)ptr;
  1530. btrfs_set_extent_inline_ref_type(leaf, iref, type);
  1531. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1532. struct btrfs_extent_data_ref *dref;
  1533. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  1534. btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
  1535. btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
  1536. btrfs_set_extent_data_ref_offset(leaf, dref, offset);
  1537. btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
  1538. } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
  1539. struct btrfs_shared_data_ref *sref;
  1540. sref = (struct btrfs_shared_data_ref *)(iref + 1);
  1541. btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
  1542. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  1543. } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
  1544. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  1545. } else {
  1546. btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
  1547. }
  1548. btrfs_mark_buffer_dirty(leaf);
  1549. }
  1550. static int lookup_extent_backref(struct btrfs_trans_handle *trans,
  1551. struct btrfs_root *root,
  1552. struct btrfs_path *path,
  1553. struct btrfs_extent_inline_ref **ref_ret,
  1554. u64 bytenr, u64 num_bytes, u64 parent,
  1555. u64 root_objectid, u64 owner, u64 offset)
  1556. {
  1557. int ret;
  1558. ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
  1559. bytenr, num_bytes, parent,
  1560. root_objectid, owner, offset, 0);
  1561. if (ret != -ENOENT)
  1562. return ret;
  1563. btrfs_release_path(path);
  1564. *ref_ret = NULL;
  1565. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1566. ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
  1567. root_objectid);
  1568. } else {
  1569. ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
  1570. root_objectid, owner, offset);
  1571. }
  1572. return ret;
  1573. }
  1574. /*
  1575. * helper to update/remove inline back ref
  1576. */
  1577. static noinline_for_stack
  1578. void update_inline_extent_backref(struct btrfs_root *root,
  1579. struct btrfs_path *path,
  1580. struct btrfs_extent_inline_ref *iref,
  1581. int refs_to_mod,
  1582. struct btrfs_delayed_extent_op *extent_op,
  1583. int *last_ref)
  1584. {
  1585. struct extent_buffer *leaf;
  1586. struct btrfs_extent_item *ei;
  1587. struct btrfs_extent_data_ref *dref = NULL;
  1588. struct btrfs_shared_data_ref *sref = NULL;
  1589. unsigned long ptr;
  1590. unsigned long end;
  1591. u32 item_size;
  1592. int size;
  1593. int type;
  1594. u64 refs;
  1595. leaf = path->nodes[0];
  1596. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1597. refs = btrfs_extent_refs(leaf, ei);
  1598. WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
  1599. refs += refs_to_mod;
  1600. btrfs_set_extent_refs(leaf, ei, refs);
  1601. if (extent_op)
  1602. __run_delayed_extent_op(extent_op, leaf, ei);
  1603. type = btrfs_extent_inline_ref_type(leaf, iref);
  1604. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1605. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  1606. refs = btrfs_extent_data_ref_count(leaf, dref);
  1607. } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
  1608. sref = (struct btrfs_shared_data_ref *)(iref + 1);
  1609. refs = btrfs_shared_data_ref_count(leaf, sref);
  1610. } else {
  1611. refs = 1;
  1612. BUG_ON(refs_to_mod != -1);
  1613. }
  1614. BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
  1615. refs += refs_to_mod;
  1616. if (refs > 0) {
  1617. if (type == BTRFS_EXTENT_DATA_REF_KEY)
  1618. btrfs_set_extent_data_ref_count(leaf, dref, refs);
  1619. else
  1620. btrfs_set_shared_data_ref_count(leaf, sref, refs);
  1621. } else {
  1622. *last_ref = 1;
  1623. size = btrfs_extent_inline_ref_size(type);
  1624. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1625. ptr = (unsigned long)iref;
  1626. end = (unsigned long)ei + item_size;
  1627. if (ptr + size < end)
  1628. memmove_extent_buffer(leaf, ptr, ptr + size,
  1629. end - ptr - size);
  1630. item_size -= size;
  1631. btrfs_truncate_item(root, path, item_size, 1);
  1632. }
  1633. btrfs_mark_buffer_dirty(leaf);
  1634. }
  1635. static noinline_for_stack
  1636. int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
  1637. struct btrfs_root *root,
  1638. struct btrfs_path *path,
  1639. u64 bytenr, u64 num_bytes, u64 parent,
  1640. u64 root_objectid, u64 owner,
  1641. u64 offset, int refs_to_add,
  1642. struct btrfs_delayed_extent_op *extent_op)
  1643. {
  1644. struct btrfs_extent_inline_ref *iref;
  1645. int ret;
  1646. ret = lookup_inline_extent_backref(trans, root, path, &iref,
  1647. bytenr, num_bytes, parent,
  1648. root_objectid, owner, offset, 1);
  1649. if (ret == 0) {
  1650. BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
  1651. update_inline_extent_backref(root, path, iref,
  1652. refs_to_add, extent_op, NULL);
  1653. } else if (ret == -ENOENT) {
  1654. setup_inline_extent_backref(root, path, iref, parent,
  1655. root_objectid, owner, offset,
  1656. refs_to_add, extent_op);
  1657. ret = 0;
  1658. }
  1659. return ret;
  1660. }
  1661. static int insert_extent_backref(struct btrfs_trans_handle *trans,
  1662. struct btrfs_root *root,
  1663. struct btrfs_path *path,
  1664. u64 bytenr, u64 parent, u64 root_objectid,
  1665. u64 owner, u64 offset, int refs_to_add)
  1666. {
  1667. int ret;
  1668. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1669. BUG_ON(refs_to_add != 1);
  1670. ret = insert_tree_block_ref(trans, root, path, bytenr,
  1671. parent, root_objectid);
  1672. } else {
  1673. ret = insert_extent_data_ref(trans, root, path, bytenr,
  1674. parent, root_objectid,
  1675. owner, offset, refs_to_add);
  1676. }
  1677. return ret;
  1678. }
  1679. static int remove_extent_backref(struct btrfs_trans_handle *trans,
  1680. struct btrfs_root *root,
  1681. struct btrfs_path *path,
  1682. struct btrfs_extent_inline_ref *iref,
  1683. int refs_to_drop, int is_data, int *last_ref)
  1684. {
  1685. int ret = 0;
  1686. BUG_ON(!is_data && refs_to_drop != 1);
  1687. if (iref) {
  1688. update_inline_extent_backref(root, path, iref,
  1689. -refs_to_drop, NULL, last_ref);
  1690. } else if (is_data) {
  1691. ret = remove_extent_data_ref(trans, root, path, refs_to_drop,
  1692. last_ref);
  1693. } else {
  1694. *last_ref = 1;
  1695. ret = btrfs_del_item(trans, root, path);
  1696. }
  1697. return ret;
  1698. }
  1699. static int btrfs_issue_discard(struct block_device *bdev,
  1700. u64 start, u64 len)
  1701. {
  1702. return blkdev_issue_discard(bdev, start >> 9, len >> 9, GFP_NOFS, 0);
  1703. }
  1704. int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
  1705. u64 num_bytes, u64 *actual_bytes)
  1706. {
  1707. int ret;
  1708. u64 discarded_bytes = 0;
  1709. struct btrfs_bio *bbio = NULL;
  1710. /* Tell the block device(s) that the sectors can be discarded */
  1711. ret = btrfs_map_block(root->fs_info, REQ_DISCARD,
  1712. bytenr, &num_bytes, &bbio, 0);
  1713. /* Error condition is -ENOMEM */
  1714. if (!ret) {
  1715. struct btrfs_bio_stripe *stripe = bbio->stripes;
  1716. int i;
  1717. for (i = 0; i < bbio->num_stripes; i++, stripe++) {
  1718. if (!stripe->dev->can_discard)
  1719. continue;
  1720. ret = btrfs_issue_discard(stripe->dev->bdev,
  1721. stripe->physical,
  1722. stripe->length);
  1723. if (!ret)
  1724. discarded_bytes += stripe->length;
  1725. else if (ret != -EOPNOTSUPP)
  1726. break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
  1727. /*
  1728. * Just in case we get back EOPNOTSUPP for some reason,
  1729. * just ignore the return value so we don't screw up
  1730. * people calling discard_extent.
  1731. */
  1732. ret = 0;
  1733. }
  1734. btrfs_put_bbio(bbio);
  1735. }
  1736. if (actual_bytes)
  1737. *actual_bytes = discarded_bytes;
  1738. if (ret == -EOPNOTSUPP)
  1739. ret = 0;
  1740. return ret;
  1741. }
  1742. /* Can return -ENOMEM */
  1743. int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
  1744. struct btrfs_root *root,
  1745. u64 bytenr, u64 num_bytes, u64 parent,
  1746. u64 root_objectid, u64 owner, u64 offset,
  1747. int no_quota)
  1748. {
  1749. int ret;
  1750. struct btrfs_fs_info *fs_info = root->fs_info;
  1751. BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
  1752. root_objectid == BTRFS_TREE_LOG_OBJECTID);
  1753. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1754. ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
  1755. num_bytes,
  1756. parent, root_objectid, (int)owner,
  1757. BTRFS_ADD_DELAYED_REF, NULL, no_quota);
  1758. } else {
  1759. ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
  1760. num_bytes,
  1761. parent, root_objectid, owner, offset,
  1762. BTRFS_ADD_DELAYED_REF, NULL, no_quota);
  1763. }
  1764. return ret;
  1765. }
  1766. static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
  1767. struct btrfs_root *root,
  1768. u64 bytenr, u64 num_bytes,
  1769. u64 parent, u64 root_objectid,
  1770. u64 owner, u64 offset, int refs_to_add,
  1771. int no_quota,
  1772. struct btrfs_delayed_extent_op *extent_op)
  1773. {
  1774. struct btrfs_fs_info *fs_info = root->fs_info;
  1775. struct btrfs_path *path;
  1776. struct extent_buffer *leaf;
  1777. struct btrfs_extent_item *item;
  1778. struct btrfs_key key;
  1779. u64 refs;
  1780. int ret;
  1781. enum btrfs_qgroup_operation_type type = BTRFS_QGROUP_OPER_ADD_EXCL;
  1782. path = btrfs_alloc_path();
  1783. if (!path)
  1784. return -ENOMEM;
  1785. if (!is_fstree(root_objectid) || !root->fs_info->quota_enabled)
  1786. no_quota = 1;
  1787. path->reada = 1;
  1788. path->leave_spinning = 1;
  1789. /* this will setup the path even if it fails to insert the back ref */
  1790. ret = insert_inline_extent_backref(trans, fs_info->extent_root, path,
  1791. bytenr, num_bytes, parent,
  1792. root_objectid, owner, offset,
  1793. refs_to_add, extent_op);
  1794. if ((ret < 0 && ret != -EAGAIN) || (!ret && no_quota))
  1795. goto out;
  1796. /*
  1797. * Ok we were able to insert an inline extent and it appears to be a new
  1798. * reference, deal with the qgroup accounting.
  1799. */
  1800. if (!ret && !no_quota) {
  1801. ASSERT(root->fs_info->quota_enabled);
  1802. leaf = path->nodes[0];
  1803. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1804. item = btrfs_item_ptr(leaf, path->slots[0],
  1805. struct btrfs_extent_item);
  1806. if (btrfs_extent_refs(leaf, item) > (u64)refs_to_add)
  1807. type = BTRFS_QGROUP_OPER_ADD_SHARED;
  1808. btrfs_release_path(path);
  1809. ret = btrfs_qgroup_record_ref(trans, fs_info, root_objectid,
  1810. bytenr, num_bytes, type, 0);
  1811. goto out;
  1812. }
  1813. /*
  1814. * Ok we had -EAGAIN which means we didn't have space to insert and
  1815. * inline extent ref, so just update the reference count and add a
  1816. * normal backref.
  1817. */
  1818. leaf = path->nodes[0];
  1819. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1820. item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1821. refs = btrfs_extent_refs(leaf, item);
  1822. if (refs)
  1823. type = BTRFS_QGROUP_OPER_ADD_SHARED;
  1824. btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
  1825. if (extent_op)
  1826. __run_delayed_extent_op(extent_op, leaf, item);
  1827. btrfs_mark_buffer_dirty(leaf);
  1828. btrfs_release_path(path);
  1829. if (!no_quota) {
  1830. ret = btrfs_qgroup_record_ref(trans, fs_info, root_objectid,
  1831. bytenr, num_bytes, type, 0);
  1832. if (ret)
  1833. goto out;
  1834. }
  1835. path->reada = 1;
  1836. path->leave_spinning = 1;
  1837. /* now insert the actual backref */
  1838. ret = insert_extent_backref(trans, root->fs_info->extent_root,
  1839. path, bytenr, parent, root_objectid,
  1840. owner, offset, refs_to_add);
  1841. if (ret)
  1842. btrfs_abort_transaction(trans, root, ret);
  1843. out:
  1844. btrfs_free_path(path);
  1845. return ret;
  1846. }
  1847. static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
  1848. struct btrfs_root *root,
  1849. struct btrfs_delayed_ref_node *node,
  1850. struct btrfs_delayed_extent_op *extent_op,
  1851. int insert_reserved)
  1852. {
  1853. int ret = 0;
  1854. struct btrfs_delayed_data_ref *ref;
  1855. struct btrfs_key ins;
  1856. u64 parent = 0;
  1857. u64 ref_root = 0;
  1858. u64 flags = 0;
  1859. ins.objectid = node->bytenr;
  1860. ins.offset = node->num_bytes;
  1861. ins.type = BTRFS_EXTENT_ITEM_KEY;
  1862. ref = btrfs_delayed_node_to_data_ref(node);
  1863. trace_run_delayed_data_ref(node, ref, node->action);
  1864. if (node->type == BTRFS_SHARED_DATA_REF_KEY)
  1865. parent = ref->parent;
  1866. ref_root = ref->root;
  1867. if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
  1868. if (extent_op)
  1869. flags |= extent_op->flags_to_set;
  1870. ret = alloc_reserved_file_extent(trans, root,
  1871. parent, ref_root, flags,
  1872. ref->objectid, ref->offset,
  1873. &ins, node->ref_mod);
  1874. } else if (node->action == BTRFS_ADD_DELAYED_REF) {
  1875. ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
  1876. node->num_bytes, parent,
  1877. ref_root, ref->objectid,
  1878. ref->offset, node->ref_mod,
  1879. node->no_quota, extent_op);
  1880. } else if (node->action == BTRFS_DROP_DELAYED_REF) {
  1881. ret = __btrfs_free_extent(trans, root, node->bytenr,
  1882. node->num_bytes, parent,
  1883. ref_root, ref->objectid,
  1884. ref->offset, node->ref_mod,
  1885. extent_op, node->no_quota);
  1886. } else {
  1887. BUG();
  1888. }
  1889. return ret;
  1890. }
  1891. static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
  1892. struct extent_buffer *leaf,
  1893. struct btrfs_extent_item *ei)
  1894. {
  1895. u64 flags = btrfs_extent_flags(leaf, ei);
  1896. if (extent_op->update_flags) {
  1897. flags |= extent_op->flags_to_set;
  1898. btrfs_set_extent_flags(leaf, ei, flags);
  1899. }
  1900. if (extent_op->update_key) {
  1901. struct btrfs_tree_block_info *bi;
  1902. BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
  1903. bi = (struct btrfs_tree_block_info *)(ei + 1);
  1904. btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
  1905. }
  1906. }
  1907. static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
  1908. struct btrfs_root *root,
  1909. struct btrfs_delayed_ref_node *node,
  1910. struct btrfs_delayed_extent_op *extent_op)
  1911. {
  1912. struct btrfs_key key;
  1913. struct btrfs_path *path;
  1914. struct btrfs_extent_item *ei;
  1915. struct extent_buffer *leaf;
  1916. u32 item_size;
  1917. int ret;
  1918. int err = 0;
  1919. int metadata = !extent_op->is_data;
  1920. if (trans->aborted)
  1921. return 0;
  1922. if (metadata && !btrfs_fs_incompat(root->fs_info, SKINNY_METADATA))
  1923. metadata = 0;
  1924. path = btrfs_alloc_path();
  1925. if (!path)
  1926. return -ENOMEM;
  1927. key.objectid = node->bytenr;
  1928. if (metadata) {
  1929. key.type = BTRFS_METADATA_ITEM_KEY;
  1930. key.offset = extent_op->level;
  1931. } else {
  1932. key.type = BTRFS_EXTENT_ITEM_KEY;
  1933. key.offset = node->num_bytes;
  1934. }
  1935. again:
  1936. path->reada = 1;
  1937. path->leave_spinning = 1;
  1938. ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
  1939. path, 0, 1);
  1940. if (ret < 0) {
  1941. err = ret;
  1942. goto out;
  1943. }
  1944. if (ret > 0) {
  1945. if (metadata) {
  1946. if (path->slots[0] > 0) {
  1947. path->slots[0]--;
  1948. btrfs_item_key_to_cpu(path->nodes[0], &key,
  1949. path->slots[0]);
  1950. if (key.objectid == node->bytenr &&
  1951. key.type == BTRFS_EXTENT_ITEM_KEY &&
  1952. key.offset == node->num_bytes)
  1953. ret = 0;
  1954. }
  1955. if (ret > 0) {
  1956. btrfs_release_path(path);
  1957. metadata = 0;
  1958. key.objectid = node->bytenr;
  1959. key.offset = node->num_bytes;
  1960. key.type = BTRFS_EXTENT_ITEM_KEY;
  1961. goto again;
  1962. }
  1963. } else {
  1964. err = -EIO;
  1965. goto out;
  1966. }
  1967. }
  1968. leaf = path->nodes[0];
  1969. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1970. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1971. if (item_size < sizeof(*ei)) {
  1972. ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
  1973. path, (u64)-1, 0);
  1974. if (ret < 0) {
  1975. err = ret;
  1976. goto out;
  1977. }
  1978. leaf = path->nodes[0];
  1979. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1980. }
  1981. #endif
  1982. BUG_ON(item_size < sizeof(*ei));
  1983. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1984. __run_delayed_extent_op(extent_op, leaf, ei);
  1985. btrfs_mark_buffer_dirty(leaf);
  1986. out:
  1987. btrfs_free_path(path);
  1988. return err;
  1989. }
  1990. static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
  1991. struct btrfs_root *root,
  1992. struct btrfs_delayed_ref_node *node,
  1993. struct btrfs_delayed_extent_op *extent_op,
  1994. int insert_reserved)
  1995. {
  1996. int ret = 0;
  1997. struct btrfs_delayed_tree_ref *ref;
  1998. struct btrfs_key ins;
  1999. u64 parent = 0;
  2000. u64 ref_root = 0;
  2001. bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
  2002. SKINNY_METADATA);
  2003. ref = btrfs_delayed_node_to_tree_ref(node);
  2004. trace_run_delayed_tree_ref(node, ref, node->action);
  2005. if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
  2006. parent = ref->parent;
  2007. ref_root = ref->root;
  2008. ins.objectid = node->bytenr;
  2009. if (skinny_metadata) {
  2010. ins.offset = ref->level;
  2011. ins.type = BTRFS_METADATA_ITEM_KEY;
  2012. } else {
  2013. ins.offset = node->num_bytes;
  2014. ins.type = BTRFS_EXTENT_ITEM_KEY;
  2015. }
  2016. BUG_ON(node->ref_mod != 1);
  2017. if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
  2018. BUG_ON(!extent_op || !extent_op->update_flags);
  2019. ret = alloc_reserved_tree_block(trans, root,
  2020. parent, ref_root,
  2021. extent_op->flags_to_set,
  2022. &extent_op->key,
  2023. ref->level, &ins,
  2024. node->no_quota);
  2025. } else if (node->action == BTRFS_ADD_DELAYED_REF) {
  2026. ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
  2027. node->num_bytes, parent, ref_root,
  2028. ref->level, 0, 1, node->no_quota,
  2029. extent_op);
  2030. } else if (node->action == BTRFS_DROP_DELAYED_REF) {
  2031. ret = __btrfs_free_extent(trans, root, node->bytenr,
  2032. node->num_bytes, parent, ref_root,
  2033. ref->level, 0, 1, extent_op,
  2034. node->no_quota);
  2035. } else {
  2036. BUG();
  2037. }
  2038. return ret;
  2039. }
  2040. /* helper function to actually process a single delayed ref entry */
  2041. static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
  2042. struct btrfs_root *root,
  2043. struct btrfs_delayed_ref_node *node,
  2044. struct btrfs_delayed_extent_op *extent_op,
  2045. int insert_reserved)
  2046. {
  2047. int ret = 0;
  2048. if (trans->aborted) {
  2049. if (insert_reserved)
  2050. btrfs_pin_extent(root, node->bytenr,
  2051. node->num_bytes, 1);
  2052. return 0;
  2053. }
  2054. if (btrfs_delayed_ref_is_head(node)) {
  2055. struct btrfs_delayed_ref_head *head;
  2056. /*
  2057. * we've hit the end of the chain and we were supposed
  2058. * to insert this extent into the tree. But, it got
  2059. * deleted before we ever needed to insert it, so all
  2060. * we have to do is clean up the accounting
  2061. */
  2062. BUG_ON(extent_op);
  2063. head = btrfs_delayed_node_to_head(node);
  2064. trace_run_delayed_ref_head(node, head, node->action);
  2065. if (insert_reserved) {
  2066. btrfs_pin_extent(root, node->bytenr,
  2067. node->num_bytes, 1);
  2068. if (head->is_data) {
  2069. ret = btrfs_del_csums(trans, root,
  2070. node->bytenr,
  2071. node->num_bytes);
  2072. }
  2073. }
  2074. return ret;
  2075. }
  2076. if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
  2077. node->type == BTRFS_SHARED_BLOCK_REF_KEY)
  2078. ret = run_delayed_tree_ref(trans, root, node, extent_op,
  2079. insert_reserved);
  2080. else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
  2081. node->type == BTRFS_SHARED_DATA_REF_KEY)
  2082. ret = run_delayed_data_ref(trans, root, node, extent_op,
  2083. insert_reserved);
  2084. else
  2085. BUG();
  2086. return ret;
  2087. }
  2088. static noinline struct btrfs_delayed_ref_node *
  2089. select_delayed_ref(struct btrfs_delayed_ref_head *head)
  2090. {
  2091. struct rb_node *node;
  2092. struct btrfs_delayed_ref_node *ref, *last = NULL;;
  2093. /*
  2094. * select delayed ref of type BTRFS_ADD_DELAYED_REF first.
  2095. * this prevents ref count from going down to zero when
  2096. * there still are pending delayed ref.
  2097. */
  2098. node = rb_first(&head->ref_root);
  2099. while (node) {
  2100. ref = rb_entry(node, struct btrfs_delayed_ref_node,
  2101. rb_node);
  2102. if (ref->action == BTRFS_ADD_DELAYED_REF)
  2103. return ref;
  2104. else if (last == NULL)
  2105. last = ref;
  2106. node = rb_next(node);
  2107. }
  2108. return last;
  2109. }
  2110. /*
  2111. * Returns 0 on success or if called with an already aborted transaction.
  2112. * Returns -ENOMEM or -EIO on failure and will abort the transaction.
  2113. */
  2114. static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
  2115. struct btrfs_root *root,
  2116. unsigned long nr)
  2117. {
  2118. struct btrfs_delayed_ref_root *delayed_refs;
  2119. struct btrfs_delayed_ref_node *ref;
  2120. struct btrfs_delayed_ref_head *locked_ref = NULL;
  2121. struct btrfs_delayed_extent_op *extent_op;
  2122. struct btrfs_fs_info *fs_info = root->fs_info;
  2123. ktime_t start = ktime_get();
  2124. int ret;
  2125. unsigned long count = 0;
  2126. unsigned long actual_count = 0;
  2127. int must_insert_reserved = 0;
  2128. delayed_refs = &trans->transaction->delayed_refs;
  2129. while (1) {
  2130. if (!locked_ref) {
  2131. if (count >= nr)
  2132. break;
  2133. spin_lock(&delayed_refs->lock);
  2134. locked_ref = btrfs_select_ref_head(trans);
  2135. if (!locked_ref) {
  2136. spin_unlock(&delayed_refs->lock);
  2137. break;
  2138. }
  2139. /* grab the lock that says we are going to process
  2140. * all the refs for this head */
  2141. ret = btrfs_delayed_ref_lock(trans, locked_ref);
  2142. spin_unlock(&delayed_refs->lock);
  2143. /*
  2144. * we may have dropped the spin lock to get the head
  2145. * mutex lock, and that might have given someone else
  2146. * time to free the head. If that's true, it has been
  2147. * removed from our list and we can move on.
  2148. */
  2149. if (ret == -EAGAIN) {
  2150. locked_ref = NULL;
  2151. count++;
  2152. continue;
  2153. }
  2154. }
  2155. /*
  2156. * We need to try and merge add/drops of the same ref since we
  2157. * can run into issues with relocate dropping the implicit ref
  2158. * and then it being added back again before the drop can
  2159. * finish. If we merged anything we need to re-loop so we can
  2160. * get a good ref.
  2161. */
  2162. spin_lock(&locked_ref->lock);
  2163. btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
  2164. locked_ref);
  2165. /*
  2166. * locked_ref is the head node, so we have to go one
  2167. * node back for any delayed ref updates
  2168. */
  2169. ref = select_delayed_ref(locked_ref);
  2170. if (ref && ref->seq &&
  2171. btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
  2172. spin_unlock(&locked_ref->lock);
  2173. btrfs_delayed_ref_unlock(locked_ref);
  2174. spin_lock(&delayed_refs->lock);
  2175. locked_ref->processing = 0;
  2176. delayed_refs->num_heads_ready++;
  2177. spin_unlock(&delayed_refs->lock);
  2178. locked_ref = NULL;
  2179. cond_resched();
  2180. count++;
  2181. continue;
  2182. }
  2183. /*
  2184. * record the must insert reserved flag before we
  2185. * drop the spin lock.
  2186. */
  2187. must_insert_reserved = locked_ref->must_insert_reserved;
  2188. locked_ref->must_insert_reserved = 0;
  2189. extent_op = locked_ref->extent_op;
  2190. locked_ref->extent_op = NULL;
  2191. if (!ref) {
  2192. /* All delayed refs have been processed, Go ahead
  2193. * and send the head node to run_one_delayed_ref,
  2194. * so that any accounting fixes can happen
  2195. */
  2196. ref = &locked_ref->node;
  2197. if (extent_op && must_insert_reserved) {
  2198. btrfs_free_delayed_extent_op(extent_op);
  2199. extent_op = NULL;
  2200. }
  2201. if (extent_op) {
  2202. spin_unlock(&locked_ref->lock);
  2203. ret = run_delayed_extent_op(trans, root,
  2204. ref, extent_op);
  2205. btrfs_free_delayed_extent_op(extent_op);
  2206. if (ret) {
  2207. /*
  2208. * Need to reset must_insert_reserved if
  2209. * there was an error so the abort stuff
  2210. * can cleanup the reserved space
  2211. * properly.
  2212. */
  2213. if (must_insert_reserved)
  2214. locked_ref->must_insert_reserved = 1;
  2215. locked_ref->processing = 0;
  2216. btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
  2217. btrfs_delayed_ref_unlock(locked_ref);
  2218. return ret;
  2219. }
  2220. continue;
  2221. }
  2222. /*
  2223. * Need to drop our head ref lock and re-aqcuire the
  2224. * delayed ref lock and then re-check to make sure
  2225. * nobody got added.
  2226. */
  2227. spin_unlock(&locked_ref->lock);
  2228. spin_lock(&delayed_refs->lock);
  2229. spin_lock(&locked_ref->lock);
  2230. if (rb_first(&locked_ref->ref_root) ||
  2231. locked_ref->extent_op) {
  2232. spin_unlock(&locked_ref->lock);
  2233. spin_unlock(&delayed_refs->lock);
  2234. continue;
  2235. }
  2236. ref->in_tree = 0;
  2237. delayed_refs->num_heads--;
  2238. rb_erase(&locked_ref->href_node,
  2239. &delayed_refs->href_root);
  2240. spin_unlock(&delayed_refs->lock);
  2241. } else {
  2242. actual_count++;
  2243. ref->in_tree = 0;
  2244. rb_erase(&ref->rb_node, &locked_ref->ref_root);
  2245. }
  2246. atomic_dec(&delayed_refs->num_entries);
  2247. if (!btrfs_delayed_ref_is_head(ref)) {
  2248. /*
  2249. * when we play the delayed ref, also correct the
  2250. * ref_mod on head
  2251. */
  2252. switch (ref->action) {
  2253. case BTRFS_ADD_DELAYED_REF:
  2254. case BTRFS_ADD_DELAYED_EXTENT:
  2255. locked_ref->node.ref_mod -= ref->ref_mod;
  2256. break;
  2257. case BTRFS_DROP_DELAYED_REF:
  2258. locked_ref->node.ref_mod += ref->ref_mod;
  2259. break;
  2260. default:
  2261. WARN_ON(1);
  2262. }
  2263. }
  2264. spin_unlock(&locked_ref->lock);
  2265. ret = run_one_delayed_ref(trans, root, ref, extent_op,
  2266. must_insert_reserved);
  2267. btrfs_free_delayed_extent_op(extent_op);
  2268. if (ret) {
  2269. locked_ref->processing = 0;
  2270. btrfs_delayed_ref_unlock(locked_ref);
  2271. btrfs_put_delayed_ref(ref);
  2272. btrfs_debug(fs_info, "run_one_delayed_ref returned %d", ret);
  2273. return ret;
  2274. }
  2275. /*
  2276. * If this node is a head, that means all the refs in this head
  2277. * have been dealt with, and we will pick the next head to deal
  2278. * with, so we must unlock the head and drop it from the cluster
  2279. * list before we release it.
  2280. */
  2281. if (btrfs_delayed_ref_is_head(ref)) {
  2282. btrfs_delayed_ref_unlock(locked_ref);
  2283. locked_ref = NULL;
  2284. }
  2285. btrfs_put_delayed_ref(ref);
  2286. count++;
  2287. cond_resched();
  2288. }
  2289. /*
  2290. * We don't want to include ref heads since we can have empty ref heads
  2291. * and those will drastically skew our runtime down since we just do
  2292. * accounting, no actual extent tree updates.
  2293. */
  2294. if (actual_count > 0) {
  2295. u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
  2296. u64 avg;
  2297. /*
  2298. * We weigh the current average higher than our current runtime
  2299. * to avoid large swings in the average.
  2300. */
  2301. spin_lock(&delayed_refs->lock);
  2302. avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
  2303. avg = div64_u64(avg, 4);
  2304. fs_info->avg_delayed_ref_runtime = avg;
  2305. spin_unlock(&delayed_refs->lock);
  2306. }
  2307. return 0;
  2308. }
  2309. #ifdef SCRAMBLE_DELAYED_REFS
  2310. /*
  2311. * Normally delayed refs get processed in ascending bytenr order. This
  2312. * correlates in most cases to the order added. To expose dependencies on this
  2313. * order, we start to process the tree in the middle instead of the beginning
  2314. */
  2315. static u64 find_middle(struct rb_root *root)
  2316. {
  2317. struct rb_node *n = root->rb_node;
  2318. struct btrfs_delayed_ref_node *entry;
  2319. int alt = 1;
  2320. u64 middle;
  2321. u64 first = 0, last = 0;
  2322. n = rb_first(root);
  2323. if (n) {
  2324. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  2325. first = entry->bytenr;
  2326. }
  2327. n = rb_last(root);
  2328. if (n) {
  2329. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  2330. last = entry->bytenr;
  2331. }
  2332. n = root->rb_node;
  2333. while (n) {
  2334. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  2335. WARN_ON(!entry->in_tree);
  2336. middle = entry->bytenr;
  2337. if (alt)
  2338. n = n->rb_left;
  2339. else
  2340. n = n->rb_right;
  2341. alt = 1 - alt;
  2342. }
  2343. return middle;
  2344. }
  2345. #endif
  2346. static inline u64 heads_to_leaves(struct btrfs_root *root, u64 heads)
  2347. {
  2348. u64 num_bytes;
  2349. num_bytes = heads * (sizeof(struct btrfs_extent_item) +
  2350. sizeof(struct btrfs_extent_inline_ref));
  2351. if (!btrfs_fs_incompat(root->fs_info, SKINNY_METADATA))
  2352. num_bytes += heads * sizeof(struct btrfs_tree_block_info);
  2353. /*
  2354. * We don't ever fill up leaves all the way so multiply by 2 just to be
  2355. * closer to what we're really going to want to ouse.
  2356. */
  2357. return div64_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(root));
  2358. }
  2359. int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
  2360. struct btrfs_root *root)
  2361. {
  2362. struct btrfs_block_rsv *global_rsv;
  2363. u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
  2364. u64 num_bytes;
  2365. int ret = 0;
  2366. num_bytes = btrfs_calc_trans_metadata_size(root, 1);
  2367. num_heads = heads_to_leaves(root, num_heads);
  2368. if (num_heads > 1)
  2369. num_bytes += (num_heads - 1) * root->nodesize;
  2370. num_bytes <<= 1;
  2371. global_rsv = &root->fs_info->global_block_rsv;
  2372. /*
  2373. * If we can't allocate any more chunks lets make sure we have _lots_ of
  2374. * wiggle room since running delayed refs can create more delayed refs.
  2375. */
  2376. if (global_rsv->space_info->full)
  2377. num_bytes <<= 1;
  2378. spin_lock(&global_rsv->lock);
  2379. if (global_rsv->reserved <= num_bytes)
  2380. ret = 1;
  2381. spin_unlock(&global_rsv->lock);
  2382. return ret;
  2383. }
  2384. int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
  2385. struct btrfs_root *root)
  2386. {
  2387. struct btrfs_fs_info *fs_info = root->fs_info;
  2388. u64 num_entries =
  2389. atomic_read(&trans->transaction->delayed_refs.num_entries);
  2390. u64 avg_runtime;
  2391. u64 val;
  2392. smp_mb();
  2393. avg_runtime = fs_info->avg_delayed_ref_runtime;
  2394. val = num_entries * avg_runtime;
  2395. if (num_entries * avg_runtime >= NSEC_PER_SEC)
  2396. return 1;
  2397. if (val >= NSEC_PER_SEC / 2)
  2398. return 2;
  2399. return btrfs_check_space_for_delayed_refs(trans, root);
  2400. }
  2401. struct async_delayed_refs {
  2402. struct btrfs_root *root;
  2403. int count;
  2404. int error;
  2405. int sync;
  2406. struct completion wait;
  2407. struct btrfs_work work;
  2408. };
  2409. static void delayed_ref_async_start(struct btrfs_work *work)
  2410. {
  2411. struct async_delayed_refs *async;
  2412. struct btrfs_trans_handle *trans;
  2413. int ret;
  2414. async = container_of(work, struct async_delayed_refs, work);
  2415. trans = btrfs_join_transaction(async->root);
  2416. if (IS_ERR(trans)) {
  2417. async->error = PTR_ERR(trans);
  2418. goto done;
  2419. }
  2420. /*
  2421. * trans->sync means that when we call end_transaciton, we won't
  2422. * wait on delayed refs
  2423. */
  2424. trans->sync = true;
  2425. ret = btrfs_run_delayed_refs(trans, async->root, async->count);
  2426. if (ret)
  2427. async->error = ret;
  2428. ret = btrfs_end_transaction(trans, async->root);
  2429. if (ret && !async->error)
  2430. async->error = ret;
  2431. done:
  2432. if (async->sync)
  2433. complete(&async->wait);
  2434. else
  2435. kfree(async);
  2436. }
  2437. int btrfs_async_run_delayed_refs(struct btrfs_root *root,
  2438. unsigned long count, int wait)
  2439. {
  2440. struct async_delayed_refs *async;
  2441. int ret;
  2442. async = kmalloc(sizeof(*async), GFP_NOFS);
  2443. if (!async)
  2444. return -ENOMEM;
  2445. async->root = root->fs_info->tree_root;
  2446. async->count = count;
  2447. async->error = 0;
  2448. if (wait)
  2449. async->sync = 1;
  2450. else
  2451. async->sync = 0;
  2452. init_completion(&async->wait);
  2453. btrfs_init_work(&async->work, btrfs_extent_refs_helper,
  2454. delayed_ref_async_start, NULL, NULL);
  2455. btrfs_queue_work(root->fs_info->extent_workers, &async->work);
  2456. if (wait) {
  2457. wait_for_completion(&async->wait);
  2458. ret = async->error;
  2459. kfree(async);
  2460. return ret;
  2461. }
  2462. return 0;
  2463. }
  2464. /*
  2465. * this starts processing the delayed reference count updates and
  2466. * extent insertions we have queued up so far. count can be
  2467. * 0, which means to process everything in the tree at the start
  2468. * of the run (but not newly added entries), or it can be some target
  2469. * number you'd like to process.
  2470. *
  2471. * Returns 0 on success or if called with an aborted transaction
  2472. * Returns <0 on error and aborts the transaction
  2473. */
  2474. int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
  2475. struct btrfs_root *root, unsigned long count)
  2476. {
  2477. struct rb_node *node;
  2478. struct btrfs_delayed_ref_root *delayed_refs;
  2479. struct btrfs_delayed_ref_head *head;
  2480. int ret;
  2481. int run_all = count == (unsigned long)-1;
  2482. /* We'll clean this up in btrfs_cleanup_transaction */
  2483. if (trans->aborted)
  2484. return 0;
  2485. if (root == root->fs_info->extent_root)
  2486. root = root->fs_info->tree_root;
  2487. delayed_refs = &trans->transaction->delayed_refs;
  2488. if (count == 0)
  2489. count = atomic_read(&delayed_refs->num_entries) * 2;
  2490. again:
  2491. #ifdef SCRAMBLE_DELAYED_REFS
  2492. delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
  2493. #endif
  2494. ret = __btrfs_run_delayed_refs(trans, root, count);
  2495. if (ret < 0) {
  2496. btrfs_abort_transaction(trans, root, ret);
  2497. return ret;
  2498. }
  2499. if (run_all) {
  2500. if (!list_empty(&trans->new_bgs))
  2501. btrfs_create_pending_block_groups(trans, root);
  2502. spin_lock(&delayed_refs->lock);
  2503. node = rb_first(&delayed_refs->href_root);
  2504. if (!node) {
  2505. spin_unlock(&delayed_refs->lock);
  2506. goto out;
  2507. }
  2508. count = (unsigned long)-1;
  2509. while (node) {
  2510. head = rb_entry(node, struct btrfs_delayed_ref_head,
  2511. href_node);
  2512. if (btrfs_delayed_ref_is_head(&head->node)) {
  2513. struct btrfs_delayed_ref_node *ref;
  2514. ref = &head->node;
  2515. atomic_inc(&ref->refs);
  2516. spin_unlock(&delayed_refs->lock);
  2517. /*
  2518. * Mutex was contended, block until it's
  2519. * released and try again
  2520. */
  2521. mutex_lock(&head->mutex);
  2522. mutex_unlock(&head->mutex);
  2523. btrfs_put_delayed_ref(ref);
  2524. cond_resched();
  2525. goto again;
  2526. } else {
  2527. WARN_ON(1);
  2528. }
  2529. node = rb_next(node);
  2530. }
  2531. spin_unlock(&delayed_refs->lock);
  2532. cond_resched();
  2533. goto again;
  2534. }
  2535. out:
  2536. ret = btrfs_delayed_qgroup_accounting(trans, root->fs_info);
  2537. if (ret)
  2538. return ret;
  2539. assert_qgroups_uptodate(trans);
  2540. return 0;
  2541. }
  2542. int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
  2543. struct btrfs_root *root,
  2544. u64 bytenr, u64 num_bytes, u64 flags,
  2545. int level, int is_data)
  2546. {
  2547. struct btrfs_delayed_extent_op *extent_op;
  2548. int ret;
  2549. extent_op = btrfs_alloc_delayed_extent_op();
  2550. if (!extent_op)
  2551. return -ENOMEM;
  2552. extent_op->flags_to_set = flags;
  2553. extent_op->update_flags = 1;
  2554. extent_op->update_key = 0;
  2555. extent_op->is_data = is_data ? 1 : 0;
  2556. extent_op->level = level;
  2557. ret = btrfs_add_delayed_extent_op(root->fs_info, trans, bytenr,
  2558. num_bytes, extent_op);
  2559. if (ret)
  2560. btrfs_free_delayed_extent_op(extent_op);
  2561. return ret;
  2562. }
  2563. static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
  2564. struct btrfs_root *root,
  2565. struct btrfs_path *path,
  2566. u64 objectid, u64 offset, u64 bytenr)
  2567. {
  2568. struct btrfs_delayed_ref_head *head;
  2569. struct btrfs_delayed_ref_node *ref;
  2570. struct btrfs_delayed_data_ref *data_ref;
  2571. struct btrfs_delayed_ref_root *delayed_refs;
  2572. struct rb_node *node;
  2573. int ret = 0;
  2574. delayed_refs = &trans->transaction->delayed_refs;
  2575. spin_lock(&delayed_refs->lock);
  2576. head = btrfs_find_delayed_ref_head(trans, bytenr);
  2577. if (!head) {
  2578. spin_unlock(&delayed_refs->lock);
  2579. return 0;
  2580. }
  2581. if (!mutex_trylock(&head->mutex)) {
  2582. atomic_inc(&head->node.refs);
  2583. spin_unlock(&delayed_refs->lock);
  2584. btrfs_release_path(path);
  2585. /*
  2586. * Mutex was contended, block until it's released and let
  2587. * caller try again
  2588. */
  2589. mutex_lock(&head->mutex);
  2590. mutex_unlock(&head->mutex);
  2591. btrfs_put_delayed_ref(&head->node);
  2592. return -EAGAIN;
  2593. }
  2594. spin_unlock(&delayed_refs->lock);
  2595. spin_lock(&head->lock);
  2596. node = rb_first(&head->ref_root);
  2597. while (node) {
  2598. ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
  2599. node = rb_next(node);
  2600. /* If it's a shared ref we know a cross reference exists */
  2601. if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
  2602. ret = 1;
  2603. break;
  2604. }
  2605. data_ref = btrfs_delayed_node_to_data_ref(ref);
  2606. /*
  2607. * If our ref doesn't match the one we're currently looking at
  2608. * then we have a cross reference.
  2609. */
  2610. if (data_ref->root != root->root_key.objectid ||
  2611. data_ref->objectid != objectid ||
  2612. data_ref->offset != offset) {
  2613. ret = 1;
  2614. break;
  2615. }
  2616. }
  2617. spin_unlock(&head->lock);
  2618. mutex_unlock(&head->mutex);
  2619. return ret;
  2620. }
  2621. static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
  2622. struct btrfs_root *root,
  2623. struct btrfs_path *path,
  2624. u64 objectid, u64 offset, u64 bytenr)
  2625. {
  2626. struct btrfs_root *extent_root = root->fs_info->extent_root;
  2627. struct extent_buffer *leaf;
  2628. struct btrfs_extent_data_ref *ref;
  2629. struct btrfs_extent_inline_ref *iref;
  2630. struct btrfs_extent_item *ei;
  2631. struct btrfs_key key;
  2632. u32 item_size;
  2633. int ret;
  2634. key.objectid = bytenr;
  2635. key.offset = (u64)-1;
  2636. key.type = BTRFS_EXTENT_ITEM_KEY;
  2637. ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
  2638. if (ret < 0)
  2639. goto out;
  2640. BUG_ON(ret == 0); /* Corruption */
  2641. ret = -ENOENT;
  2642. if (path->slots[0] == 0)
  2643. goto out;
  2644. path->slots[0]--;
  2645. leaf = path->nodes[0];
  2646. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  2647. if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
  2648. goto out;
  2649. ret = 1;
  2650. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  2651. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  2652. if (item_size < sizeof(*ei)) {
  2653. WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
  2654. goto out;
  2655. }
  2656. #endif
  2657. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  2658. if (item_size != sizeof(*ei) +
  2659. btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
  2660. goto out;
  2661. if (btrfs_extent_generation(leaf, ei) <=
  2662. btrfs_root_last_snapshot(&root->root_item))
  2663. goto out;
  2664. iref = (struct btrfs_extent_inline_ref *)(ei + 1);
  2665. if (btrfs_extent_inline_ref_type(leaf, iref) !=
  2666. BTRFS_EXTENT_DATA_REF_KEY)
  2667. goto out;
  2668. ref = (struct btrfs_extent_data_ref *)(&iref->offset);
  2669. if (btrfs_extent_refs(leaf, ei) !=
  2670. btrfs_extent_data_ref_count(leaf, ref) ||
  2671. btrfs_extent_data_ref_root(leaf, ref) !=
  2672. root->root_key.objectid ||
  2673. btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
  2674. btrfs_extent_data_ref_offset(leaf, ref) != offset)
  2675. goto out;
  2676. ret = 0;
  2677. out:
  2678. return ret;
  2679. }
  2680. int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
  2681. struct btrfs_root *root,
  2682. u64 objectid, u64 offset, u64 bytenr)
  2683. {
  2684. struct btrfs_path *path;
  2685. int ret;
  2686. int ret2;
  2687. path = btrfs_alloc_path();
  2688. if (!path)
  2689. return -ENOENT;
  2690. do {
  2691. ret = check_committed_ref(trans, root, path, objectid,
  2692. offset, bytenr);
  2693. if (ret && ret != -ENOENT)
  2694. goto out;
  2695. ret2 = check_delayed_ref(trans, root, path, objectid,
  2696. offset, bytenr);
  2697. } while (ret2 == -EAGAIN);
  2698. if (ret2 && ret2 != -ENOENT) {
  2699. ret = ret2;
  2700. goto out;
  2701. }
  2702. if (ret != -ENOENT || ret2 != -ENOENT)
  2703. ret = 0;
  2704. out:
  2705. btrfs_free_path(path);
  2706. if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
  2707. WARN_ON(ret > 0);
  2708. return ret;
  2709. }
  2710. static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
  2711. struct btrfs_root *root,
  2712. struct extent_buffer *buf,
  2713. int full_backref, int inc)
  2714. {
  2715. u64 bytenr;
  2716. u64 num_bytes;
  2717. u64 parent;
  2718. u64 ref_root;
  2719. u32 nritems;
  2720. struct btrfs_key key;
  2721. struct btrfs_file_extent_item *fi;
  2722. int i;
  2723. int level;
  2724. int ret = 0;
  2725. int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
  2726. u64, u64, u64, u64, u64, u64, int);
  2727. if (btrfs_test_is_dummy_root(root))
  2728. return 0;
  2729. ref_root = btrfs_header_owner(buf);
  2730. nritems = btrfs_header_nritems(buf);
  2731. level = btrfs_header_level(buf);
  2732. if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
  2733. return 0;
  2734. if (inc)
  2735. process_func = btrfs_inc_extent_ref;
  2736. else
  2737. process_func = btrfs_free_extent;
  2738. if (full_backref)
  2739. parent = buf->start;
  2740. else
  2741. parent = 0;
  2742. for (i = 0; i < nritems; i++) {
  2743. if (level == 0) {
  2744. btrfs_item_key_to_cpu(buf, &key, i);
  2745. if (key.type != BTRFS_EXTENT_DATA_KEY)
  2746. continue;
  2747. fi = btrfs_item_ptr(buf, i,
  2748. struct btrfs_file_extent_item);
  2749. if (btrfs_file_extent_type(buf, fi) ==
  2750. BTRFS_FILE_EXTENT_INLINE)
  2751. continue;
  2752. bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
  2753. if (bytenr == 0)
  2754. continue;
  2755. num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
  2756. key.offset -= btrfs_file_extent_offset(buf, fi);
  2757. ret = process_func(trans, root, bytenr, num_bytes,
  2758. parent, ref_root, key.objectid,
  2759. key.offset, 1);
  2760. if (ret)
  2761. goto fail;
  2762. } else {
  2763. bytenr = btrfs_node_blockptr(buf, i);
  2764. num_bytes = root->nodesize;
  2765. ret = process_func(trans, root, bytenr, num_bytes,
  2766. parent, ref_root, level - 1, 0,
  2767. 1);
  2768. if (ret)
  2769. goto fail;
  2770. }
  2771. }
  2772. return 0;
  2773. fail:
  2774. return ret;
  2775. }
  2776. int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  2777. struct extent_buffer *buf, int full_backref)
  2778. {
  2779. return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
  2780. }
  2781. int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  2782. struct extent_buffer *buf, int full_backref)
  2783. {
  2784. return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
  2785. }
  2786. static int write_one_cache_group(struct btrfs_trans_handle *trans,
  2787. struct btrfs_root *root,
  2788. struct btrfs_path *path,
  2789. struct btrfs_block_group_cache *cache)
  2790. {
  2791. int ret;
  2792. struct btrfs_root *extent_root = root->fs_info->extent_root;
  2793. unsigned long bi;
  2794. struct extent_buffer *leaf;
  2795. ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
  2796. if (ret) {
  2797. if (ret > 0)
  2798. ret = -ENOENT;
  2799. goto fail;
  2800. }
  2801. leaf = path->nodes[0];
  2802. bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
  2803. write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
  2804. btrfs_mark_buffer_dirty(leaf);
  2805. btrfs_release_path(path);
  2806. fail:
  2807. if (ret)
  2808. btrfs_abort_transaction(trans, root, ret);
  2809. return ret;
  2810. }
  2811. static struct btrfs_block_group_cache *
  2812. next_block_group(struct btrfs_root *root,
  2813. struct btrfs_block_group_cache *cache)
  2814. {
  2815. struct rb_node *node;
  2816. spin_lock(&root->fs_info->block_group_cache_lock);
  2817. /* If our block group was removed, we need a full search. */
  2818. if (RB_EMPTY_NODE(&cache->cache_node)) {
  2819. const u64 next_bytenr = cache->key.objectid + cache->key.offset;
  2820. spin_unlock(&root->fs_info->block_group_cache_lock);
  2821. btrfs_put_block_group(cache);
  2822. cache = btrfs_lookup_first_block_group(root->fs_info,
  2823. next_bytenr);
  2824. return cache;
  2825. }
  2826. node = rb_next(&cache->cache_node);
  2827. btrfs_put_block_group(cache);
  2828. if (node) {
  2829. cache = rb_entry(node, struct btrfs_block_group_cache,
  2830. cache_node);
  2831. btrfs_get_block_group(cache);
  2832. } else
  2833. cache = NULL;
  2834. spin_unlock(&root->fs_info->block_group_cache_lock);
  2835. return cache;
  2836. }
  2837. static int cache_save_setup(struct btrfs_block_group_cache *block_group,
  2838. struct btrfs_trans_handle *trans,
  2839. struct btrfs_path *path)
  2840. {
  2841. struct btrfs_root *root = block_group->fs_info->tree_root;
  2842. struct inode *inode = NULL;
  2843. u64 alloc_hint = 0;
  2844. int dcs = BTRFS_DC_ERROR;
  2845. int num_pages = 0;
  2846. int retries = 0;
  2847. int ret = 0;
  2848. /*
  2849. * If this block group is smaller than 100 megs don't bother caching the
  2850. * block group.
  2851. */
  2852. if (block_group->key.offset < (100 * 1024 * 1024)) {
  2853. spin_lock(&block_group->lock);
  2854. block_group->disk_cache_state = BTRFS_DC_WRITTEN;
  2855. spin_unlock(&block_group->lock);
  2856. return 0;
  2857. }
  2858. if (trans->aborted)
  2859. return 0;
  2860. again:
  2861. inode = lookup_free_space_inode(root, block_group, path);
  2862. if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
  2863. ret = PTR_ERR(inode);
  2864. btrfs_release_path(path);
  2865. goto out;
  2866. }
  2867. if (IS_ERR(inode)) {
  2868. BUG_ON(retries);
  2869. retries++;
  2870. if (block_group->ro)
  2871. goto out_free;
  2872. ret = create_free_space_inode(root, trans, block_group, path);
  2873. if (ret)
  2874. goto out_free;
  2875. goto again;
  2876. }
  2877. /* We've already setup this transaction, go ahead and exit */
  2878. if (block_group->cache_generation == trans->transid &&
  2879. i_size_read(inode)) {
  2880. dcs = BTRFS_DC_SETUP;
  2881. goto out_put;
  2882. }
  2883. /*
  2884. * We want to set the generation to 0, that way if anything goes wrong
  2885. * from here on out we know not to trust this cache when we load up next
  2886. * time.
  2887. */
  2888. BTRFS_I(inode)->generation = 0;
  2889. ret = btrfs_update_inode(trans, root, inode);
  2890. if (ret) {
  2891. /*
  2892. * So theoretically we could recover from this, simply set the
  2893. * super cache generation to 0 so we know to invalidate the
  2894. * cache, but then we'd have to keep track of the block groups
  2895. * that fail this way so we know we _have_ to reset this cache
  2896. * before the next commit or risk reading stale cache. So to
  2897. * limit our exposure to horrible edge cases lets just abort the
  2898. * transaction, this only happens in really bad situations
  2899. * anyway.
  2900. */
  2901. btrfs_abort_transaction(trans, root, ret);
  2902. goto out_put;
  2903. }
  2904. WARN_ON(ret);
  2905. if (i_size_read(inode) > 0) {
  2906. ret = btrfs_check_trunc_cache_free_space(root,
  2907. &root->fs_info->global_block_rsv);
  2908. if (ret)
  2909. goto out_put;
  2910. ret = btrfs_truncate_free_space_cache(root, trans, inode);
  2911. if (ret)
  2912. goto out_put;
  2913. }
  2914. spin_lock(&block_group->lock);
  2915. if (block_group->cached != BTRFS_CACHE_FINISHED ||
  2916. !btrfs_test_opt(root, SPACE_CACHE) ||
  2917. block_group->delalloc_bytes) {
  2918. /*
  2919. * don't bother trying to write stuff out _if_
  2920. * a) we're not cached,
  2921. * b) we're with nospace_cache mount option.
  2922. */
  2923. dcs = BTRFS_DC_WRITTEN;
  2924. spin_unlock(&block_group->lock);
  2925. goto out_put;
  2926. }
  2927. spin_unlock(&block_group->lock);
  2928. /*
  2929. * Try to preallocate enough space based on how big the block group is.
  2930. * Keep in mind this has to include any pinned space which could end up
  2931. * taking up quite a bit since it's not folded into the other space
  2932. * cache.
  2933. */
  2934. num_pages = (int)div64_u64(block_group->key.offset, 256 * 1024 * 1024);
  2935. if (!num_pages)
  2936. num_pages = 1;
  2937. num_pages *= 16;
  2938. num_pages *= PAGE_CACHE_SIZE;
  2939. ret = btrfs_check_data_free_space(inode, num_pages);
  2940. if (ret)
  2941. goto out_put;
  2942. ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
  2943. num_pages, num_pages,
  2944. &alloc_hint);
  2945. if (!ret)
  2946. dcs = BTRFS_DC_SETUP;
  2947. btrfs_free_reserved_data_space(inode, num_pages);
  2948. out_put:
  2949. iput(inode);
  2950. out_free:
  2951. btrfs_release_path(path);
  2952. out:
  2953. spin_lock(&block_group->lock);
  2954. if (!ret && dcs == BTRFS_DC_SETUP)
  2955. block_group->cache_generation = trans->transid;
  2956. block_group->disk_cache_state = dcs;
  2957. spin_unlock(&block_group->lock);
  2958. return ret;
  2959. }
  2960. int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
  2961. struct btrfs_root *root)
  2962. {
  2963. struct btrfs_block_group_cache *cache;
  2964. struct btrfs_transaction *cur_trans = trans->transaction;
  2965. int ret = 0;
  2966. struct btrfs_path *path;
  2967. if (list_empty(&cur_trans->dirty_bgs))
  2968. return 0;
  2969. path = btrfs_alloc_path();
  2970. if (!path)
  2971. return -ENOMEM;
  2972. /*
  2973. * We don't need the lock here since we are protected by the transaction
  2974. * commit. We want to do the cache_save_setup first and then run the
  2975. * delayed refs to make sure we have the best chance at doing this all
  2976. * in one shot.
  2977. */
  2978. while (!list_empty(&cur_trans->dirty_bgs)) {
  2979. cache = list_first_entry(&cur_trans->dirty_bgs,
  2980. struct btrfs_block_group_cache,
  2981. dirty_list);
  2982. list_del_init(&cache->dirty_list);
  2983. if (cache->disk_cache_state == BTRFS_DC_CLEAR)
  2984. cache_save_setup(cache, trans, path);
  2985. if (!ret)
  2986. ret = btrfs_run_delayed_refs(trans, root,
  2987. (unsigned long) -1);
  2988. if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP)
  2989. btrfs_write_out_cache(root, trans, cache, path);
  2990. if (!ret)
  2991. ret = write_one_cache_group(trans, root, path, cache);
  2992. btrfs_put_block_group(cache);
  2993. }
  2994. btrfs_free_path(path);
  2995. return ret;
  2996. }
  2997. int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
  2998. {
  2999. struct btrfs_block_group_cache *block_group;
  3000. int readonly = 0;
  3001. block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
  3002. if (!block_group || block_group->ro)
  3003. readonly = 1;
  3004. if (block_group)
  3005. btrfs_put_block_group(block_group);
  3006. return readonly;
  3007. }
  3008. static const char *alloc_name(u64 flags)
  3009. {
  3010. switch (flags) {
  3011. case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
  3012. return "mixed";
  3013. case BTRFS_BLOCK_GROUP_METADATA:
  3014. return "metadata";
  3015. case BTRFS_BLOCK_GROUP_DATA:
  3016. return "data";
  3017. case BTRFS_BLOCK_GROUP_SYSTEM:
  3018. return "system";
  3019. default:
  3020. WARN_ON(1);
  3021. return "invalid-combination";
  3022. };
  3023. }
  3024. static int update_space_info(struct btrfs_fs_info *info, u64 flags,
  3025. u64 total_bytes, u64 bytes_used,
  3026. struct btrfs_space_info **space_info)
  3027. {
  3028. struct btrfs_space_info *found;
  3029. int i;
  3030. int factor;
  3031. int ret;
  3032. if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
  3033. BTRFS_BLOCK_GROUP_RAID10))
  3034. factor = 2;
  3035. else
  3036. factor = 1;
  3037. found = __find_space_info(info, flags);
  3038. if (found) {
  3039. spin_lock(&found->lock);
  3040. found->total_bytes += total_bytes;
  3041. found->disk_total += total_bytes * factor;
  3042. found->bytes_used += bytes_used;
  3043. found->disk_used += bytes_used * factor;
  3044. found->full = 0;
  3045. spin_unlock(&found->lock);
  3046. *space_info = found;
  3047. return 0;
  3048. }
  3049. found = kzalloc(sizeof(*found), GFP_NOFS);
  3050. if (!found)
  3051. return -ENOMEM;
  3052. ret = percpu_counter_init(&found->total_bytes_pinned, 0, GFP_KERNEL);
  3053. if (ret) {
  3054. kfree(found);
  3055. return ret;
  3056. }
  3057. for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
  3058. INIT_LIST_HEAD(&found->block_groups[i]);
  3059. init_rwsem(&found->groups_sem);
  3060. spin_lock_init(&found->lock);
  3061. found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
  3062. found->total_bytes = total_bytes;
  3063. found->disk_total = total_bytes * factor;
  3064. found->bytes_used = bytes_used;
  3065. found->disk_used = bytes_used * factor;
  3066. found->bytes_pinned = 0;
  3067. found->bytes_reserved = 0;
  3068. found->bytes_readonly = 0;
  3069. found->bytes_may_use = 0;
  3070. found->full = 0;
  3071. found->force_alloc = CHUNK_ALLOC_NO_FORCE;
  3072. found->chunk_alloc = 0;
  3073. found->flush = 0;
  3074. init_waitqueue_head(&found->wait);
  3075. INIT_LIST_HEAD(&found->ro_bgs);
  3076. ret = kobject_init_and_add(&found->kobj, &space_info_ktype,
  3077. info->space_info_kobj, "%s",
  3078. alloc_name(found->flags));
  3079. if (ret) {
  3080. kfree(found);
  3081. return ret;
  3082. }
  3083. *space_info = found;
  3084. list_add_rcu(&found->list, &info->space_info);
  3085. if (flags & BTRFS_BLOCK_GROUP_DATA)
  3086. info->data_sinfo = found;
  3087. return ret;
  3088. }
  3089. static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
  3090. {
  3091. u64 extra_flags = chunk_to_extended(flags) &
  3092. BTRFS_EXTENDED_PROFILE_MASK;
  3093. write_seqlock(&fs_info->profiles_lock);
  3094. if (flags & BTRFS_BLOCK_GROUP_DATA)
  3095. fs_info->avail_data_alloc_bits |= extra_flags;
  3096. if (flags & BTRFS_BLOCK_GROUP_METADATA)
  3097. fs_info->avail_metadata_alloc_bits |= extra_flags;
  3098. if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
  3099. fs_info->avail_system_alloc_bits |= extra_flags;
  3100. write_sequnlock(&fs_info->profiles_lock);
  3101. }
  3102. /*
  3103. * returns target flags in extended format or 0 if restripe for this
  3104. * chunk_type is not in progress
  3105. *
  3106. * should be called with either volume_mutex or balance_lock held
  3107. */
  3108. static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
  3109. {
  3110. struct btrfs_balance_control *bctl = fs_info->balance_ctl;
  3111. u64 target = 0;
  3112. if (!bctl)
  3113. return 0;
  3114. if (flags & BTRFS_BLOCK_GROUP_DATA &&
  3115. bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
  3116. target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
  3117. } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
  3118. bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
  3119. target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
  3120. } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
  3121. bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
  3122. target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
  3123. }
  3124. return target;
  3125. }
  3126. /*
  3127. * @flags: available profiles in extended format (see ctree.h)
  3128. *
  3129. * Returns reduced profile in chunk format. If profile changing is in
  3130. * progress (either running or paused) picks the target profile (if it's
  3131. * already available), otherwise falls back to plain reducing.
  3132. */
  3133. static u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
  3134. {
  3135. u64 num_devices = root->fs_info->fs_devices->rw_devices;
  3136. u64 target;
  3137. u64 tmp;
  3138. /*
  3139. * see if restripe for this chunk_type is in progress, if so
  3140. * try to reduce to the target profile
  3141. */
  3142. spin_lock(&root->fs_info->balance_lock);
  3143. target = get_restripe_target(root->fs_info, flags);
  3144. if (target) {
  3145. /* pick target profile only if it's already available */
  3146. if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
  3147. spin_unlock(&root->fs_info->balance_lock);
  3148. return extended_to_chunk(target);
  3149. }
  3150. }
  3151. spin_unlock(&root->fs_info->balance_lock);
  3152. /* First, mask out the RAID levels which aren't possible */
  3153. if (num_devices == 1)
  3154. flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0 |
  3155. BTRFS_BLOCK_GROUP_RAID5);
  3156. if (num_devices < 3)
  3157. flags &= ~BTRFS_BLOCK_GROUP_RAID6;
  3158. if (num_devices < 4)
  3159. flags &= ~BTRFS_BLOCK_GROUP_RAID10;
  3160. tmp = flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
  3161. BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID5 |
  3162. BTRFS_BLOCK_GROUP_RAID6 | BTRFS_BLOCK_GROUP_RAID10);
  3163. flags &= ~tmp;
  3164. if (tmp & BTRFS_BLOCK_GROUP_RAID6)
  3165. tmp = BTRFS_BLOCK_GROUP_RAID6;
  3166. else if (tmp & BTRFS_BLOCK_GROUP_RAID5)
  3167. tmp = BTRFS_BLOCK_GROUP_RAID5;
  3168. else if (tmp & BTRFS_BLOCK_GROUP_RAID10)
  3169. tmp = BTRFS_BLOCK_GROUP_RAID10;
  3170. else if (tmp & BTRFS_BLOCK_GROUP_RAID1)
  3171. tmp = BTRFS_BLOCK_GROUP_RAID1;
  3172. else if (tmp & BTRFS_BLOCK_GROUP_RAID0)
  3173. tmp = BTRFS_BLOCK_GROUP_RAID0;
  3174. return extended_to_chunk(flags | tmp);
  3175. }
  3176. static u64 get_alloc_profile(struct btrfs_root *root, u64 orig_flags)
  3177. {
  3178. unsigned seq;
  3179. u64 flags;
  3180. do {
  3181. flags = orig_flags;
  3182. seq = read_seqbegin(&root->fs_info->profiles_lock);
  3183. if (flags & BTRFS_BLOCK_GROUP_DATA)
  3184. flags |= root->fs_info->avail_data_alloc_bits;
  3185. else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
  3186. flags |= root->fs_info->avail_system_alloc_bits;
  3187. else if (flags & BTRFS_BLOCK_GROUP_METADATA)
  3188. flags |= root->fs_info->avail_metadata_alloc_bits;
  3189. } while (read_seqretry(&root->fs_info->profiles_lock, seq));
  3190. return btrfs_reduce_alloc_profile(root, flags);
  3191. }
  3192. u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
  3193. {
  3194. u64 flags;
  3195. u64 ret;
  3196. if (data)
  3197. flags = BTRFS_BLOCK_GROUP_DATA;
  3198. else if (root == root->fs_info->chunk_root)
  3199. flags = BTRFS_BLOCK_GROUP_SYSTEM;
  3200. else
  3201. flags = BTRFS_BLOCK_GROUP_METADATA;
  3202. ret = get_alloc_profile(root, flags);
  3203. return ret;
  3204. }
  3205. /*
  3206. * This will check the space that the inode allocates from to make sure we have
  3207. * enough space for bytes.
  3208. */
  3209. int btrfs_check_data_free_space(struct inode *inode, u64 bytes)
  3210. {
  3211. struct btrfs_space_info *data_sinfo;
  3212. struct btrfs_root *root = BTRFS_I(inode)->root;
  3213. struct btrfs_fs_info *fs_info = root->fs_info;
  3214. u64 used;
  3215. int ret = 0, committed = 0, alloc_chunk = 1;
  3216. /* make sure bytes are sectorsize aligned */
  3217. bytes = ALIGN(bytes, root->sectorsize);
  3218. if (btrfs_is_free_space_inode(inode)) {
  3219. committed = 1;
  3220. ASSERT(current->journal_info);
  3221. }
  3222. data_sinfo = fs_info->data_sinfo;
  3223. if (!data_sinfo)
  3224. goto alloc;
  3225. again:
  3226. /* make sure we have enough space to handle the data first */
  3227. spin_lock(&data_sinfo->lock);
  3228. used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
  3229. data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
  3230. data_sinfo->bytes_may_use;
  3231. if (used + bytes > data_sinfo->total_bytes) {
  3232. struct btrfs_trans_handle *trans;
  3233. /*
  3234. * if we don't have enough free bytes in this space then we need
  3235. * to alloc a new chunk.
  3236. */
  3237. if (!data_sinfo->full && alloc_chunk) {
  3238. u64 alloc_target;
  3239. data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
  3240. spin_unlock(&data_sinfo->lock);
  3241. alloc:
  3242. alloc_target = btrfs_get_alloc_profile(root, 1);
  3243. /*
  3244. * It is ugly that we don't call nolock join
  3245. * transaction for the free space inode case here.
  3246. * But it is safe because we only do the data space
  3247. * reservation for the free space cache in the
  3248. * transaction context, the common join transaction
  3249. * just increase the counter of the current transaction
  3250. * handler, doesn't try to acquire the trans_lock of
  3251. * the fs.
  3252. */
  3253. trans = btrfs_join_transaction(root);
  3254. if (IS_ERR(trans))
  3255. return PTR_ERR(trans);
  3256. ret = do_chunk_alloc(trans, root->fs_info->extent_root,
  3257. alloc_target,
  3258. CHUNK_ALLOC_NO_FORCE);
  3259. btrfs_end_transaction(trans, root);
  3260. if (ret < 0) {
  3261. if (ret != -ENOSPC)
  3262. return ret;
  3263. else
  3264. goto commit_trans;
  3265. }
  3266. if (!data_sinfo)
  3267. data_sinfo = fs_info->data_sinfo;
  3268. goto again;
  3269. }
  3270. /*
  3271. * If we don't have enough pinned space to deal with this
  3272. * allocation don't bother committing the transaction.
  3273. */
  3274. if (percpu_counter_compare(&data_sinfo->total_bytes_pinned,
  3275. bytes) < 0)
  3276. committed = 1;
  3277. spin_unlock(&data_sinfo->lock);
  3278. /* commit the current transaction and try again */
  3279. commit_trans:
  3280. if (!committed &&
  3281. !atomic_read(&root->fs_info->open_ioctl_trans)) {
  3282. committed = 1;
  3283. trans = btrfs_join_transaction(root);
  3284. if (IS_ERR(trans))
  3285. return PTR_ERR(trans);
  3286. ret = btrfs_commit_transaction(trans, root);
  3287. if (ret)
  3288. return ret;
  3289. goto again;
  3290. }
  3291. trace_btrfs_space_reservation(root->fs_info,
  3292. "space_info:enospc",
  3293. data_sinfo->flags, bytes, 1);
  3294. return -ENOSPC;
  3295. }
  3296. data_sinfo->bytes_may_use += bytes;
  3297. trace_btrfs_space_reservation(root->fs_info, "space_info",
  3298. data_sinfo->flags, bytes, 1);
  3299. spin_unlock(&data_sinfo->lock);
  3300. return 0;
  3301. }
  3302. /*
  3303. * Called if we need to clear a data reservation for this inode.
  3304. */
  3305. void btrfs_free_reserved_data_space(struct inode *inode, u64 bytes)
  3306. {
  3307. struct btrfs_root *root = BTRFS_I(inode)->root;
  3308. struct btrfs_space_info *data_sinfo;
  3309. /* make sure bytes are sectorsize aligned */
  3310. bytes = ALIGN(bytes, root->sectorsize);
  3311. data_sinfo = root->fs_info->data_sinfo;
  3312. spin_lock(&data_sinfo->lock);
  3313. WARN_ON(data_sinfo->bytes_may_use < bytes);
  3314. data_sinfo->bytes_may_use -= bytes;
  3315. trace_btrfs_space_reservation(root->fs_info, "space_info",
  3316. data_sinfo->flags, bytes, 0);
  3317. spin_unlock(&data_sinfo->lock);
  3318. }
  3319. static void force_metadata_allocation(struct btrfs_fs_info *info)
  3320. {
  3321. struct list_head *head = &info->space_info;
  3322. struct btrfs_space_info *found;
  3323. rcu_read_lock();
  3324. list_for_each_entry_rcu(found, head, list) {
  3325. if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
  3326. found->force_alloc = CHUNK_ALLOC_FORCE;
  3327. }
  3328. rcu_read_unlock();
  3329. }
  3330. static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
  3331. {
  3332. return (global->size << 1);
  3333. }
  3334. static int should_alloc_chunk(struct btrfs_root *root,
  3335. struct btrfs_space_info *sinfo, int force)
  3336. {
  3337. struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
  3338. u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
  3339. u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
  3340. u64 thresh;
  3341. if (force == CHUNK_ALLOC_FORCE)
  3342. return 1;
  3343. /*
  3344. * We need to take into account the global rsv because for all intents
  3345. * and purposes it's used space. Don't worry about locking the
  3346. * global_rsv, it doesn't change except when the transaction commits.
  3347. */
  3348. if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
  3349. num_allocated += calc_global_rsv_need_space(global_rsv);
  3350. /*
  3351. * in limited mode, we want to have some free space up to
  3352. * about 1% of the FS size.
  3353. */
  3354. if (force == CHUNK_ALLOC_LIMITED) {
  3355. thresh = btrfs_super_total_bytes(root->fs_info->super_copy);
  3356. thresh = max_t(u64, 64 * 1024 * 1024,
  3357. div_factor_fine(thresh, 1));
  3358. if (num_bytes - num_allocated < thresh)
  3359. return 1;
  3360. }
  3361. if (num_allocated + 2 * 1024 * 1024 < div_factor(num_bytes, 8))
  3362. return 0;
  3363. return 1;
  3364. }
  3365. static u64 get_system_chunk_thresh(struct btrfs_root *root, u64 type)
  3366. {
  3367. u64 num_dev;
  3368. if (type & (BTRFS_BLOCK_GROUP_RAID10 |
  3369. BTRFS_BLOCK_GROUP_RAID0 |
  3370. BTRFS_BLOCK_GROUP_RAID5 |
  3371. BTRFS_BLOCK_GROUP_RAID6))
  3372. num_dev = root->fs_info->fs_devices->rw_devices;
  3373. else if (type & BTRFS_BLOCK_GROUP_RAID1)
  3374. num_dev = 2;
  3375. else
  3376. num_dev = 1; /* DUP or single */
  3377. /* metadata for updaing devices and chunk tree */
  3378. return btrfs_calc_trans_metadata_size(root, num_dev + 1);
  3379. }
  3380. static void check_system_chunk(struct btrfs_trans_handle *trans,
  3381. struct btrfs_root *root, u64 type)
  3382. {
  3383. struct btrfs_space_info *info;
  3384. u64 left;
  3385. u64 thresh;
  3386. info = __find_space_info(root->fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
  3387. spin_lock(&info->lock);
  3388. left = info->total_bytes - info->bytes_used - info->bytes_pinned -
  3389. info->bytes_reserved - info->bytes_readonly;
  3390. spin_unlock(&info->lock);
  3391. thresh = get_system_chunk_thresh(root, type);
  3392. if (left < thresh && btrfs_test_opt(root, ENOSPC_DEBUG)) {
  3393. btrfs_info(root->fs_info, "left=%llu, need=%llu, flags=%llu",
  3394. left, thresh, type);
  3395. dump_space_info(info, 0, 0);
  3396. }
  3397. if (left < thresh) {
  3398. u64 flags;
  3399. flags = btrfs_get_alloc_profile(root->fs_info->chunk_root, 0);
  3400. btrfs_alloc_chunk(trans, root, flags);
  3401. }
  3402. }
  3403. static int do_chunk_alloc(struct btrfs_trans_handle *trans,
  3404. struct btrfs_root *extent_root, u64 flags, int force)
  3405. {
  3406. struct btrfs_space_info *space_info;
  3407. struct btrfs_fs_info *fs_info = extent_root->fs_info;
  3408. int wait_for_alloc = 0;
  3409. int ret = 0;
  3410. /* Don't re-enter if we're already allocating a chunk */
  3411. if (trans->allocating_chunk)
  3412. return -ENOSPC;
  3413. space_info = __find_space_info(extent_root->fs_info, flags);
  3414. if (!space_info) {
  3415. ret = update_space_info(extent_root->fs_info, flags,
  3416. 0, 0, &space_info);
  3417. BUG_ON(ret); /* -ENOMEM */
  3418. }
  3419. BUG_ON(!space_info); /* Logic error */
  3420. again:
  3421. spin_lock(&space_info->lock);
  3422. if (force < space_info->force_alloc)
  3423. force = space_info->force_alloc;
  3424. if (space_info->full) {
  3425. if (should_alloc_chunk(extent_root, space_info, force))
  3426. ret = -ENOSPC;
  3427. else
  3428. ret = 0;
  3429. spin_unlock(&space_info->lock);
  3430. return ret;
  3431. }
  3432. if (!should_alloc_chunk(extent_root, space_info, force)) {
  3433. spin_unlock(&space_info->lock);
  3434. return 0;
  3435. } else if (space_info->chunk_alloc) {
  3436. wait_for_alloc = 1;
  3437. } else {
  3438. space_info->chunk_alloc = 1;
  3439. }
  3440. spin_unlock(&space_info->lock);
  3441. mutex_lock(&fs_info->chunk_mutex);
  3442. /*
  3443. * The chunk_mutex is held throughout the entirety of a chunk
  3444. * allocation, so once we've acquired the chunk_mutex we know that the
  3445. * other guy is done and we need to recheck and see if we should
  3446. * allocate.
  3447. */
  3448. if (wait_for_alloc) {
  3449. mutex_unlock(&fs_info->chunk_mutex);
  3450. wait_for_alloc = 0;
  3451. goto again;
  3452. }
  3453. trans->allocating_chunk = true;
  3454. /*
  3455. * If we have mixed data/metadata chunks we want to make sure we keep
  3456. * allocating mixed chunks instead of individual chunks.
  3457. */
  3458. if (btrfs_mixed_space_info(space_info))
  3459. flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
  3460. /*
  3461. * if we're doing a data chunk, go ahead and make sure that
  3462. * we keep a reasonable number of metadata chunks allocated in the
  3463. * FS as well.
  3464. */
  3465. if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
  3466. fs_info->data_chunk_allocations++;
  3467. if (!(fs_info->data_chunk_allocations %
  3468. fs_info->metadata_ratio))
  3469. force_metadata_allocation(fs_info);
  3470. }
  3471. /*
  3472. * Check if we have enough space in SYSTEM chunk because we may need
  3473. * to update devices.
  3474. */
  3475. check_system_chunk(trans, extent_root, flags);
  3476. ret = btrfs_alloc_chunk(trans, extent_root, flags);
  3477. trans->allocating_chunk = false;
  3478. spin_lock(&space_info->lock);
  3479. if (ret < 0 && ret != -ENOSPC)
  3480. goto out;
  3481. if (ret)
  3482. space_info->full = 1;
  3483. else
  3484. ret = 1;
  3485. space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
  3486. out:
  3487. space_info->chunk_alloc = 0;
  3488. spin_unlock(&space_info->lock);
  3489. mutex_unlock(&fs_info->chunk_mutex);
  3490. return ret;
  3491. }
  3492. static int can_overcommit(struct btrfs_root *root,
  3493. struct btrfs_space_info *space_info, u64 bytes,
  3494. enum btrfs_reserve_flush_enum flush)
  3495. {
  3496. struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
  3497. u64 profile = btrfs_get_alloc_profile(root, 0);
  3498. u64 space_size;
  3499. u64 avail;
  3500. u64 used;
  3501. used = space_info->bytes_used + space_info->bytes_reserved +
  3502. space_info->bytes_pinned + space_info->bytes_readonly;
  3503. /*
  3504. * We only want to allow over committing if we have lots of actual space
  3505. * free, but if we don't have enough space to handle the global reserve
  3506. * space then we could end up having a real enospc problem when trying
  3507. * to allocate a chunk or some other such important allocation.
  3508. */
  3509. spin_lock(&global_rsv->lock);
  3510. space_size = calc_global_rsv_need_space(global_rsv);
  3511. spin_unlock(&global_rsv->lock);
  3512. if (used + space_size >= space_info->total_bytes)
  3513. return 0;
  3514. used += space_info->bytes_may_use;
  3515. spin_lock(&root->fs_info->free_chunk_lock);
  3516. avail = root->fs_info->free_chunk_space;
  3517. spin_unlock(&root->fs_info->free_chunk_lock);
  3518. /*
  3519. * If we have dup, raid1 or raid10 then only half of the free
  3520. * space is actually useable. For raid56, the space info used
  3521. * doesn't include the parity drive, so we don't have to
  3522. * change the math
  3523. */
  3524. if (profile & (BTRFS_BLOCK_GROUP_DUP |
  3525. BTRFS_BLOCK_GROUP_RAID1 |
  3526. BTRFS_BLOCK_GROUP_RAID10))
  3527. avail >>= 1;
  3528. /*
  3529. * If we aren't flushing all things, let us overcommit up to
  3530. * 1/2th of the space. If we can flush, don't let us overcommit
  3531. * too much, let it overcommit up to 1/8 of the space.
  3532. */
  3533. if (flush == BTRFS_RESERVE_FLUSH_ALL)
  3534. avail >>= 3;
  3535. else
  3536. avail >>= 1;
  3537. if (used + bytes < space_info->total_bytes + avail)
  3538. return 1;
  3539. return 0;
  3540. }
  3541. static void btrfs_writeback_inodes_sb_nr(struct btrfs_root *root,
  3542. unsigned long nr_pages, int nr_items)
  3543. {
  3544. struct super_block *sb = root->fs_info->sb;
  3545. if (down_read_trylock(&sb->s_umount)) {
  3546. writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
  3547. up_read(&sb->s_umount);
  3548. } else {
  3549. /*
  3550. * We needn't worry the filesystem going from r/w to r/o though
  3551. * we don't acquire ->s_umount mutex, because the filesystem
  3552. * should guarantee the delalloc inodes list be empty after
  3553. * the filesystem is readonly(all dirty pages are written to
  3554. * the disk).
  3555. */
  3556. btrfs_start_delalloc_roots(root->fs_info, 0, nr_items);
  3557. if (!current->journal_info)
  3558. btrfs_wait_ordered_roots(root->fs_info, nr_items);
  3559. }
  3560. }
  3561. static inline int calc_reclaim_items_nr(struct btrfs_root *root, u64 to_reclaim)
  3562. {
  3563. u64 bytes;
  3564. int nr;
  3565. bytes = btrfs_calc_trans_metadata_size(root, 1);
  3566. nr = (int)div64_u64(to_reclaim, bytes);
  3567. if (!nr)
  3568. nr = 1;
  3569. return nr;
  3570. }
  3571. #define EXTENT_SIZE_PER_ITEM (256 * 1024)
  3572. /*
  3573. * shrink metadata reservation for delalloc
  3574. */
  3575. static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
  3576. bool wait_ordered)
  3577. {
  3578. struct btrfs_block_rsv *block_rsv;
  3579. struct btrfs_space_info *space_info;
  3580. struct btrfs_trans_handle *trans;
  3581. u64 delalloc_bytes;
  3582. u64 max_reclaim;
  3583. long time_left;
  3584. unsigned long nr_pages;
  3585. int loops;
  3586. int items;
  3587. enum btrfs_reserve_flush_enum flush;
  3588. /* Calc the number of the pages we need flush for space reservation */
  3589. items = calc_reclaim_items_nr(root, to_reclaim);
  3590. to_reclaim = items * EXTENT_SIZE_PER_ITEM;
  3591. trans = (struct btrfs_trans_handle *)current->journal_info;
  3592. block_rsv = &root->fs_info->delalloc_block_rsv;
  3593. space_info = block_rsv->space_info;
  3594. delalloc_bytes = percpu_counter_sum_positive(
  3595. &root->fs_info->delalloc_bytes);
  3596. if (delalloc_bytes == 0) {
  3597. if (trans)
  3598. return;
  3599. if (wait_ordered)
  3600. btrfs_wait_ordered_roots(root->fs_info, items);
  3601. return;
  3602. }
  3603. loops = 0;
  3604. while (delalloc_bytes && loops < 3) {
  3605. max_reclaim = min(delalloc_bytes, to_reclaim);
  3606. nr_pages = max_reclaim >> PAGE_CACHE_SHIFT;
  3607. btrfs_writeback_inodes_sb_nr(root, nr_pages, items);
  3608. /*
  3609. * We need to wait for the async pages to actually start before
  3610. * we do anything.
  3611. */
  3612. max_reclaim = atomic_read(&root->fs_info->async_delalloc_pages);
  3613. if (!max_reclaim)
  3614. goto skip_async;
  3615. if (max_reclaim <= nr_pages)
  3616. max_reclaim = 0;
  3617. else
  3618. max_reclaim -= nr_pages;
  3619. wait_event(root->fs_info->async_submit_wait,
  3620. atomic_read(&root->fs_info->async_delalloc_pages) <=
  3621. (int)max_reclaim);
  3622. skip_async:
  3623. if (!trans)
  3624. flush = BTRFS_RESERVE_FLUSH_ALL;
  3625. else
  3626. flush = BTRFS_RESERVE_NO_FLUSH;
  3627. spin_lock(&space_info->lock);
  3628. if (can_overcommit(root, space_info, orig, flush)) {
  3629. spin_unlock(&space_info->lock);
  3630. break;
  3631. }
  3632. spin_unlock(&space_info->lock);
  3633. loops++;
  3634. if (wait_ordered && !trans) {
  3635. btrfs_wait_ordered_roots(root->fs_info, items);
  3636. } else {
  3637. time_left = schedule_timeout_killable(1);
  3638. if (time_left)
  3639. break;
  3640. }
  3641. delalloc_bytes = percpu_counter_sum_positive(
  3642. &root->fs_info->delalloc_bytes);
  3643. }
  3644. }
  3645. /**
  3646. * maybe_commit_transaction - possibly commit the transaction if its ok to
  3647. * @root - the root we're allocating for
  3648. * @bytes - the number of bytes we want to reserve
  3649. * @force - force the commit
  3650. *
  3651. * This will check to make sure that committing the transaction will actually
  3652. * get us somewhere and then commit the transaction if it does. Otherwise it
  3653. * will return -ENOSPC.
  3654. */
  3655. static int may_commit_transaction(struct btrfs_root *root,
  3656. struct btrfs_space_info *space_info,
  3657. u64 bytes, int force)
  3658. {
  3659. struct btrfs_block_rsv *delayed_rsv = &root->fs_info->delayed_block_rsv;
  3660. struct btrfs_trans_handle *trans;
  3661. trans = (struct btrfs_trans_handle *)current->journal_info;
  3662. if (trans)
  3663. return -EAGAIN;
  3664. if (force)
  3665. goto commit;
  3666. /* See if there is enough pinned space to make this reservation */
  3667. if (percpu_counter_compare(&space_info->total_bytes_pinned,
  3668. bytes) >= 0)
  3669. goto commit;
  3670. /*
  3671. * See if there is some space in the delayed insertion reservation for
  3672. * this reservation.
  3673. */
  3674. if (space_info != delayed_rsv->space_info)
  3675. return -ENOSPC;
  3676. spin_lock(&delayed_rsv->lock);
  3677. if (percpu_counter_compare(&space_info->total_bytes_pinned,
  3678. bytes - delayed_rsv->size) >= 0) {
  3679. spin_unlock(&delayed_rsv->lock);
  3680. return -ENOSPC;
  3681. }
  3682. spin_unlock(&delayed_rsv->lock);
  3683. commit:
  3684. trans = btrfs_join_transaction(root);
  3685. if (IS_ERR(trans))
  3686. return -ENOSPC;
  3687. return btrfs_commit_transaction(trans, root);
  3688. }
  3689. enum flush_state {
  3690. FLUSH_DELAYED_ITEMS_NR = 1,
  3691. FLUSH_DELAYED_ITEMS = 2,
  3692. FLUSH_DELALLOC = 3,
  3693. FLUSH_DELALLOC_WAIT = 4,
  3694. ALLOC_CHUNK = 5,
  3695. COMMIT_TRANS = 6,
  3696. };
  3697. static int flush_space(struct btrfs_root *root,
  3698. struct btrfs_space_info *space_info, u64 num_bytes,
  3699. u64 orig_bytes, int state)
  3700. {
  3701. struct btrfs_trans_handle *trans;
  3702. int nr;
  3703. int ret = 0;
  3704. switch (state) {
  3705. case FLUSH_DELAYED_ITEMS_NR:
  3706. case FLUSH_DELAYED_ITEMS:
  3707. if (state == FLUSH_DELAYED_ITEMS_NR)
  3708. nr = calc_reclaim_items_nr(root, num_bytes) * 2;
  3709. else
  3710. nr = -1;
  3711. trans = btrfs_join_transaction(root);
  3712. if (IS_ERR(trans)) {
  3713. ret = PTR_ERR(trans);
  3714. break;
  3715. }
  3716. ret = btrfs_run_delayed_items_nr(trans, root, nr);
  3717. btrfs_end_transaction(trans, root);
  3718. break;
  3719. case FLUSH_DELALLOC:
  3720. case FLUSH_DELALLOC_WAIT:
  3721. shrink_delalloc(root, num_bytes * 2, orig_bytes,
  3722. state == FLUSH_DELALLOC_WAIT);
  3723. break;
  3724. case ALLOC_CHUNK:
  3725. trans = btrfs_join_transaction(root);
  3726. if (IS_ERR(trans)) {
  3727. ret = PTR_ERR(trans);
  3728. break;
  3729. }
  3730. ret = do_chunk_alloc(trans, root->fs_info->extent_root,
  3731. btrfs_get_alloc_profile(root, 0),
  3732. CHUNK_ALLOC_NO_FORCE);
  3733. btrfs_end_transaction(trans, root);
  3734. if (ret == -ENOSPC)
  3735. ret = 0;
  3736. break;
  3737. case COMMIT_TRANS:
  3738. ret = may_commit_transaction(root, space_info, orig_bytes, 0);
  3739. break;
  3740. default:
  3741. ret = -ENOSPC;
  3742. break;
  3743. }
  3744. return ret;
  3745. }
  3746. static inline u64
  3747. btrfs_calc_reclaim_metadata_size(struct btrfs_root *root,
  3748. struct btrfs_space_info *space_info)
  3749. {
  3750. u64 used;
  3751. u64 expected;
  3752. u64 to_reclaim;
  3753. to_reclaim = min_t(u64, num_online_cpus() * 1024 * 1024,
  3754. 16 * 1024 * 1024);
  3755. spin_lock(&space_info->lock);
  3756. if (can_overcommit(root, space_info, to_reclaim,
  3757. BTRFS_RESERVE_FLUSH_ALL)) {
  3758. to_reclaim = 0;
  3759. goto out;
  3760. }
  3761. used = space_info->bytes_used + space_info->bytes_reserved +
  3762. space_info->bytes_pinned + space_info->bytes_readonly +
  3763. space_info->bytes_may_use;
  3764. if (can_overcommit(root, space_info, 1024 * 1024,
  3765. BTRFS_RESERVE_FLUSH_ALL))
  3766. expected = div_factor_fine(space_info->total_bytes, 95);
  3767. else
  3768. expected = div_factor_fine(space_info->total_bytes, 90);
  3769. if (used > expected)
  3770. to_reclaim = used - expected;
  3771. else
  3772. to_reclaim = 0;
  3773. to_reclaim = min(to_reclaim, space_info->bytes_may_use +
  3774. space_info->bytes_reserved);
  3775. out:
  3776. spin_unlock(&space_info->lock);
  3777. return to_reclaim;
  3778. }
  3779. static inline int need_do_async_reclaim(struct btrfs_space_info *space_info,
  3780. struct btrfs_fs_info *fs_info, u64 used)
  3781. {
  3782. return (used >= div_factor_fine(space_info->total_bytes, 98) &&
  3783. !btrfs_fs_closing(fs_info) &&
  3784. !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
  3785. }
  3786. static int btrfs_need_do_async_reclaim(struct btrfs_space_info *space_info,
  3787. struct btrfs_fs_info *fs_info,
  3788. int flush_state)
  3789. {
  3790. u64 used;
  3791. spin_lock(&space_info->lock);
  3792. /*
  3793. * We run out of space and have not got any free space via flush_space,
  3794. * so don't bother doing async reclaim.
  3795. */
  3796. if (flush_state > COMMIT_TRANS && space_info->full) {
  3797. spin_unlock(&space_info->lock);
  3798. return 0;
  3799. }
  3800. used = space_info->bytes_used + space_info->bytes_reserved +
  3801. space_info->bytes_pinned + space_info->bytes_readonly +
  3802. space_info->bytes_may_use;
  3803. if (need_do_async_reclaim(space_info, fs_info, used)) {
  3804. spin_unlock(&space_info->lock);
  3805. return 1;
  3806. }
  3807. spin_unlock(&space_info->lock);
  3808. return 0;
  3809. }
  3810. static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
  3811. {
  3812. struct btrfs_fs_info *fs_info;
  3813. struct btrfs_space_info *space_info;
  3814. u64 to_reclaim;
  3815. int flush_state;
  3816. fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
  3817. space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
  3818. to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
  3819. space_info);
  3820. if (!to_reclaim)
  3821. return;
  3822. flush_state = FLUSH_DELAYED_ITEMS_NR;
  3823. do {
  3824. flush_space(fs_info->fs_root, space_info, to_reclaim,
  3825. to_reclaim, flush_state);
  3826. flush_state++;
  3827. if (!btrfs_need_do_async_reclaim(space_info, fs_info,
  3828. flush_state))
  3829. return;
  3830. } while (flush_state <= COMMIT_TRANS);
  3831. if (btrfs_need_do_async_reclaim(space_info, fs_info, flush_state))
  3832. queue_work(system_unbound_wq, work);
  3833. }
  3834. void btrfs_init_async_reclaim_work(struct work_struct *work)
  3835. {
  3836. INIT_WORK(work, btrfs_async_reclaim_metadata_space);
  3837. }
  3838. /**
  3839. * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
  3840. * @root - the root we're allocating for
  3841. * @block_rsv - the block_rsv we're allocating for
  3842. * @orig_bytes - the number of bytes we want
  3843. * @flush - whether or not we can flush to make our reservation
  3844. *
  3845. * This will reserve orgi_bytes number of bytes from the space info associated
  3846. * with the block_rsv. If there is not enough space it will make an attempt to
  3847. * flush out space to make room. It will do this by flushing delalloc if
  3848. * possible or committing the transaction. If flush is 0 then no attempts to
  3849. * regain reservations will be made and this will fail if there is not enough
  3850. * space already.
  3851. */
  3852. static int reserve_metadata_bytes(struct btrfs_root *root,
  3853. struct btrfs_block_rsv *block_rsv,
  3854. u64 orig_bytes,
  3855. enum btrfs_reserve_flush_enum flush)
  3856. {
  3857. struct btrfs_space_info *space_info = block_rsv->space_info;
  3858. u64 used;
  3859. u64 num_bytes = orig_bytes;
  3860. int flush_state = FLUSH_DELAYED_ITEMS_NR;
  3861. int ret = 0;
  3862. bool flushing = false;
  3863. again:
  3864. ret = 0;
  3865. spin_lock(&space_info->lock);
  3866. /*
  3867. * We only want to wait if somebody other than us is flushing and we
  3868. * are actually allowed to flush all things.
  3869. */
  3870. while (flush == BTRFS_RESERVE_FLUSH_ALL && !flushing &&
  3871. space_info->flush) {
  3872. spin_unlock(&space_info->lock);
  3873. /*
  3874. * If we have a trans handle we can't wait because the flusher
  3875. * may have to commit the transaction, which would mean we would
  3876. * deadlock since we are waiting for the flusher to finish, but
  3877. * hold the current transaction open.
  3878. */
  3879. if (current->journal_info)
  3880. return -EAGAIN;
  3881. ret = wait_event_killable(space_info->wait, !space_info->flush);
  3882. /* Must have been killed, return */
  3883. if (ret)
  3884. return -EINTR;
  3885. spin_lock(&space_info->lock);
  3886. }
  3887. ret = -ENOSPC;
  3888. used = space_info->bytes_used + space_info->bytes_reserved +
  3889. space_info->bytes_pinned + space_info->bytes_readonly +
  3890. space_info->bytes_may_use;
  3891. /*
  3892. * The idea here is that we've not already over-reserved the block group
  3893. * then we can go ahead and save our reservation first and then start
  3894. * flushing if we need to. Otherwise if we've already overcommitted
  3895. * lets start flushing stuff first and then come back and try to make
  3896. * our reservation.
  3897. */
  3898. if (used <= space_info->total_bytes) {
  3899. if (used + orig_bytes <= space_info->total_bytes) {
  3900. space_info->bytes_may_use += orig_bytes;
  3901. trace_btrfs_space_reservation(root->fs_info,
  3902. "space_info", space_info->flags, orig_bytes, 1);
  3903. ret = 0;
  3904. } else {
  3905. /*
  3906. * Ok set num_bytes to orig_bytes since we aren't
  3907. * overocmmitted, this way we only try and reclaim what
  3908. * we need.
  3909. */
  3910. num_bytes = orig_bytes;
  3911. }
  3912. } else {
  3913. /*
  3914. * Ok we're over committed, set num_bytes to the overcommitted
  3915. * amount plus the amount of bytes that we need for this
  3916. * reservation.
  3917. */
  3918. num_bytes = used - space_info->total_bytes +
  3919. (orig_bytes * 2);
  3920. }
  3921. if (ret && can_overcommit(root, space_info, orig_bytes, flush)) {
  3922. space_info->bytes_may_use += orig_bytes;
  3923. trace_btrfs_space_reservation(root->fs_info, "space_info",
  3924. space_info->flags, orig_bytes,
  3925. 1);
  3926. ret = 0;
  3927. }
  3928. /*
  3929. * Couldn't make our reservation, save our place so while we're trying
  3930. * to reclaim space we can actually use it instead of somebody else
  3931. * stealing it from us.
  3932. *
  3933. * We make the other tasks wait for the flush only when we can flush
  3934. * all things.
  3935. */
  3936. if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
  3937. flushing = true;
  3938. space_info->flush = 1;
  3939. } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
  3940. used += orig_bytes;
  3941. /*
  3942. * We will do the space reservation dance during log replay,
  3943. * which means we won't have fs_info->fs_root set, so don't do
  3944. * the async reclaim as we will panic.
  3945. */
  3946. if (!root->fs_info->log_root_recovering &&
  3947. need_do_async_reclaim(space_info, root->fs_info, used) &&
  3948. !work_busy(&root->fs_info->async_reclaim_work))
  3949. queue_work(system_unbound_wq,
  3950. &root->fs_info->async_reclaim_work);
  3951. }
  3952. spin_unlock(&space_info->lock);
  3953. if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
  3954. goto out;
  3955. ret = flush_space(root, space_info, num_bytes, orig_bytes,
  3956. flush_state);
  3957. flush_state++;
  3958. /*
  3959. * If we are FLUSH_LIMIT, we can not flush delalloc, or the deadlock
  3960. * would happen. So skip delalloc flush.
  3961. */
  3962. if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
  3963. (flush_state == FLUSH_DELALLOC ||
  3964. flush_state == FLUSH_DELALLOC_WAIT))
  3965. flush_state = ALLOC_CHUNK;
  3966. if (!ret)
  3967. goto again;
  3968. else if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
  3969. flush_state < COMMIT_TRANS)
  3970. goto again;
  3971. else if (flush == BTRFS_RESERVE_FLUSH_ALL &&
  3972. flush_state <= COMMIT_TRANS)
  3973. goto again;
  3974. out:
  3975. if (ret == -ENOSPC &&
  3976. unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
  3977. struct btrfs_block_rsv *global_rsv =
  3978. &root->fs_info->global_block_rsv;
  3979. if (block_rsv != global_rsv &&
  3980. !block_rsv_use_bytes(global_rsv, orig_bytes))
  3981. ret = 0;
  3982. }
  3983. if (ret == -ENOSPC)
  3984. trace_btrfs_space_reservation(root->fs_info,
  3985. "space_info:enospc",
  3986. space_info->flags, orig_bytes, 1);
  3987. if (flushing) {
  3988. spin_lock(&space_info->lock);
  3989. space_info->flush = 0;
  3990. wake_up_all(&space_info->wait);
  3991. spin_unlock(&space_info->lock);
  3992. }
  3993. return ret;
  3994. }
  3995. static struct btrfs_block_rsv *get_block_rsv(
  3996. const struct btrfs_trans_handle *trans,
  3997. const struct btrfs_root *root)
  3998. {
  3999. struct btrfs_block_rsv *block_rsv = NULL;
  4000. if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
  4001. block_rsv = trans->block_rsv;
  4002. if (root == root->fs_info->csum_root && trans->adding_csums)
  4003. block_rsv = trans->block_rsv;
  4004. if (root == root->fs_info->uuid_root)
  4005. block_rsv = trans->block_rsv;
  4006. if (!block_rsv)
  4007. block_rsv = root->block_rsv;
  4008. if (!block_rsv)
  4009. block_rsv = &root->fs_info->empty_block_rsv;
  4010. return block_rsv;
  4011. }
  4012. static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
  4013. u64 num_bytes)
  4014. {
  4015. int ret = -ENOSPC;
  4016. spin_lock(&block_rsv->lock);
  4017. if (block_rsv->reserved >= num_bytes) {
  4018. block_rsv->reserved -= num_bytes;
  4019. if (block_rsv->reserved < block_rsv->size)
  4020. block_rsv->full = 0;
  4021. ret = 0;
  4022. }
  4023. spin_unlock(&block_rsv->lock);
  4024. return ret;
  4025. }
  4026. static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
  4027. u64 num_bytes, int update_size)
  4028. {
  4029. spin_lock(&block_rsv->lock);
  4030. block_rsv->reserved += num_bytes;
  4031. if (update_size)
  4032. block_rsv->size += num_bytes;
  4033. else if (block_rsv->reserved >= block_rsv->size)
  4034. block_rsv->full = 1;
  4035. spin_unlock(&block_rsv->lock);
  4036. }
  4037. int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
  4038. struct btrfs_block_rsv *dest, u64 num_bytes,
  4039. int min_factor)
  4040. {
  4041. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  4042. u64 min_bytes;
  4043. if (global_rsv->space_info != dest->space_info)
  4044. return -ENOSPC;
  4045. spin_lock(&global_rsv->lock);
  4046. min_bytes = div_factor(global_rsv->size, min_factor);
  4047. if (global_rsv->reserved < min_bytes + num_bytes) {
  4048. spin_unlock(&global_rsv->lock);
  4049. return -ENOSPC;
  4050. }
  4051. global_rsv->reserved -= num_bytes;
  4052. if (global_rsv->reserved < global_rsv->size)
  4053. global_rsv->full = 0;
  4054. spin_unlock(&global_rsv->lock);
  4055. block_rsv_add_bytes(dest, num_bytes, 1);
  4056. return 0;
  4057. }
  4058. static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
  4059. struct btrfs_block_rsv *block_rsv,
  4060. struct btrfs_block_rsv *dest, u64 num_bytes)
  4061. {
  4062. struct btrfs_space_info *space_info = block_rsv->space_info;
  4063. spin_lock(&block_rsv->lock);
  4064. if (num_bytes == (u64)-1)
  4065. num_bytes = block_rsv->size;
  4066. block_rsv->size -= num_bytes;
  4067. if (block_rsv->reserved >= block_rsv->size) {
  4068. num_bytes = block_rsv->reserved - block_rsv->size;
  4069. block_rsv->reserved = block_rsv->size;
  4070. block_rsv->full = 1;
  4071. } else {
  4072. num_bytes = 0;
  4073. }
  4074. spin_unlock(&block_rsv->lock);
  4075. if (num_bytes > 0) {
  4076. if (dest) {
  4077. spin_lock(&dest->lock);
  4078. if (!dest->full) {
  4079. u64 bytes_to_add;
  4080. bytes_to_add = dest->size - dest->reserved;
  4081. bytes_to_add = min(num_bytes, bytes_to_add);
  4082. dest->reserved += bytes_to_add;
  4083. if (dest->reserved >= dest->size)
  4084. dest->full = 1;
  4085. num_bytes -= bytes_to_add;
  4086. }
  4087. spin_unlock(&dest->lock);
  4088. }
  4089. if (num_bytes) {
  4090. spin_lock(&space_info->lock);
  4091. space_info->bytes_may_use -= num_bytes;
  4092. trace_btrfs_space_reservation(fs_info, "space_info",
  4093. space_info->flags, num_bytes, 0);
  4094. spin_unlock(&space_info->lock);
  4095. }
  4096. }
  4097. }
  4098. static int block_rsv_migrate_bytes(struct btrfs_block_rsv *src,
  4099. struct btrfs_block_rsv *dst, u64 num_bytes)
  4100. {
  4101. int ret;
  4102. ret = block_rsv_use_bytes(src, num_bytes);
  4103. if (ret)
  4104. return ret;
  4105. block_rsv_add_bytes(dst, num_bytes, 1);
  4106. return 0;
  4107. }
  4108. void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
  4109. {
  4110. memset(rsv, 0, sizeof(*rsv));
  4111. spin_lock_init(&rsv->lock);
  4112. rsv->type = type;
  4113. }
  4114. struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root,
  4115. unsigned short type)
  4116. {
  4117. struct btrfs_block_rsv *block_rsv;
  4118. struct btrfs_fs_info *fs_info = root->fs_info;
  4119. block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
  4120. if (!block_rsv)
  4121. return NULL;
  4122. btrfs_init_block_rsv(block_rsv, type);
  4123. block_rsv->space_info = __find_space_info(fs_info,
  4124. BTRFS_BLOCK_GROUP_METADATA);
  4125. return block_rsv;
  4126. }
  4127. void btrfs_free_block_rsv(struct btrfs_root *root,
  4128. struct btrfs_block_rsv *rsv)
  4129. {
  4130. if (!rsv)
  4131. return;
  4132. btrfs_block_rsv_release(root, rsv, (u64)-1);
  4133. kfree(rsv);
  4134. }
  4135. int btrfs_block_rsv_add(struct btrfs_root *root,
  4136. struct btrfs_block_rsv *block_rsv, u64 num_bytes,
  4137. enum btrfs_reserve_flush_enum flush)
  4138. {
  4139. int ret;
  4140. if (num_bytes == 0)
  4141. return 0;
  4142. ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
  4143. if (!ret) {
  4144. block_rsv_add_bytes(block_rsv, num_bytes, 1);
  4145. return 0;
  4146. }
  4147. return ret;
  4148. }
  4149. int btrfs_block_rsv_check(struct btrfs_root *root,
  4150. struct btrfs_block_rsv *block_rsv, int min_factor)
  4151. {
  4152. u64 num_bytes = 0;
  4153. int ret = -ENOSPC;
  4154. if (!block_rsv)
  4155. return 0;
  4156. spin_lock(&block_rsv->lock);
  4157. num_bytes = div_factor(block_rsv->size, min_factor);
  4158. if (block_rsv->reserved >= num_bytes)
  4159. ret = 0;
  4160. spin_unlock(&block_rsv->lock);
  4161. return ret;
  4162. }
  4163. int btrfs_block_rsv_refill(struct btrfs_root *root,
  4164. struct btrfs_block_rsv *block_rsv, u64 min_reserved,
  4165. enum btrfs_reserve_flush_enum flush)
  4166. {
  4167. u64 num_bytes = 0;
  4168. int ret = -ENOSPC;
  4169. if (!block_rsv)
  4170. return 0;
  4171. spin_lock(&block_rsv->lock);
  4172. num_bytes = min_reserved;
  4173. if (block_rsv->reserved >= num_bytes)
  4174. ret = 0;
  4175. else
  4176. num_bytes -= block_rsv->reserved;
  4177. spin_unlock(&block_rsv->lock);
  4178. if (!ret)
  4179. return 0;
  4180. ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
  4181. if (!ret) {
  4182. block_rsv_add_bytes(block_rsv, num_bytes, 0);
  4183. return 0;
  4184. }
  4185. return ret;
  4186. }
  4187. int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src_rsv,
  4188. struct btrfs_block_rsv *dst_rsv,
  4189. u64 num_bytes)
  4190. {
  4191. return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
  4192. }
  4193. void btrfs_block_rsv_release(struct btrfs_root *root,
  4194. struct btrfs_block_rsv *block_rsv,
  4195. u64 num_bytes)
  4196. {
  4197. struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
  4198. if (global_rsv == block_rsv ||
  4199. block_rsv->space_info != global_rsv->space_info)
  4200. global_rsv = NULL;
  4201. block_rsv_release_bytes(root->fs_info, block_rsv, global_rsv,
  4202. num_bytes);
  4203. }
  4204. /*
  4205. * helper to calculate size of global block reservation.
  4206. * the desired value is sum of space used by extent tree,
  4207. * checksum tree and root tree
  4208. */
  4209. static u64 calc_global_metadata_size(struct btrfs_fs_info *fs_info)
  4210. {
  4211. struct btrfs_space_info *sinfo;
  4212. u64 num_bytes;
  4213. u64 meta_used;
  4214. u64 data_used;
  4215. int csum_size = btrfs_super_csum_size(fs_info->super_copy);
  4216. sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_DATA);
  4217. spin_lock(&sinfo->lock);
  4218. data_used = sinfo->bytes_used;
  4219. spin_unlock(&sinfo->lock);
  4220. sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
  4221. spin_lock(&sinfo->lock);
  4222. if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)
  4223. data_used = 0;
  4224. meta_used = sinfo->bytes_used;
  4225. spin_unlock(&sinfo->lock);
  4226. num_bytes = (data_used >> fs_info->sb->s_blocksize_bits) *
  4227. csum_size * 2;
  4228. num_bytes += div64_u64(data_used + meta_used, 50);
  4229. if (num_bytes * 3 > meta_used)
  4230. num_bytes = div64_u64(meta_used, 3);
  4231. return ALIGN(num_bytes, fs_info->extent_root->nodesize << 10);
  4232. }
  4233. static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
  4234. {
  4235. struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
  4236. struct btrfs_space_info *sinfo = block_rsv->space_info;
  4237. u64 num_bytes;
  4238. num_bytes = calc_global_metadata_size(fs_info);
  4239. spin_lock(&sinfo->lock);
  4240. spin_lock(&block_rsv->lock);
  4241. block_rsv->size = min_t(u64, num_bytes, 512 * 1024 * 1024);
  4242. num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
  4243. sinfo->bytes_reserved + sinfo->bytes_readonly +
  4244. sinfo->bytes_may_use;
  4245. if (sinfo->total_bytes > num_bytes) {
  4246. num_bytes = sinfo->total_bytes - num_bytes;
  4247. block_rsv->reserved += num_bytes;
  4248. sinfo->bytes_may_use += num_bytes;
  4249. trace_btrfs_space_reservation(fs_info, "space_info",
  4250. sinfo->flags, num_bytes, 1);
  4251. }
  4252. if (block_rsv->reserved >= block_rsv->size) {
  4253. num_bytes = block_rsv->reserved - block_rsv->size;
  4254. sinfo->bytes_may_use -= num_bytes;
  4255. trace_btrfs_space_reservation(fs_info, "space_info",
  4256. sinfo->flags, num_bytes, 0);
  4257. block_rsv->reserved = block_rsv->size;
  4258. block_rsv->full = 1;
  4259. }
  4260. spin_unlock(&block_rsv->lock);
  4261. spin_unlock(&sinfo->lock);
  4262. }
  4263. static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
  4264. {
  4265. struct btrfs_space_info *space_info;
  4266. space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
  4267. fs_info->chunk_block_rsv.space_info = space_info;
  4268. space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
  4269. fs_info->global_block_rsv.space_info = space_info;
  4270. fs_info->delalloc_block_rsv.space_info = space_info;
  4271. fs_info->trans_block_rsv.space_info = space_info;
  4272. fs_info->empty_block_rsv.space_info = space_info;
  4273. fs_info->delayed_block_rsv.space_info = space_info;
  4274. fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
  4275. fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
  4276. fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
  4277. fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
  4278. if (fs_info->quota_root)
  4279. fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
  4280. fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
  4281. update_global_block_rsv(fs_info);
  4282. }
  4283. static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
  4284. {
  4285. block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
  4286. (u64)-1);
  4287. WARN_ON(fs_info->delalloc_block_rsv.size > 0);
  4288. WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
  4289. WARN_ON(fs_info->trans_block_rsv.size > 0);
  4290. WARN_ON(fs_info->trans_block_rsv.reserved > 0);
  4291. WARN_ON(fs_info->chunk_block_rsv.size > 0);
  4292. WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
  4293. WARN_ON(fs_info->delayed_block_rsv.size > 0);
  4294. WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
  4295. }
  4296. void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
  4297. struct btrfs_root *root)
  4298. {
  4299. if (!trans->block_rsv)
  4300. return;
  4301. if (!trans->bytes_reserved)
  4302. return;
  4303. trace_btrfs_space_reservation(root->fs_info, "transaction",
  4304. trans->transid, trans->bytes_reserved, 0);
  4305. btrfs_block_rsv_release(root, trans->block_rsv, trans->bytes_reserved);
  4306. trans->bytes_reserved = 0;
  4307. }
  4308. /* Can only return 0 or -ENOSPC */
  4309. int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
  4310. struct inode *inode)
  4311. {
  4312. struct btrfs_root *root = BTRFS_I(inode)->root;
  4313. struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
  4314. struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
  4315. /*
  4316. * We need to hold space in order to delete our orphan item once we've
  4317. * added it, so this takes the reservation so we can release it later
  4318. * when we are truly done with the orphan item.
  4319. */
  4320. u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
  4321. trace_btrfs_space_reservation(root->fs_info, "orphan",
  4322. btrfs_ino(inode), num_bytes, 1);
  4323. return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
  4324. }
  4325. void btrfs_orphan_release_metadata(struct inode *inode)
  4326. {
  4327. struct btrfs_root *root = BTRFS_I(inode)->root;
  4328. u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
  4329. trace_btrfs_space_reservation(root->fs_info, "orphan",
  4330. btrfs_ino(inode), num_bytes, 0);
  4331. btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
  4332. }
  4333. /*
  4334. * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
  4335. * root: the root of the parent directory
  4336. * rsv: block reservation
  4337. * items: the number of items that we need do reservation
  4338. * qgroup_reserved: used to return the reserved size in qgroup
  4339. *
  4340. * This function is used to reserve the space for snapshot/subvolume
  4341. * creation and deletion. Those operations are different with the
  4342. * common file/directory operations, they change two fs/file trees
  4343. * and root tree, the number of items that the qgroup reserves is
  4344. * different with the free space reservation. So we can not use
  4345. * the space reseravtion mechanism in start_transaction().
  4346. */
  4347. int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
  4348. struct btrfs_block_rsv *rsv,
  4349. int items,
  4350. u64 *qgroup_reserved,
  4351. bool use_global_rsv)
  4352. {
  4353. u64 num_bytes;
  4354. int ret;
  4355. struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
  4356. if (root->fs_info->quota_enabled) {
  4357. /* One for parent inode, two for dir entries */
  4358. num_bytes = 3 * root->nodesize;
  4359. ret = btrfs_qgroup_reserve(root, num_bytes);
  4360. if (ret)
  4361. return ret;
  4362. } else {
  4363. num_bytes = 0;
  4364. }
  4365. *qgroup_reserved = num_bytes;
  4366. num_bytes = btrfs_calc_trans_metadata_size(root, items);
  4367. rsv->space_info = __find_space_info(root->fs_info,
  4368. BTRFS_BLOCK_GROUP_METADATA);
  4369. ret = btrfs_block_rsv_add(root, rsv, num_bytes,
  4370. BTRFS_RESERVE_FLUSH_ALL);
  4371. if (ret == -ENOSPC && use_global_rsv)
  4372. ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes);
  4373. if (ret) {
  4374. if (*qgroup_reserved)
  4375. btrfs_qgroup_free(root, *qgroup_reserved);
  4376. }
  4377. return ret;
  4378. }
  4379. void btrfs_subvolume_release_metadata(struct btrfs_root *root,
  4380. struct btrfs_block_rsv *rsv,
  4381. u64 qgroup_reserved)
  4382. {
  4383. btrfs_block_rsv_release(root, rsv, (u64)-1);
  4384. if (qgroup_reserved)
  4385. btrfs_qgroup_free(root, qgroup_reserved);
  4386. }
  4387. /**
  4388. * drop_outstanding_extent - drop an outstanding extent
  4389. * @inode: the inode we're dropping the extent for
  4390. * @num_bytes: the number of bytes we're relaseing.
  4391. *
  4392. * This is called when we are freeing up an outstanding extent, either called
  4393. * after an error or after an extent is written. This will return the number of
  4394. * reserved extents that need to be freed. This must be called with
  4395. * BTRFS_I(inode)->lock held.
  4396. */
  4397. static unsigned drop_outstanding_extent(struct inode *inode, u64 num_bytes)
  4398. {
  4399. unsigned drop_inode_space = 0;
  4400. unsigned dropped_extents = 0;
  4401. unsigned num_extents = 0;
  4402. num_extents = (unsigned)div64_u64(num_bytes +
  4403. BTRFS_MAX_EXTENT_SIZE - 1,
  4404. BTRFS_MAX_EXTENT_SIZE);
  4405. ASSERT(num_extents);
  4406. ASSERT(BTRFS_I(inode)->outstanding_extents >= num_extents);
  4407. BTRFS_I(inode)->outstanding_extents -= num_extents;
  4408. if (BTRFS_I(inode)->outstanding_extents == 0 &&
  4409. test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
  4410. &BTRFS_I(inode)->runtime_flags))
  4411. drop_inode_space = 1;
  4412. /*
  4413. * If we have more or the same amount of outsanding extents than we have
  4414. * reserved then we need to leave the reserved extents count alone.
  4415. */
  4416. if (BTRFS_I(inode)->outstanding_extents >=
  4417. BTRFS_I(inode)->reserved_extents)
  4418. return drop_inode_space;
  4419. dropped_extents = BTRFS_I(inode)->reserved_extents -
  4420. BTRFS_I(inode)->outstanding_extents;
  4421. BTRFS_I(inode)->reserved_extents -= dropped_extents;
  4422. return dropped_extents + drop_inode_space;
  4423. }
  4424. /**
  4425. * calc_csum_metadata_size - return the amount of metada space that must be
  4426. * reserved/free'd for the given bytes.
  4427. * @inode: the inode we're manipulating
  4428. * @num_bytes: the number of bytes in question
  4429. * @reserve: 1 if we are reserving space, 0 if we are freeing space
  4430. *
  4431. * This adjusts the number of csum_bytes in the inode and then returns the
  4432. * correct amount of metadata that must either be reserved or freed. We
  4433. * calculate how many checksums we can fit into one leaf and then divide the
  4434. * number of bytes that will need to be checksumed by this value to figure out
  4435. * how many checksums will be required. If we are adding bytes then the number
  4436. * may go up and we will return the number of additional bytes that must be
  4437. * reserved. If it is going down we will return the number of bytes that must
  4438. * be freed.
  4439. *
  4440. * This must be called with BTRFS_I(inode)->lock held.
  4441. */
  4442. static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
  4443. int reserve)
  4444. {
  4445. struct btrfs_root *root = BTRFS_I(inode)->root;
  4446. u64 csum_size;
  4447. int num_csums_per_leaf;
  4448. int num_csums;
  4449. int old_csums;
  4450. if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
  4451. BTRFS_I(inode)->csum_bytes == 0)
  4452. return 0;
  4453. old_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
  4454. if (reserve)
  4455. BTRFS_I(inode)->csum_bytes += num_bytes;
  4456. else
  4457. BTRFS_I(inode)->csum_bytes -= num_bytes;
  4458. csum_size = BTRFS_LEAF_DATA_SIZE(root) - sizeof(struct btrfs_item);
  4459. num_csums_per_leaf = (int)div64_u64(csum_size,
  4460. sizeof(struct btrfs_csum_item) +
  4461. sizeof(struct btrfs_disk_key));
  4462. num_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
  4463. num_csums = num_csums + num_csums_per_leaf - 1;
  4464. num_csums = num_csums / num_csums_per_leaf;
  4465. old_csums = old_csums + num_csums_per_leaf - 1;
  4466. old_csums = old_csums / num_csums_per_leaf;
  4467. /* No change, no need to reserve more */
  4468. if (old_csums == num_csums)
  4469. return 0;
  4470. if (reserve)
  4471. return btrfs_calc_trans_metadata_size(root,
  4472. num_csums - old_csums);
  4473. return btrfs_calc_trans_metadata_size(root, old_csums - num_csums);
  4474. }
  4475. int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
  4476. {
  4477. struct btrfs_root *root = BTRFS_I(inode)->root;
  4478. struct btrfs_block_rsv *block_rsv = &root->fs_info->delalloc_block_rsv;
  4479. u64 to_reserve = 0;
  4480. u64 csum_bytes;
  4481. unsigned nr_extents = 0;
  4482. int extra_reserve = 0;
  4483. enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
  4484. int ret = 0;
  4485. bool delalloc_lock = true;
  4486. u64 to_free = 0;
  4487. unsigned dropped;
  4488. /* If we are a free space inode we need to not flush since we will be in
  4489. * the middle of a transaction commit. We also don't need the delalloc
  4490. * mutex since we won't race with anybody. We need this mostly to make
  4491. * lockdep shut its filthy mouth.
  4492. */
  4493. if (btrfs_is_free_space_inode(inode)) {
  4494. flush = BTRFS_RESERVE_NO_FLUSH;
  4495. delalloc_lock = false;
  4496. }
  4497. if (flush != BTRFS_RESERVE_NO_FLUSH &&
  4498. btrfs_transaction_in_commit(root->fs_info))
  4499. schedule_timeout(1);
  4500. if (delalloc_lock)
  4501. mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
  4502. num_bytes = ALIGN(num_bytes, root->sectorsize);
  4503. spin_lock(&BTRFS_I(inode)->lock);
  4504. BTRFS_I(inode)->outstanding_extents++;
  4505. if (BTRFS_I(inode)->outstanding_extents >
  4506. BTRFS_I(inode)->reserved_extents)
  4507. nr_extents = BTRFS_I(inode)->outstanding_extents -
  4508. BTRFS_I(inode)->reserved_extents;
  4509. /*
  4510. * Add an item to reserve for updating the inode when we complete the
  4511. * delalloc io.
  4512. */
  4513. if (!test_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
  4514. &BTRFS_I(inode)->runtime_flags)) {
  4515. nr_extents++;
  4516. extra_reserve = 1;
  4517. }
  4518. to_reserve = btrfs_calc_trans_metadata_size(root, nr_extents);
  4519. to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
  4520. csum_bytes = BTRFS_I(inode)->csum_bytes;
  4521. spin_unlock(&BTRFS_I(inode)->lock);
  4522. if (root->fs_info->quota_enabled) {
  4523. ret = btrfs_qgroup_reserve(root, num_bytes +
  4524. nr_extents * root->nodesize);
  4525. if (ret)
  4526. goto out_fail;
  4527. }
  4528. ret = reserve_metadata_bytes(root, block_rsv, to_reserve, flush);
  4529. if (unlikely(ret)) {
  4530. if (root->fs_info->quota_enabled)
  4531. btrfs_qgroup_free(root, num_bytes +
  4532. nr_extents * root->nodesize);
  4533. goto out_fail;
  4534. }
  4535. spin_lock(&BTRFS_I(inode)->lock);
  4536. if (extra_reserve) {
  4537. set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
  4538. &BTRFS_I(inode)->runtime_flags);
  4539. nr_extents--;
  4540. }
  4541. BTRFS_I(inode)->reserved_extents += nr_extents;
  4542. spin_unlock(&BTRFS_I(inode)->lock);
  4543. if (delalloc_lock)
  4544. mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
  4545. if (to_reserve)
  4546. trace_btrfs_space_reservation(root->fs_info, "delalloc",
  4547. btrfs_ino(inode), to_reserve, 1);
  4548. block_rsv_add_bytes(block_rsv, to_reserve, 1);
  4549. return 0;
  4550. out_fail:
  4551. spin_lock(&BTRFS_I(inode)->lock);
  4552. dropped = drop_outstanding_extent(inode, num_bytes);
  4553. /*
  4554. * If the inodes csum_bytes is the same as the original
  4555. * csum_bytes then we know we haven't raced with any free()ers
  4556. * so we can just reduce our inodes csum bytes and carry on.
  4557. */
  4558. if (BTRFS_I(inode)->csum_bytes == csum_bytes) {
  4559. calc_csum_metadata_size(inode, num_bytes, 0);
  4560. } else {
  4561. u64 orig_csum_bytes = BTRFS_I(inode)->csum_bytes;
  4562. u64 bytes;
  4563. /*
  4564. * This is tricky, but first we need to figure out how much we
  4565. * free'd from any free-ers that occured during this
  4566. * reservation, so we reset ->csum_bytes to the csum_bytes
  4567. * before we dropped our lock, and then call the free for the
  4568. * number of bytes that were freed while we were trying our
  4569. * reservation.
  4570. */
  4571. bytes = csum_bytes - BTRFS_I(inode)->csum_bytes;
  4572. BTRFS_I(inode)->csum_bytes = csum_bytes;
  4573. to_free = calc_csum_metadata_size(inode, bytes, 0);
  4574. /*
  4575. * Now we need to see how much we would have freed had we not
  4576. * been making this reservation and our ->csum_bytes were not
  4577. * artificially inflated.
  4578. */
  4579. BTRFS_I(inode)->csum_bytes = csum_bytes - num_bytes;
  4580. bytes = csum_bytes - orig_csum_bytes;
  4581. bytes = calc_csum_metadata_size(inode, bytes, 0);
  4582. /*
  4583. * Now reset ->csum_bytes to what it should be. If bytes is
  4584. * more than to_free then we would have free'd more space had we
  4585. * not had an artificially high ->csum_bytes, so we need to free
  4586. * the remainder. If bytes is the same or less then we don't
  4587. * need to do anything, the other free-ers did the correct
  4588. * thing.
  4589. */
  4590. BTRFS_I(inode)->csum_bytes = orig_csum_bytes - num_bytes;
  4591. if (bytes > to_free)
  4592. to_free = bytes - to_free;
  4593. else
  4594. to_free = 0;
  4595. }
  4596. spin_unlock(&BTRFS_I(inode)->lock);
  4597. if (dropped)
  4598. to_free += btrfs_calc_trans_metadata_size(root, dropped);
  4599. if (to_free) {
  4600. btrfs_block_rsv_release(root, block_rsv, to_free);
  4601. trace_btrfs_space_reservation(root->fs_info, "delalloc",
  4602. btrfs_ino(inode), to_free, 0);
  4603. }
  4604. if (delalloc_lock)
  4605. mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
  4606. return ret;
  4607. }
  4608. /**
  4609. * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
  4610. * @inode: the inode to release the reservation for
  4611. * @num_bytes: the number of bytes we're releasing
  4612. *
  4613. * This will release the metadata reservation for an inode. This can be called
  4614. * once we complete IO for a given set of bytes to release their metadata
  4615. * reservations.
  4616. */
  4617. void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
  4618. {
  4619. struct btrfs_root *root = BTRFS_I(inode)->root;
  4620. u64 to_free = 0;
  4621. unsigned dropped;
  4622. num_bytes = ALIGN(num_bytes, root->sectorsize);
  4623. spin_lock(&BTRFS_I(inode)->lock);
  4624. dropped = drop_outstanding_extent(inode, num_bytes);
  4625. if (num_bytes)
  4626. to_free = calc_csum_metadata_size(inode, num_bytes, 0);
  4627. spin_unlock(&BTRFS_I(inode)->lock);
  4628. if (dropped > 0)
  4629. to_free += btrfs_calc_trans_metadata_size(root, dropped);
  4630. trace_btrfs_space_reservation(root->fs_info, "delalloc",
  4631. btrfs_ino(inode), to_free, 0);
  4632. if (root->fs_info->quota_enabled) {
  4633. btrfs_qgroup_free(root, num_bytes +
  4634. dropped * root->nodesize);
  4635. }
  4636. btrfs_block_rsv_release(root, &root->fs_info->delalloc_block_rsv,
  4637. to_free);
  4638. }
  4639. /**
  4640. * btrfs_delalloc_reserve_space - reserve data and metadata space for delalloc
  4641. * @inode: inode we're writing to
  4642. * @num_bytes: the number of bytes we want to allocate
  4643. *
  4644. * This will do the following things
  4645. *
  4646. * o reserve space in the data space info for num_bytes
  4647. * o reserve space in the metadata space info based on number of outstanding
  4648. * extents and how much csums will be needed
  4649. * o add to the inodes ->delalloc_bytes
  4650. * o add it to the fs_info's delalloc inodes list.
  4651. *
  4652. * This will return 0 for success and -ENOSPC if there is no space left.
  4653. */
  4654. int btrfs_delalloc_reserve_space(struct inode *inode, u64 num_bytes)
  4655. {
  4656. int ret;
  4657. ret = btrfs_check_data_free_space(inode, num_bytes);
  4658. if (ret)
  4659. return ret;
  4660. ret = btrfs_delalloc_reserve_metadata(inode, num_bytes);
  4661. if (ret) {
  4662. btrfs_free_reserved_data_space(inode, num_bytes);
  4663. return ret;
  4664. }
  4665. return 0;
  4666. }
  4667. /**
  4668. * btrfs_delalloc_release_space - release data and metadata space for delalloc
  4669. * @inode: inode we're releasing space for
  4670. * @num_bytes: the number of bytes we want to free up
  4671. *
  4672. * This must be matched with a call to btrfs_delalloc_reserve_space. This is
  4673. * called in the case that we don't need the metadata AND data reservations
  4674. * anymore. So if there is an error or we insert an inline extent.
  4675. *
  4676. * This function will release the metadata space that was not used and will
  4677. * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
  4678. * list if there are no delalloc bytes left.
  4679. */
  4680. void btrfs_delalloc_release_space(struct inode *inode, u64 num_bytes)
  4681. {
  4682. btrfs_delalloc_release_metadata(inode, num_bytes);
  4683. btrfs_free_reserved_data_space(inode, num_bytes);
  4684. }
  4685. static int update_block_group(struct btrfs_trans_handle *trans,
  4686. struct btrfs_root *root, u64 bytenr,
  4687. u64 num_bytes, int alloc)
  4688. {
  4689. struct btrfs_block_group_cache *cache = NULL;
  4690. struct btrfs_fs_info *info = root->fs_info;
  4691. u64 total = num_bytes;
  4692. u64 old_val;
  4693. u64 byte_in_group;
  4694. int factor;
  4695. /* block accounting for super block */
  4696. spin_lock(&info->delalloc_root_lock);
  4697. old_val = btrfs_super_bytes_used(info->super_copy);
  4698. if (alloc)
  4699. old_val += num_bytes;
  4700. else
  4701. old_val -= num_bytes;
  4702. btrfs_set_super_bytes_used(info->super_copy, old_val);
  4703. spin_unlock(&info->delalloc_root_lock);
  4704. while (total) {
  4705. cache = btrfs_lookup_block_group(info, bytenr);
  4706. if (!cache)
  4707. return -ENOENT;
  4708. if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
  4709. BTRFS_BLOCK_GROUP_RAID1 |
  4710. BTRFS_BLOCK_GROUP_RAID10))
  4711. factor = 2;
  4712. else
  4713. factor = 1;
  4714. /*
  4715. * If this block group has free space cache written out, we
  4716. * need to make sure to load it if we are removing space. This
  4717. * is because we need the unpinning stage to actually add the
  4718. * space back to the block group, otherwise we will leak space.
  4719. */
  4720. if (!alloc && cache->cached == BTRFS_CACHE_NO)
  4721. cache_block_group(cache, 1);
  4722. spin_lock(&trans->transaction->dirty_bgs_lock);
  4723. if (list_empty(&cache->dirty_list)) {
  4724. list_add_tail(&cache->dirty_list,
  4725. &trans->transaction->dirty_bgs);
  4726. btrfs_get_block_group(cache);
  4727. }
  4728. spin_unlock(&trans->transaction->dirty_bgs_lock);
  4729. byte_in_group = bytenr - cache->key.objectid;
  4730. WARN_ON(byte_in_group > cache->key.offset);
  4731. spin_lock(&cache->space_info->lock);
  4732. spin_lock(&cache->lock);
  4733. if (btrfs_test_opt(root, SPACE_CACHE) &&
  4734. cache->disk_cache_state < BTRFS_DC_CLEAR)
  4735. cache->disk_cache_state = BTRFS_DC_CLEAR;
  4736. old_val = btrfs_block_group_used(&cache->item);
  4737. num_bytes = min(total, cache->key.offset - byte_in_group);
  4738. if (alloc) {
  4739. old_val += num_bytes;
  4740. btrfs_set_block_group_used(&cache->item, old_val);
  4741. cache->reserved -= num_bytes;
  4742. cache->space_info->bytes_reserved -= num_bytes;
  4743. cache->space_info->bytes_used += num_bytes;
  4744. cache->space_info->disk_used += num_bytes * factor;
  4745. spin_unlock(&cache->lock);
  4746. spin_unlock(&cache->space_info->lock);
  4747. } else {
  4748. old_val -= num_bytes;
  4749. btrfs_set_block_group_used(&cache->item, old_val);
  4750. cache->pinned += num_bytes;
  4751. cache->space_info->bytes_pinned += num_bytes;
  4752. cache->space_info->bytes_used -= num_bytes;
  4753. cache->space_info->disk_used -= num_bytes * factor;
  4754. spin_unlock(&cache->lock);
  4755. spin_unlock(&cache->space_info->lock);
  4756. set_extent_dirty(info->pinned_extents,
  4757. bytenr, bytenr + num_bytes - 1,
  4758. GFP_NOFS | __GFP_NOFAIL);
  4759. /*
  4760. * No longer have used bytes in this block group, queue
  4761. * it for deletion.
  4762. */
  4763. if (old_val == 0) {
  4764. spin_lock(&info->unused_bgs_lock);
  4765. if (list_empty(&cache->bg_list)) {
  4766. btrfs_get_block_group(cache);
  4767. list_add_tail(&cache->bg_list,
  4768. &info->unused_bgs);
  4769. }
  4770. spin_unlock(&info->unused_bgs_lock);
  4771. }
  4772. }
  4773. btrfs_put_block_group(cache);
  4774. total -= num_bytes;
  4775. bytenr += num_bytes;
  4776. }
  4777. return 0;
  4778. }
  4779. static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
  4780. {
  4781. struct btrfs_block_group_cache *cache;
  4782. u64 bytenr;
  4783. spin_lock(&root->fs_info->block_group_cache_lock);
  4784. bytenr = root->fs_info->first_logical_byte;
  4785. spin_unlock(&root->fs_info->block_group_cache_lock);
  4786. if (bytenr < (u64)-1)
  4787. return bytenr;
  4788. cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
  4789. if (!cache)
  4790. return 0;
  4791. bytenr = cache->key.objectid;
  4792. btrfs_put_block_group(cache);
  4793. return bytenr;
  4794. }
  4795. static int pin_down_extent(struct btrfs_root *root,
  4796. struct btrfs_block_group_cache *cache,
  4797. u64 bytenr, u64 num_bytes, int reserved)
  4798. {
  4799. spin_lock(&cache->space_info->lock);
  4800. spin_lock(&cache->lock);
  4801. cache->pinned += num_bytes;
  4802. cache->space_info->bytes_pinned += num_bytes;
  4803. if (reserved) {
  4804. cache->reserved -= num_bytes;
  4805. cache->space_info->bytes_reserved -= num_bytes;
  4806. }
  4807. spin_unlock(&cache->lock);
  4808. spin_unlock(&cache->space_info->lock);
  4809. set_extent_dirty(root->fs_info->pinned_extents, bytenr,
  4810. bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
  4811. if (reserved)
  4812. trace_btrfs_reserved_extent_free(root, bytenr, num_bytes);
  4813. return 0;
  4814. }
  4815. /*
  4816. * this function must be called within transaction
  4817. */
  4818. int btrfs_pin_extent(struct btrfs_root *root,
  4819. u64 bytenr, u64 num_bytes, int reserved)
  4820. {
  4821. struct btrfs_block_group_cache *cache;
  4822. cache = btrfs_lookup_block_group(root->fs_info, bytenr);
  4823. BUG_ON(!cache); /* Logic error */
  4824. pin_down_extent(root, cache, bytenr, num_bytes, reserved);
  4825. btrfs_put_block_group(cache);
  4826. return 0;
  4827. }
  4828. /*
  4829. * this function must be called within transaction
  4830. */
  4831. int btrfs_pin_extent_for_log_replay(struct btrfs_root *root,
  4832. u64 bytenr, u64 num_bytes)
  4833. {
  4834. struct btrfs_block_group_cache *cache;
  4835. int ret;
  4836. cache = btrfs_lookup_block_group(root->fs_info, bytenr);
  4837. if (!cache)
  4838. return -EINVAL;
  4839. /*
  4840. * pull in the free space cache (if any) so that our pin
  4841. * removes the free space from the cache. We have load_only set
  4842. * to one because the slow code to read in the free extents does check
  4843. * the pinned extents.
  4844. */
  4845. cache_block_group(cache, 1);
  4846. pin_down_extent(root, cache, bytenr, num_bytes, 0);
  4847. /* remove us from the free space cache (if we're there at all) */
  4848. ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
  4849. btrfs_put_block_group(cache);
  4850. return ret;
  4851. }
  4852. static int __exclude_logged_extent(struct btrfs_root *root, u64 start, u64 num_bytes)
  4853. {
  4854. int ret;
  4855. struct btrfs_block_group_cache *block_group;
  4856. struct btrfs_caching_control *caching_ctl;
  4857. block_group = btrfs_lookup_block_group(root->fs_info, start);
  4858. if (!block_group)
  4859. return -EINVAL;
  4860. cache_block_group(block_group, 0);
  4861. caching_ctl = get_caching_control(block_group);
  4862. if (!caching_ctl) {
  4863. /* Logic error */
  4864. BUG_ON(!block_group_cache_done(block_group));
  4865. ret = btrfs_remove_free_space(block_group, start, num_bytes);
  4866. } else {
  4867. mutex_lock(&caching_ctl->mutex);
  4868. if (start >= caching_ctl->progress) {
  4869. ret = add_excluded_extent(root, start, num_bytes);
  4870. } else if (start + num_bytes <= caching_ctl->progress) {
  4871. ret = btrfs_remove_free_space(block_group,
  4872. start, num_bytes);
  4873. } else {
  4874. num_bytes = caching_ctl->progress - start;
  4875. ret = btrfs_remove_free_space(block_group,
  4876. start, num_bytes);
  4877. if (ret)
  4878. goto out_lock;
  4879. num_bytes = (start + num_bytes) -
  4880. caching_ctl->progress;
  4881. start = caching_ctl->progress;
  4882. ret = add_excluded_extent(root, start, num_bytes);
  4883. }
  4884. out_lock:
  4885. mutex_unlock(&caching_ctl->mutex);
  4886. put_caching_control(caching_ctl);
  4887. }
  4888. btrfs_put_block_group(block_group);
  4889. return ret;
  4890. }
  4891. int btrfs_exclude_logged_extents(struct btrfs_root *log,
  4892. struct extent_buffer *eb)
  4893. {
  4894. struct btrfs_file_extent_item *item;
  4895. struct btrfs_key key;
  4896. int found_type;
  4897. int i;
  4898. if (!btrfs_fs_incompat(log->fs_info, MIXED_GROUPS))
  4899. return 0;
  4900. for (i = 0; i < btrfs_header_nritems(eb); i++) {
  4901. btrfs_item_key_to_cpu(eb, &key, i);
  4902. if (key.type != BTRFS_EXTENT_DATA_KEY)
  4903. continue;
  4904. item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
  4905. found_type = btrfs_file_extent_type(eb, item);
  4906. if (found_type == BTRFS_FILE_EXTENT_INLINE)
  4907. continue;
  4908. if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
  4909. continue;
  4910. key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
  4911. key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
  4912. __exclude_logged_extent(log, key.objectid, key.offset);
  4913. }
  4914. return 0;
  4915. }
  4916. /**
  4917. * btrfs_update_reserved_bytes - update the block_group and space info counters
  4918. * @cache: The cache we are manipulating
  4919. * @num_bytes: The number of bytes in question
  4920. * @reserve: One of the reservation enums
  4921. * @delalloc: The blocks are allocated for the delalloc write
  4922. *
  4923. * This is called by the allocator when it reserves space, or by somebody who is
  4924. * freeing space that was never actually used on disk. For example if you
  4925. * reserve some space for a new leaf in transaction A and before transaction A
  4926. * commits you free that leaf, you call this with reserve set to 0 in order to
  4927. * clear the reservation.
  4928. *
  4929. * Metadata reservations should be called with RESERVE_ALLOC so we do the proper
  4930. * ENOSPC accounting. For data we handle the reservation through clearing the
  4931. * delalloc bits in the io_tree. We have to do this since we could end up
  4932. * allocating less disk space for the amount of data we have reserved in the
  4933. * case of compression.
  4934. *
  4935. * If this is a reservation and the block group has become read only we cannot
  4936. * make the reservation and return -EAGAIN, otherwise this function always
  4937. * succeeds.
  4938. */
  4939. static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
  4940. u64 num_bytes, int reserve, int delalloc)
  4941. {
  4942. struct btrfs_space_info *space_info = cache->space_info;
  4943. int ret = 0;
  4944. spin_lock(&space_info->lock);
  4945. spin_lock(&cache->lock);
  4946. if (reserve != RESERVE_FREE) {
  4947. if (cache->ro) {
  4948. ret = -EAGAIN;
  4949. } else {
  4950. cache->reserved += num_bytes;
  4951. space_info->bytes_reserved += num_bytes;
  4952. if (reserve == RESERVE_ALLOC) {
  4953. trace_btrfs_space_reservation(cache->fs_info,
  4954. "space_info", space_info->flags,
  4955. num_bytes, 0);
  4956. space_info->bytes_may_use -= num_bytes;
  4957. }
  4958. if (delalloc)
  4959. cache->delalloc_bytes += num_bytes;
  4960. }
  4961. } else {
  4962. if (cache->ro)
  4963. space_info->bytes_readonly += num_bytes;
  4964. cache->reserved -= num_bytes;
  4965. space_info->bytes_reserved -= num_bytes;
  4966. if (delalloc)
  4967. cache->delalloc_bytes -= num_bytes;
  4968. }
  4969. spin_unlock(&cache->lock);
  4970. spin_unlock(&space_info->lock);
  4971. return ret;
  4972. }
  4973. void btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
  4974. struct btrfs_root *root)
  4975. {
  4976. struct btrfs_fs_info *fs_info = root->fs_info;
  4977. struct btrfs_caching_control *next;
  4978. struct btrfs_caching_control *caching_ctl;
  4979. struct btrfs_block_group_cache *cache;
  4980. down_write(&fs_info->commit_root_sem);
  4981. list_for_each_entry_safe(caching_ctl, next,
  4982. &fs_info->caching_block_groups, list) {
  4983. cache = caching_ctl->block_group;
  4984. if (block_group_cache_done(cache)) {
  4985. cache->last_byte_to_unpin = (u64)-1;
  4986. list_del_init(&caching_ctl->list);
  4987. put_caching_control(caching_ctl);
  4988. } else {
  4989. cache->last_byte_to_unpin = caching_ctl->progress;
  4990. }
  4991. }
  4992. if (fs_info->pinned_extents == &fs_info->freed_extents[0])
  4993. fs_info->pinned_extents = &fs_info->freed_extents[1];
  4994. else
  4995. fs_info->pinned_extents = &fs_info->freed_extents[0];
  4996. up_write(&fs_info->commit_root_sem);
  4997. update_global_block_rsv(fs_info);
  4998. }
  4999. static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end,
  5000. const bool return_free_space)
  5001. {
  5002. struct btrfs_fs_info *fs_info = root->fs_info;
  5003. struct btrfs_block_group_cache *cache = NULL;
  5004. struct btrfs_space_info *space_info;
  5005. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  5006. u64 len;
  5007. bool readonly;
  5008. while (start <= end) {
  5009. readonly = false;
  5010. if (!cache ||
  5011. start >= cache->key.objectid + cache->key.offset) {
  5012. if (cache)
  5013. btrfs_put_block_group(cache);
  5014. cache = btrfs_lookup_block_group(fs_info, start);
  5015. BUG_ON(!cache); /* Logic error */
  5016. }
  5017. len = cache->key.objectid + cache->key.offset - start;
  5018. len = min(len, end + 1 - start);
  5019. if (start < cache->last_byte_to_unpin) {
  5020. len = min(len, cache->last_byte_to_unpin - start);
  5021. if (return_free_space)
  5022. btrfs_add_free_space(cache, start, len);
  5023. }
  5024. start += len;
  5025. space_info = cache->space_info;
  5026. spin_lock(&space_info->lock);
  5027. spin_lock(&cache->lock);
  5028. cache->pinned -= len;
  5029. space_info->bytes_pinned -= len;
  5030. percpu_counter_add(&space_info->total_bytes_pinned, -len);
  5031. if (cache->ro) {
  5032. space_info->bytes_readonly += len;
  5033. readonly = true;
  5034. }
  5035. spin_unlock(&cache->lock);
  5036. if (!readonly && global_rsv->space_info == space_info) {
  5037. spin_lock(&global_rsv->lock);
  5038. if (!global_rsv->full) {
  5039. len = min(len, global_rsv->size -
  5040. global_rsv->reserved);
  5041. global_rsv->reserved += len;
  5042. space_info->bytes_may_use += len;
  5043. if (global_rsv->reserved >= global_rsv->size)
  5044. global_rsv->full = 1;
  5045. }
  5046. spin_unlock(&global_rsv->lock);
  5047. }
  5048. spin_unlock(&space_info->lock);
  5049. }
  5050. if (cache)
  5051. btrfs_put_block_group(cache);
  5052. return 0;
  5053. }
  5054. int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
  5055. struct btrfs_root *root)
  5056. {
  5057. struct btrfs_fs_info *fs_info = root->fs_info;
  5058. struct extent_io_tree *unpin;
  5059. u64 start;
  5060. u64 end;
  5061. int ret;
  5062. if (trans->aborted)
  5063. return 0;
  5064. if (fs_info->pinned_extents == &fs_info->freed_extents[0])
  5065. unpin = &fs_info->freed_extents[1];
  5066. else
  5067. unpin = &fs_info->freed_extents[0];
  5068. while (1) {
  5069. mutex_lock(&fs_info->unused_bg_unpin_mutex);
  5070. ret = find_first_extent_bit(unpin, 0, &start, &end,
  5071. EXTENT_DIRTY, NULL);
  5072. if (ret) {
  5073. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  5074. break;
  5075. }
  5076. if (btrfs_test_opt(root, DISCARD))
  5077. ret = btrfs_discard_extent(root, start,
  5078. end + 1 - start, NULL);
  5079. clear_extent_dirty(unpin, start, end, GFP_NOFS);
  5080. unpin_extent_range(root, start, end, true);
  5081. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  5082. cond_resched();
  5083. }
  5084. return 0;
  5085. }
  5086. static void add_pinned_bytes(struct btrfs_fs_info *fs_info, u64 num_bytes,
  5087. u64 owner, u64 root_objectid)
  5088. {
  5089. struct btrfs_space_info *space_info;
  5090. u64 flags;
  5091. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  5092. if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
  5093. flags = BTRFS_BLOCK_GROUP_SYSTEM;
  5094. else
  5095. flags = BTRFS_BLOCK_GROUP_METADATA;
  5096. } else {
  5097. flags = BTRFS_BLOCK_GROUP_DATA;
  5098. }
  5099. space_info = __find_space_info(fs_info, flags);
  5100. BUG_ON(!space_info); /* Logic bug */
  5101. percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
  5102. }
  5103. static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
  5104. struct btrfs_root *root,
  5105. u64 bytenr, u64 num_bytes, u64 parent,
  5106. u64 root_objectid, u64 owner_objectid,
  5107. u64 owner_offset, int refs_to_drop,
  5108. struct btrfs_delayed_extent_op *extent_op,
  5109. int no_quota)
  5110. {
  5111. struct btrfs_key key;
  5112. struct btrfs_path *path;
  5113. struct btrfs_fs_info *info = root->fs_info;
  5114. struct btrfs_root *extent_root = info->extent_root;
  5115. struct extent_buffer *leaf;
  5116. struct btrfs_extent_item *ei;
  5117. struct btrfs_extent_inline_ref *iref;
  5118. int ret;
  5119. int is_data;
  5120. int extent_slot = 0;
  5121. int found_extent = 0;
  5122. int num_to_del = 1;
  5123. u32 item_size;
  5124. u64 refs;
  5125. int last_ref = 0;
  5126. enum btrfs_qgroup_operation_type type = BTRFS_QGROUP_OPER_SUB_EXCL;
  5127. bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
  5128. SKINNY_METADATA);
  5129. if (!info->quota_enabled || !is_fstree(root_objectid))
  5130. no_quota = 1;
  5131. path = btrfs_alloc_path();
  5132. if (!path)
  5133. return -ENOMEM;
  5134. path->reada = 1;
  5135. path->leave_spinning = 1;
  5136. is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
  5137. BUG_ON(!is_data && refs_to_drop != 1);
  5138. if (is_data)
  5139. skinny_metadata = 0;
  5140. ret = lookup_extent_backref(trans, extent_root, path, &iref,
  5141. bytenr, num_bytes, parent,
  5142. root_objectid, owner_objectid,
  5143. owner_offset);
  5144. if (ret == 0) {
  5145. extent_slot = path->slots[0];
  5146. while (extent_slot >= 0) {
  5147. btrfs_item_key_to_cpu(path->nodes[0], &key,
  5148. extent_slot);
  5149. if (key.objectid != bytenr)
  5150. break;
  5151. if (key.type == BTRFS_EXTENT_ITEM_KEY &&
  5152. key.offset == num_bytes) {
  5153. found_extent = 1;
  5154. break;
  5155. }
  5156. if (key.type == BTRFS_METADATA_ITEM_KEY &&
  5157. key.offset == owner_objectid) {
  5158. found_extent = 1;
  5159. break;
  5160. }
  5161. if (path->slots[0] - extent_slot > 5)
  5162. break;
  5163. extent_slot--;
  5164. }
  5165. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  5166. item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
  5167. if (found_extent && item_size < sizeof(*ei))
  5168. found_extent = 0;
  5169. #endif
  5170. if (!found_extent) {
  5171. BUG_ON(iref);
  5172. ret = remove_extent_backref(trans, extent_root, path,
  5173. NULL, refs_to_drop,
  5174. is_data, &last_ref);
  5175. if (ret) {
  5176. btrfs_abort_transaction(trans, extent_root, ret);
  5177. goto out;
  5178. }
  5179. btrfs_release_path(path);
  5180. path->leave_spinning = 1;
  5181. key.objectid = bytenr;
  5182. key.type = BTRFS_EXTENT_ITEM_KEY;
  5183. key.offset = num_bytes;
  5184. if (!is_data && skinny_metadata) {
  5185. key.type = BTRFS_METADATA_ITEM_KEY;
  5186. key.offset = owner_objectid;
  5187. }
  5188. ret = btrfs_search_slot(trans, extent_root,
  5189. &key, path, -1, 1);
  5190. if (ret > 0 && skinny_metadata && path->slots[0]) {
  5191. /*
  5192. * Couldn't find our skinny metadata item,
  5193. * see if we have ye olde extent item.
  5194. */
  5195. path->slots[0]--;
  5196. btrfs_item_key_to_cpu(path->nodes[0], &key,
  5197. path->slots[0]);
  5198. if (key.objectid == bytenr &&
  5199. key.type == BTRFS_EXTENT_ITEM_KEY &&
  5200. key.offset == num_bytes)
  5201. ret = 0;
  5202. }
  5203. if (ret > 0 && skinny_metadata) {
  5204. skinny_metadata = false;
  5205. key.objectid = bytenr;
  5206. key.type = BTRFS_EXTENT_ITEM_KEY;
  5207. key.offset = num_bytes;
  5208. btrfs_release_path(path);
  5209. ret = btrfs_search_slot(trans, extent_root,
  5210. &key, path, -1, 1);
  5211. }
  5212. if (ret) {
  5213. btrfs_err(info, "umm, got %d back from search, was looking for %llu",
  5214. ret, bytenr);
  5215. if (ret > 0)
  5216. btrfs_print_leaf(extent_root,
  5217. path->nodes[0]);
  5218. }
  5219. if (ret < 0) {
  5220. btrfs_abort_transaction(trans, extent_root, ret);
  5221. goto out;
  5222. }
  5223. extent_slot = path->slots[0];
  5224. }
  5225. } else if (WARN_ON(ret == -ENOENT)) {
  5226. btrfs_print_leaf(extent_root, path->nodes[0]);
  5227. btrfs_err(info,
  5228. "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
  5229. bytenr, parent, root_objectid, owner_objectid,
  5230. owner_offset);
  5231. btrfs_abort_transaction(trans, extent_root, ret);
  5232. goto out;
  5233. } else {
  5234. btrfs_abort_transaction(trans, extent_root, ret);
  5235. goto out;
  5236. }
  5237. leaf = path->nodes[0];
  5238. item_size = btrfs_item_size_nr(leaf, extent_slot);
  5239. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  5240. if (item_size < sizeof(*ei)) {
  5241. BUG_ON(found_extent || extent_slot != path->slots[0]);
  5242. ret = convert_extent_item_v0(trans, extent_root, path,
  5243. owner_objectid, 0);
  5244. if (ret < 0) {
  5245. btrfs_abort_transaction(trans, extent_root, ret);
  5246. goto out;
  5247. }
  5248. btrfs_release_path(path);
  5249. path->leave_spinning = 1;
  5250. key.objectid = bytenr;
  5251. key.type = BTRFS_EXTENT_ITEM_KEY;
  5252. key.offset = num_bytes;
  5253. ret = btrfs_search_slot(trans, extent_root, &key, path,
  5254. -1, 1);
  5255. if (ret) {
  5256. btrfs_err(info, "umm, got %d back from search, was looking for %llu",
  5257. ret, bytenr);
  5258. btrfs_print_leaf(extent_root, path->nodes[0]);
  5259. }
  5260. if (ret < 0) {
  5261. btrfs_abort_transaction(trans, extent_root, ret);
  5262. goto out;
  5263. }
  5264. extent_slot = path->slots[0];
  5265. leaf = path->nodes[0];
  5266. item_size = btrfs_item_size_nr(leaf, extent_slot);
  5267. }
  5268. #endif
  5269. BUG_ON(item_size < sizeof(*ei));
  5270. ei = btrfs_item_ptr(leaf, extent_slot,
  5271. struct btrfs_extent_item);
  5272. if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
  5273. key.type == BTRFS_EXTENT_ITEM_KEY) {
  5274. struct btrfs_tree_block_info *bi;
  5275. BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
  5276. bi = (struct btrfs_tree_block_info *)(ei + 1);
  5277. WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
  5278. }
  5279. refs = btrfs_extent_refs(leaf, ei);
  5280. if (refs < refs_to_drop) {
  5281. btrfs_err(info, "trying to drop %d refs but we only have %Lu "
  5282. "for bytenr %Lu", refs_to_drop, refs, bytenr);
  5283. ret = -EINVAL;
  5284. btrfs_abort_transaction(trans, extent_root, ret);
  5285. goto out;
  5286. }
  5287. refs -= refs_to_drop;
  5288. if (refs > 0) {
  5289. type = BTRFS_QGROUP_OPER_SUB_SHARED;
  5290. if (extent_op)
  5291. __run_delayed_extent_op(extent_op, leaf, ei);
  5292. /*
  5293. * In the case of inline back ref, reference count will
  5294. * be updated by remove_extent_backref
  5295. */
  5296. if (iref) {
  5297. BUG_ON(!found_extent);
  5298. } else {
  5299. btrfs_set_extent_refs(leaf, ei, refs);
  5300. btrfs_mark_buffer_dirty(leaf);
  5301. }
  5302. if (found_extent) {
  5303. ret = remove_extent_backref(trans, extent_root, path,
  5304. iref, refs_to_drop,
  5305. is_data, &last_ref);
  5306. if (ret) {
  5307. btrfs_abort_transaction(trans, extent_root, ret);
  5308. goto out;
  5309. }
  5310. }
  5311. add_pinned_bytes(root->fs_info, -num_bytes, owner_objectid,
  5312. root_objectid);
  5313. } else {
  5314. if (found_extent) {
  5315. BUG_ON(is_data && refs_to_drop !=
  5316. extent_data_ref_count(root, path, iref));
  5317. if (iref) {
  5318. BUG_ON(path->slots[0] != extent_slot);
  5319. } else {
  5320. BUG_ON(path->slots[0] != extent_slot + 1);
  5321. path->slots[0] = extent_slot;
  5322. num_to_del = 2;
  5323. }
  5324. }
  5325. last_ref = 1;
  5326. ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
  5327. num_to_del);
  5328. if (ret) {
  5329. btrfs_abort_transaction(trans, extent_root, ret);
  5330. goto out;
  5331. }
  5332. btrfs_release_path(path);
  5333. if (is_data) {
  5334. ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
  5335. if (ret) {
  5336. btrfs_abort_transaction(trans, extent_root, ret);
  5337. goto out;
  5338. }
  5339. }
  5340. ret = update_block_group(trans, root, bytenr, num_bytes, 0);
  5341. if (ret) {
  5342. btrfs_abort_transaction(trans, extent_root, ret);
  5343. goto out;
  5344. }
  5345. }
  5346. btrfs_release_path(path);
  5347. /* Deal with the quota accounting */
  5348. if (!ret && last_ref && !no_quota) {
  5349. int mod_seq = 0;
  5350. if (owner_objectid >= BTRFS_FIRST_FREE_OBJECTID &&
  5351. type == BTRFS_QGROUP_OPER_SUB_SHARED)
  5352. mod_seq = 1;
  5353. ret = btrfs_qgroup_record_ref(trans, info, root_objectid,
  5354. bytenr, num_bytes, type,
  5355. mod_seq);
  5356. }
  5357. out:
  5358. btrfs_free_path(path);
  5359. return ret;
  5360. }
  5361. /*
  5362. * when we free an block, it is possible (and likely) that we free the last
  5363. * delayed ref for that extent as well. This searches the delayed ref tree for
  5364. * a given extent, and if there are no other delayed refs to be processed, it
  5365. * removes it from the tree.
  5366. */
  5367. static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
  5368. struct btrfs_root *root, u64 bytenr)
  5369. {
  5370. struct btrfs_delayed_ref_head *head;
  5371. struct btrfs_delayed_ref_root *delayed_refs;
  5372. int ret = 0;
  5373. delayed_refs = &trans->transaction->delayed_refs;
  5374. spin_lock(&delayed_refs->lock);
  5375. head = btrfs_find_delayed_ref_head(trans, bytenr);
  5376. if (!head)
  5377. goto out_delayed_unlock;
  5378. spin_lock(&head->lock);
  5379. if (rb_first(&head->ref_root))
  5380. goto out;
  5381. if (head->extent_op) {
  5382. if (!head->must_insert_reserved)
  5383. goto out;
  5384. btrfs_free_delayed_extent_op(head->extent_op);
  5385. head->extent_op = NULL;
  5386. }
  5387. /*
  5388. * waiting for the lock here would deadlock. If someone else has it
  5389. * locked they are already in the process of dropping it anyway
  5390. */
  5391. if (!mutex_trylock(&head->mutex))
  5392. goto out;
  5393. /*
  5394. * at this point we have a head with no other entries. Go
  5395. * ahead and process it.
  5396. */
  5397. head->node.in_tree = 0;
  5398. rb_erase(&head->href_node, &delayed_refs->href_root);
  5399. atomic_dec(&delayed_refs->num_entries);
  5400. /*
  5401. * we don't take a ref on the node because we're removing it from the
  5402. * tree, so we just steal the ref the tree was holding.
  5403. */
  5404. delayed_refs->num_heads--;
  5405. if (head->processing == 0)
  5406. delayed_refs->num_heads_ready--;
  5407. head->processing = 0;
  5408. spin_unlock(&head->lock);
  5409. spin_unlock(&delayed_refs->lock);
  5410. BUG_ON(head->extent_op);
  5411. if (head->must_insert_reserved)
  5412. ret = 1;
  5413. mutex_unlock(&head->mutex);
  5414. btrfs_put_delayed_ref(&head->node);
  5415. return ret;
  5416. out:
  5417. spin_unlock(&head->lock);
  5418. out_delayed_unlock:
  5419. spin_unlock(&delayed_refs->lock);
  5420. return 0;
  5421. }
  5422. void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
  5423. struct btrfs_root *root,
  5424. struct extent_buffer *buf,
  5425. u64 parent, int last_ref)
  5426. {
  5427. int pin = 1;
  5428. int ret;
  5429. if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
  5430. ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
  5431. buf->start, buf->len,
  5432. parent, root->root_key.objectid,
  5433. btrfs_header_level(buf),
  5434. BTRFS_DROP_DELAYED_REF, NULL, 0);
  5435. BUG_ON(ret); /* -ENOMEM */
  5436. }
  5437. if (!last_ref)
  5438. return;
  5439. if (btrfs_header_generation(buf) == trans->transid) {
  5440. struct btrfs_block_group_cache *cache;
  5441. if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
  5442. ret = check_ref_cleanup(trans, root, buf->start);
  5443. if (!ret)
  5444. goto out;
  5445. }
  5446. cache = btrfs_lookup_block_group(root->fs_info, buf->start);
  5447. if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
  5448. pin_down_extent(root, cache, buf->start, buf->len, 1);
  5449. btrfs_put_block_group(cache);
  5450. goto out;
  5451. }
  5452. WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
  5453. btrfs_add_free_space(cache, buf->start, buf->len);
  5454. btrfs_update_reserved_bytes(cache, buf->len, RESERVE_FREE, 0);
  5455. btrfs_put_block_group(cache);
  5456. trace_btrfs_reserved_extent_free(root, buf->start, buf->len);
  5457. pin = 0;
  5458. }
  5459. out:
  5460. if (pin)
  5461. add_pinned_bytes(root->fs_info, buf->len,
  5462. btrfs_header_level(buf),
  5463. root->root_key.objectid);
  5464. /*
  5465. * Deleting the buffer, clear the corrupt flag since it doesn't matter
  5466. * anymore.
  5467. */
  5468. clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
  5469. }
  5470. /* Can return -ENOMEM */
  5471. int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  5472. u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
  5473. u64 owner, u64 offset, int no_quota)
  5474. {
  5475. int ret;
  5476. struct btrfs_fs_info *fs_info = root->fs_info;
  5477. if (btrfs_test_is_dummy_root(root))
  5478. return 0;
  5479. add_pinned_bytes(root->fs_info, num_bytes, owner, root_objectid);
  5480. /*
  5481. * tree log blocks never actually go into the extent allocation
  5482. * tree, just update pinning info and exit early.
  5483. */
  5484. if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
  5485. WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
  5486. /* unlocks the pinned mutex */
  5487. btrfs_pin_extent(root, bytenr, num_bytes, 1);
  5488. ret = 0;
  5489. } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  5490. ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
  5491. num_bytes,
  5492. parent, root_objectid, (int)owner,
  5493. BTRFS_DROP_DELAYED_REF, NULL, no_quota);
  5494. } else {
  5495. ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
  5496. num_bytes,
  5497. parent, root_objectid, owner,
  5498. offset, BTRFS_DROP_DELAYED_REF,
  5499. NULL, no_quota);
  5500. }
  5501. return ret;
  5502. }
  5503. /*
  5504. * when we wait for progress in the block group caching, its because
  5505. * our allocation attempt failed at least once. So, we must sleep
  5506. * and let some progress happen before we try again.
  5507. *
  5508. * This function will sleep at least once waiting for new free space to
  5509. * show up, and then it will check the block group free space numbers
  5510. * for our min num_bytes. Another option is to have it go ahead
  5511. * and look in the rbtree for a free extent of a given size, but this
  5512. * is a good start.
  5513. *
  5514. * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
  5515. * any of the information in this block group.
  5516. */
  5517. static noinline void
  5518. wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
  5519. u64 num_bytes)
  5520. {
  5521. struct btrfs_caching_control *caching_ctl;
  5522. caching_ctl = get_caching_control(cache);
  5523. if (!caching_ctl)
  5524. return;
  5525. wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
  5526. (cache->free_space_ctl->free_space >= num_bytes));
  5527. put_caching_control(caching_ctl);
  5528. }
  5529. static noinline int
  5530. wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
  5531. {
  5532. struct btrfs_caching_control *caching_ctl;
  5533. int ret = 0;
  5534. caching_ctl = get_caching_control(cache);
  5535. if (!caching_ctl)
  5536. return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
  5537. wait_event(caching_ctl->wait, block_group_cache_done(cache));
  5538. if (cache->cached == BTRFS_CACHE_ERROR)
  5539. ret = -EIO;
  5540. put_caching_control(caching_ctl);
  5541. return ret;
  5542. }
  5543. int __get_raid_index(u64 flags)
  5544. {
  5545. if (flags & BTRFS_BLOCK_GROUP_RAID10)
  5546. return BTRFS_RAID_RAID10;
  5547. else if (flags & BTRFS_BLOCK_GROUP_RAID1)
  5548. return BTRFS_RAID_RAID1;
  5549. else if (flags & BTRFS_BLOCK_GROUP_DUP)
  5550. return BTRFS_RAID_DUP;
  5551. else if (flags & BTRFS_BLOCK_GROUP_RAID0)
  5552. return BTRFS_RAID_RAID0;
  5553. else if (flags & BTRFS_BLOCK_GROUP_RAID5)
  5554. return BTRFS_RAID_RAID5;
  5555. else if (flags & BTRFS_BLOCK_GROUP_RAID6)
  5556. return BTRFS_RAID_RAID6;
  5557. return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
  5558. }
  5559. int get_block_group_index(struct btrfs_block_group_cache *cache)
  5560. {
  5561. return __get_raid_index(cache->flags);
  5562. }
  5563. static const char *btrfs_raid_type_names[BTRFS_NR_RAID_TYPES] = {
  5564. [BTRFS_RAID_RAID10] = "raid10",
  5565. [BTRFS_RAID_RAID1] = "raid1",
  5566. [BTRFS_RAID_DUP] = "dup",
  5567. [BTRFS_RAID_RAID0] = "raid0",
  5568. [BTRFS_RAID_SINGLE] = "single",
  5569. [BTRFS_RAID_RAID5] = "raid5",
  5570. [BTRFS_RAID_RAID6] = "raid6",
  5571. };
  5572. static const char *get_raid_name(enum btrfs_raid_types type)
  5573. {
  5574. if (type >= BTRFS_NR_RAID_TYPES)
  5575. return NULL;
  5576. return btrfs_raid_type_names[type];
  5577. }
  5578. enum btrfs_loop_type {
  5579. LOOP_CACHING_NOWAIT = 0,
  5580. LOOP_CACHING_WAIT = 1,
  5581. LOOP_ALLOC_CHUNK = 2,
  5582. LOOP_NO_EMPTY_SIZE = 3,
  5583. };
  5584. static inline void
  5585. btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
  5586. int delalloc)
  5587. {
  5588. if (delalloc)
  5589. down_read(&cache->data_rwsem);
  5590. }
  5591. static inline void
  5592. btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
  5593. int delalloc)
  5594. {
  5595. btrfs_get_block_group(cache);
  5596. if (delalloc)
  5597. down_read(&cache->data_rwsem);
  5598. }
  5599. static struct btrfs_block_group_cache *
  5600. btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
  5601. struct btrfs_free_cluster *cluster,
  5602. int delalloc)
  5603. {
  5604. struct btrfs_block_group_cache *used_bg;
  5605. bool locked = false;
  5606. again:
  5607. spin_lock(&cluster->refill_lock);
  5608. if (locked) {
  5609. if (used_bg == cluster->block_group)
  5610. return used_bg;
  5611. up_read(&used_bg->data_rwsem);
  5612. btrfs_put_block_group(used_bg);
  5613. }
  5614. used_bg = cluster->block_group;
  5615. if (!used_bg)
  5616. return NULL;
  5617. if (used_bg == block_group)
  5618. return used_bg;
  5619. btrfs_get_block_group(used_bg);
  5620. if (!delalloc)
  5621. return used_bg;
  5622. if (down_read_trylock(&used_bg->data_rwsem))
  5623. return used_bg;
  5624. spin_unlock(&cluster->refill_lock);
  5625. down_read(&used_bg->data_rwsem);
  5626. locked = true;
  5627. goto again;
  5628. }
  5629. static inline void
  5630. btrfs_release_block_group(struct btrfs_block_group_cache *cache,
  5631. int delalloc)
  5632. {
  5633. if (delalloc)
  5634. up_read(&cache->data_rwsem);
  5635. btrfs_put_block_group(cache);
  5636. }
  5637. /*
  5638. * walks the btree of allocated extents and find a hole of a given size.
  5639. * The key ins is changed to record the hole:
  5640. * ins->objectid == start position
  5641. * ins->flags = BTRFS_EXTENT_ITEM_KEY
  5642. * ins->offset == the size of the hole.
  5643. * Any available blocks before search_start are skipped.
  5644. *
  5645. * If there is no suitable free space, we will record the max size of
  5646. * the free space extent currently.
  5647. */
  5648. static noinline int find_free_extent(struct btrfs_root *orig_root,
  5649. u64 num_bytes, u64 empty_size,
  5650. u64 hint_byte, struct btrfs_key *ins,
  5651. u64 flags, int delalloc)
  5652. {
  5653. int ret = 0;
  5654. struct btrfs_root *root = orig_root->fs_info->extent_root;
  5655. struct btrfs_free_cluster *last_ptr = NULL;
  5656. struct btrfs_block_group_cache *block_group = NULL;
  5657. u64 search_start = 0;
  5658. u64 max_extent_size = 0;
  5659. int empty_cluster = 2 * 1024 * 1024;
  5660. struct btrfs_space_info *space_info;
  5661. int loop = 0;
  5662. int index = __get_raid_index(flags);
  5663. int alloc_type = (flags & BTRFS_BLOCK_GROUP_DATA) ?
  5664. RESERVE_ALLOC_NO_ACCOUNT : RESERVE_ALLOC;
  5665. bool failed_cluster_refill = false;
  5666. bool failed_alloc = false;
  5667. bool use_cluster = true;
  5668. bool have_caching_bg = false;
  5669. WARN_ON(num_bytes < root->sectorsize);
  5670. ins->type = BTRFS_EXTENT_ITEM_KEY;
  5671. ins->objectid = 0;
  5672. ins->offset = 0;
  5673. trace_find_free_extent(orig_root, num_bytes, empty_size, flags);
  5674. space_info = __find_space_info(root->fs_info, flags);
  5675. if (!space_info) {
  5676. btrfs_err(root->fs_info, "No space info for %llu", flags);
  5677. return -ENOSPC;
  5678. }
  5679. /*
  5680. * If the space info is for both data and metadata it means we have a
  5681. * small filesystem and we can't use the clustering stuff.
  5682. */
  5683. if (btrfs_mixed_space_info(space_info))
  5684. use_cluster = false;
  5685. if (flags & BTRFS_BLOCK_GROUP_METADATA && use_cluster) {
  5686. last_ptr = &root->fs_info->meta_alloc_cluster;
  5687. if (!btrfs_test_opt(root, SSD))
  5688. empty_cluster = 64 * 1024;
  5689. }
  5690. if ((flags & BTRFS_BLOCK_GROUP_DATA) && use_cluster &&
  5691. btrfs_test_opt(root, SSD)) {
  5692. last_ptr = &root->fs_info->data_alloc_cluster;
  5693. }
  5694. if (last_ptr) {
  5695. spin_lock(&last_ptr->lock);
  5696. if (last_ptr->block_group)
  5697. hint_byte = last_ptr->window_start;
  5698. spin_unlock(&last_ptr->lock);
  5699. }
  5700. search_start = max(search_start, first_logical_byte(root, 0));
  5701. search_start = max(search_start, hint_byte);
  5702. if (!last_ptr)
  5703. empty_cluster = 0;
  5704. if (search_start == hint_byte) {
  5705. block_group = btrfs_lookup_block_group(root->fs_info,
  5706. search_start);
  5707. /*
  5708. * we don't want to use the block group if it doesn't match our
  5709. * allocation bits, or if its not cached.
  5710. *
  5711. * However if we are re-searching with an ideal block group
  5712. * picked out then we don't care that the block group is cached.
  5713. */
  5714. if (block_group && block_group_bits(block_group, flags) &&
  5715. block_group->cached != BTRFS_CACHE_NO) {
  5716. down_read(&space_info->groups_sem);
  5717. if (list_empty(&block_group->list) ||
  5718. block_group->ro) {
  5719. /*
  5720. * someone is removing this block group,
  5721. * we can't jump into the have_block_group
  5722. * target because our list pointers are not
  5723. * valid
  5724. */
  5725. btrfs_put_block_group(block_group);
  5726. up_read(&space_info->groups_sem);
  5727. } else {
  5728. index = get_block_group_index(block_group);
  5729. btrfs_lock_block_group(block_group, delalloc);
  5730. goto have_block_group;
  5731. }
  5732. } else if (block_group) {
  5733. btrfs_put_block_group(block_group);
  5734. }
  5735. }
  5736. search:
  5737. have_caching_bg = false;
  5738. down_read(&space_info->groups_sem);
  5739. list_for_each_entry(block_group, &space_info->block_groups[index],
  5740. list) {
  5741. u64 offset;
  5742. int cached;
  5743. btrfs_grab_block_group(block_group, delalloc);
  5744. search_start = block_group->key.objectid;
  5745. /*
  5746. * this can happen if we end up cycling through all the
  5747. * raid types, but we want to make sure we only allocate
  5748. * for the proper type.
  5749. */
  5750. if (!block_group_bits(block_group, flags)) {
  5751. u64 extra = BTRFS_BLOCK_GROUP_DUP |
  5752. BTRFS_BLOCK_GROUP_RAID1 |
  5753. BTRFS_BLOCK_GROUP_RAID5 |
  5754. BTRFS_BLOCK_GROUP_RAID6 |
  5755. BTRFS_BLOCK_GROUP_RAID10;
  5756. /*
  5757. * if they asked for extra copies and this block group
  5758. * doesn't provide them, bail. This does allow us to
  5759. * fill raid0 from raid1.
  5760. */
  5761. if ((flags & extra) && !(block_group->flags & extra))
  5762. goto loop;
  5763. }
  5764. have_block_group:
  5765. cached = block_group_cache_done(block_group);
  5766. if (unlikely(!cached)) {
  5767. ret = cache_block_group(block_group, 0);
  5768. BUG_ON(ret < 0);
  5769. ret = 0;
  5770. }
  5771. if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
  5772. goto loop;
  5773. if (unlikely(block_group->ro))
  5774. goto loop;
  5775. /*
  5776. * Ok we want to try and use the cluster allocator, so
  5777. * lets look there
  5778. */
  5779. if (last_ptr) {
  5780. struct btrfs_block_group_cache *used_block_group;
  5781. unsigned long aligned_cluster;
  5782. /*
  5783. * the refill lock keeps out other
  5784. * people trying to start a new cluster
  5785. */
  5786. used_block_group = btrfs_lock_cluster(block_group,
  5787. last_ptr,
  5788. delalloc);
  5789. if (!used_block_group)
  5790. goto refill_cluster;
  5791. if (used_block_group != block_group &&
  5792. (used_block_group->ro ||
  5793. !block_group_bits(used_block_group, flags)))
  5794. goto release_cluster;
  5795. offset = btrfs_alloc_from_cluster(used_block_group,
  5796. last_ptr,
  5797. num_bytes,
  5798. used_block_group->key.objectid,
  5799. &max_extent_size);
  5800. if (offset) {
  5801. /* we have a block, we're done */
  5802. spin_unlock(&last_ptr->refill_lock);
  5803. trace_btrfs_reserve_extent_cluster(root,
  5804. used_block_group,
  5805. search_start, num_bytes);
  5806. if (used_block_group != block_group) {
  5807. btrfs_release_block_group(block_group,
  5808. delalloc);
  5809. block_group = used_block_group;
  5810. }
  5811. goto checks;
  5812. }
  5813. WARN_ON(last_ptr->block_group != used_block_group);
  5814. release_cluster:
  5815. /* If we are on LOOP_NO_EMPTY_SIZE, we can't
  5816. * set up a new clusters, so lets just skip it
  5817. * and let the allocator find whatever block
  5818. * it can find. If we reach this point, we
  5819. * will have tried the cluster allocator
  5820. * plenty of times and not have found
  5821. * anything, so we are likely way too
  5822. * fragmented for the clustering stuff to find
  5823. * anything.
  5824. *
  5825. * However, if the cluster is taken from the
  5826. * current block group, release the cluster
  5827. * first, so that we stand a better chance of
  5828. * succeeding in the unclustered
  5829. * allocation. */
  5830. if (loop >= LOOP_NO_EMPTY_SIZE &&
  5831. used_block_group != block_group) {
  5832. spin_unlock(&last_ptr->refill_lock);
  5833. btrfs_release_block_group(used_block_group,
  5834. delalloc);
  5835. goto unclustered_alloc;
  5836. }
  5837. /*
  5838. * this cluster didn't work out, free it and
  5839. * start over
  5840. */
  5841. btrfs_return_cluster_to_free_space(NULL, last_ptr);
  5842. if (used_block_group != block_group)
  5843. btrfs_release_block_group(used_block_group,
  5844. delalloc);
  5845. refill_cluster:
  5846. if (loop >= LOOP_NO_EMPTY_SIZE) {
  5847. spin_unlock(&last_ptr->refill_lock);
  5848. goto unclustered_alloc;
  5849. }
  5850. aligned_cluster = max_t(unsigned long,
  5851. empty_cluster + empty_size,
  5852. block_group->full_stripe_len);
  5853. /* allocate a cluster in this block group */
  5854. ret = btrfs_find_space_cluster(root, block_group,
  5855. last_ptr, search_start,
  5856. num_bytes,
  5857. aligned_cluster);
  5858. if (ret == 0) {
  5859. /*
  5860. * now pull our allocation out of this
  5861. * cluster
  5862. */
  5863. offset = btrfs_alloc_from_cluster(block_group,
  5864. last_ptr,
  5865. num_bytes,
  5866. search_start,
  5867. &max_extent_size);
  5868. if (offset) {
  5869. /* we found one, proceed */
  5870. spin_unlock(&last_ptr->refill_lock);
  5871. trace_btrfs_reserve_extent_cluster(root,
  5872. block_group, search_start,
  5873. num_bytes);
  5874. goto checks;
  5875. }
  5876. } else if (!cached && loop > LOOP_CACHING_NOWAIT
  5877. && !failed_cluster_refill) {
  5878. spin_unlock(&last_ptr->refill_lock);
  5879. failed_cluster_refill = true;
  5880. wait_block_group_cache_progress(block_group,
  5881. num_bytes + empty_cluster + empty_size);
  5882. goto have_block_group;
  5883. }
  5884. /*
  5885. * at this point we either didn't find a cluster
  5886. * or we weren't able to allocate a block from our
  5887. * cluster. Free the cluster we've been trying
  5888. * to use, and go to the next block group
  5889. */
  5890. btrfs_return_cluster_to_free_space(NULL, last_ptr);
  5891. spin_unlock(&last_ptr->refill_lock);
  5892. goto loop;
  5893. }
  5894. unclustered_alloc:
  5895. spin_lock(&block_group->free_space_ctl->tree_lock);
  5896. if (cached &&
  5897. block_group->free_space_ctl->free_space <
  5898. num_bytes + empty_cluster + empty_size) {
  5899. if (block_group->free_space_ctl->free_space >
  5900. max_extent_size)
  5901. max_extent_size =
  5902. block_group->free_space_ctl->free_space;
  5903. spin_unlock(&block_group->free_space_ctl->tree_lock);
  5904. goto loop;
  5905. }
  5906. spin_unlock(&block_group->free_space_ctl->tree_lock);
  5907. offset = btrfs_find_space_for_alloc(block_group, search_start,
  5908. num_bytes, empty_size,
  5909. &max_extent_size);
  5910. /*
  5911. * If we didn't find a chunk, and we haven't failed on this
  5912. * block group before, and this block group is in the middle of
  5913. * caching and we are ok with waiting, then go ahead and wait
  5914. * for progress to be made, and set failed_alloc to true.
  5915. *
  5916. * If failed_alloc is true then we've already waited on this
  5917. * block group once and should move on to the next block group.
  5918. */
  5919. if (!offset && !failed_alloc && !cached &&
  5920. loop > LOOP_CACHING_NOWAIT) {
  5921. wait_block_group_cache_progress(block_group,
  5922. num_bytes + empty_size);
  5923. failed_alloc = true;
  5924. goto have_block_group;
  5925. } else if (!offset) {
  5926. if (!cached)
  5927. have_caching_bg = true;
  5928. goto loop;
  5929. }
  5930. checks:
  5931. search_start = ALIGN(offset, root->stripesize);
  5932. /* move on to the next group */
  5933. if (search_start + num_bytes >
  5934. block_group->key.objectid + block_group->key.offset) {
  5935. btrfs_add_free_space(block_group, offset, num_bytes);
  5936. goto loop;
  5937. }
  5938. if (offset < search_start)
  5939. btrfs_add_free_space(block_group, offset,
  5940. search_start - offset);
  5941. BUG_ON(offset > search_start);
  5942. ret = btrfs_update_reserved_bytes(block_group, num_bytes,
  5943. alloc_type, delalloc);
  5944. if (ret == -EAGAIN) {
  5945. btrfs_add_free_space(block_group, offset, num_bytes);
  5946. goto loop;
  5947. }
  5948. /* we are all good, lets return */
  5949. ins->objectid = search_start;
  5950. ins->offset = num_bytes;
  5951. trace_btrfs_reserve_extent(orig_root, block_group,
  5952. search_start, num_bytes);
  5953. btrfs_release_block_group(block_group, delalloc);
  5954. break;
  5955. loop:
  5956. failed_cluster_refill = false;
  5957. failed_alloc = false;
  5958. BUG_ON(index != get_block_group_index(block_group));
  5959. btrfs_release_block_group(block_group, delalloc);
  5960. }
  5961. up_read(&space_info->groups_sem);
  5962. if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
  5963. goto search;
  5964. if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
  5965. goto search;
  5966. /*
  5967. * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
  5968. * caching kthreads as we move along
  5969. * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
  5970. * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
  5971. * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
  5972. * again
  5973. */
  5974. if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
  5975. index = 0;
  5976. loop++;
  5977. if (loop == LOOP_ALLOC_CHUNK) {
  5978. struct btrfs_trans_handle *trans;
  5979. int exist = 0;
  5980. trans = current->journal_info;
  5981. if (trans)
  5982. exist = 1;
  5983. else
  5984. trans = btrfs_join_transaction(root);
  5985. if (IS_ERR(trans)) {
  5986. ret = PTR_ERR(trans);
  5987. goto out;
  5988. }
  5989. ret = do_chunk_alloc(trans, root, flags,
  5990. CHUNK_ALLOC_FORCE);
  5991. /*
  5992. * Do not bail out on ENOSPC since we
  5993. * can do more things.
  5994. */
  5995. if (ret < 0 && ret != -ENOSPC)
  5996. btrfs_abort_transaction(trans,
  5997. root, ret);
  5998. else
  5999. ret = 0;
  6000. if (!exist)
  6001. btrfs_end_transaction(trans, root);
  6002. if (ret)
  6003. goto out;
  6004. }
  6005. if (loop == LOOP_NO_EMPTY_SIZE) {
  6006. empty_size = 0;
  6007. empty_cluster = 0;
  6008. }
  6009. goto search;
  6010. } else if (!ins->objectid) {
  6011. ret = -ENOSPC;
  6012. } else if (ins->objectid) {
  6013. ret = 0;
  6014. }
  6015. out:
  6016. if (ret == -ENOSPC)
  6017. ins->offset = max_extent_size;
  6018. return ret;
  6019. }
  6020. static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
  6021. int dump_block_groups)
  6022. {
  6023. struct btrfs_block_group_cache *cache;
  6024. int index = 0;
  6025. spin_lock(&info->lock);
  6026. printk(KERN_INFO "BTRFS: space_info %llu has %llu free, is %sfull\n",
  6027. info->flags,
  6028. info->total_bytes - info->bytes_used - info->bytes_pinned -
  6029. info->bytes_reserved - info->bytes_readonly,
  6030. (info->full) ? "" : "not ");
  6031. printk(KERN_INFO "BTRFS: space_info total=%llu, used=%llu, pinned=%llu, "
  6032. "reserved=%llu, may_use=%llu, readonly=%llu\n",
  6033. info->total_bytes, info->bytes_used, info->bytes_pinned,
  6034. info->bytes_reserved, info->bytes_may_use,
  6035. info->bytes_readonly);
  6036. spin_unlock(&info->lock);
  6037. if (!dump_block_groups)
  6038. return;
  6039. down_read(&info->groups_sem);
  6040. again:
  6041. list_for_each_entry(cache, &info->block_groups[index], list) {
  6042. spin_lock(&cache->lock);
  6043. printk(KERN_INFO "BTRFS: "
  6044. "block group %llu has %llu bytes, "
  6045. "%llu used %llu pinned %llu reserved %s\n",
  6046. cache->key.objectid, cache->key.offset,
  6047. btrfs_block_group_used(&cache->item), cache->pinned,
  6048. cache->reserved, cache->ro ? "[readonly]" : "");
  6049. btrfs_dump_free_space(cache, bytes);
  6050. spin_unlock(&cache->lock);
  6051. }
  6052. if (++index < BTRFS_NR_RAID_TYPES)
  6053. goto again;
  6054. up_read(&info->groups_sem);
  6055. }
  6056. int btrfs_reserve_extent(struct btrfs_root *root,
  6057. u64 num_bytes, u64 min_alloc_size,
  6058. u64 empty_size, u64 hint_byte,
  6059. struct btrfs_key *ins, int is_data, int delalloc)
  6060. {
  6061. bool final_tried = false;
  6062. u64 flags;
  6063. int ret;
  6064. flags = btrfs_get_alloc_profile(root, is_data);
  6065. again:
  6066. WARN_ON(num_bytes < root->sectorsize);
  6067. ret = find_free_extent(root, num_bytes, empty_size, hint_byte, ins,
  6068. flags, delalloc);
  6069. if (ret == -ENOSPC) {
  6070. if (!final_tried && ins->offset) {
  6071. num_bytes = min(num_bytes >> 1, ins->offset);
  6072. num_bytes = round_down(num_bytes, root->sectorsize);
  6073. num_bytes = max(num_bytes, min_alloc_size);
  6074. if (num_bytes == min_alloc_size)
  6075. final_tried = true;
  6076. goto again;
  6077. } else if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
  6078. struct btrfs_space_info *sinfo;
  6079. sinfo = __find_space_info(root->fs_info, flags);
  6080. btrfs_err(root->fs_info, "allocation failed flags %llu, wanted %llu",
  6081. flags, num_bytes);
  6082. if (sinfo)
  6083. dump_space_info(sinfo, num_bytes, 1);
  6084. }
  6085. }
  6086. return ret;
  6087. }
  6088. static int __btrfs_free_reserved_extent(struct btrfs_root *root,
  6089. u64 start, u64 len,
  6090. int pin, int delalloc)
  6091. {
  6092. struct btrfs_block_group_cache *cache;
  6093. int ret = 0;
  6094. cache = btrfs_lookup_block_group(root->fs_info, start);
  6095. if (!cache) {
  6096. btrfs_err(root->fs_info, "Unable to find block group for %llu",
  6097. start);
  6098. return -ENOSPC;
  6099. }
  6100. if (btrfs_test_opt(root, DISCARD))
  6101. ret = btrfs_discard_extent(root, start, len, NULL);
  6102. if (pin)
  6103. pin_down_extent(root, cache, start, len, 1);
  6104. else {
  6105. btrfs_add_free_space(cache, start, len);
  6106. btrfs_update_reserved_bytes(cache, len, RESERVE_FREE, delalloc);
  6107. }
  6108. btrfs_put_block_group(cache);
  6109. trace_btrfs_reserved_extent_free(root, start, len);
  6110. return ret;
  6111. }
  6112. int btrfs_free_reserved_extent(struct btrfs_root *root,
  6113. u64 start, u64 len, int delalloc)
  6114. {
  6115. return __btrfs_free_reserved_extent(root, start, len, 0, delalloc);
  6116. }
  6117. int btrfs_free_and_pin_reserved_extent(struct btrfs_root *root,
  6118. u64 start, u64 len)
  6119. {
  6120. return __btrfs_free_reserved_extent(root, start, len, 1, 0);
  6121. }
  6122. static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
  6123. struct btrfs_root *root,
  6124. u64 parent, u64 root_objectid,
  6125. u64 flags, u64 owner, u64 offset,
  6126. struct btrfs_key *ins, int ref_mod)
  6127. {
  6128. int ret;
  6129. struct btrfs_fs_info *fs_info = root->fs_info;
  6130. struct btrfs_extent_item *extent_item;
  6131. struct btrfs_extent_inline_ref *iref;
  6132. struct btrfs_path *path;
  6133. struct extent_buffer *leaf;
  6134. int type;
  6135. u32 size;
  6136. if (parent > 0)
  6137. type = BTRFS_SHARED_DATA_REF_KEY;
  6138. else
  6139. type = BTRFS_EXTENT_DATA_REF_KEY;
  6140. size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
  6141. path = btrfs_alloc_path();
  6142. if (!path)
  6143. return -ENOMEM;
  6144. path->leave_spinning = 1;
  6145. ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
  6146. ins, size);
  6147. if (ret) {
  6148. btrfs_free_path(path);
  6149. return ret;
  6150. }
  6151. leaf = path->nodes[0];
  6152. extent_item = btrfs_item_ptr(leaf, path->slots[0],
  6153. struct btrfs_extent_item);
  6154. btrfs_set_extent_refs(leaf, extent_item, ref_mod);
  6155. btrfs_set_extent_generation(leaf, extent_item, trans->transid);
  6156. btrfs_set_extent_flags(leaf, extent_item,
  6157. flags | BTRFS_EXTENT_FLAG_DATA);
  6158. iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
  6159. btrfs_set_extent_inline_ref_type(leaf, iref, type);
  6160. if (parent > 0) {
  6161. struct btrfs_shared_data_ref *ref;
  6162. ref = (struct btrfs_shared_data_ref *)(iref + 1);
  6163. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  6164. btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
  6165. } else {
  6166. struct btrfs_extent_data_ref *ref;
  6167. ref = (struct btrfs_extent_data_ref *)(&iref->offset);
  6168. btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
  6169. btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
  6170. btrfs_set_extent_data_ref_offset(leaf, ref, offset);
  6171. btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
  6172. }
  6173. btrfs_mark_buffer_dirty(path->nodes[0]);
  6174. btrfs_free_path(path);
  6175. /* Always set parent to 0 here since its exclusive anyway. */
  6176. ret = btrfs_qgroup_record_ref(trans, fs_info, root_objectid,
  6177. ins->objectid, ins->offset,
  6178. BTRFS_QGROUP_OPER_ADD_EXCL, 0);
  6179. if (ret)
  6180. return ret;
  6181. ret = update_block_group(trans, root, ins->objectid, ins->offset, 1);
  6182. if (ret) { /* -ENOENT, logic error */
  6183. btrfs_err(fs_info, "update block group failed for %llu %llu",
  6184. ins->objectid, ins->offset);
  6185. BUG();
  6186. }
  6187. trace_btrfs_reserved_extent_alloc(root, ins->objectid, ins->offset);
  6188. return ret;
  6189. }
  6190. static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
  6191. struct btrfs_root *root,
  6192. u64 parent, u64 root_objectid,
  6193. u64 flags, struct btrfs_disk_key *key,
  6194. int level, struct btrfs_key *ins,
  6195. int no_quota)
  6196. {
  6197. int ret;
  6198. struct btrfs_fs_info *fs_info = root->fs_info;
  6199. struct btrfs_extent_item *extent_item;
  6200. struct btrfs_tree_block_info *block_info;
  6201. struct btrfs_extent_inline_ref *iref;
  6202. struct btrfs_path *path;
  6203. struct extent_buffer *leaf;
  6204. u32 size = sizeof(*extent_item) + sizeof(*iref);
  6205. u64 num_bytes = ins->offset;
  6206. bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
  6207. SKINNY_METADATA);
  6208. if (!skinny_metadata)
  6209. size += sizeof(*block_info);
  6210. path = btrfs_alloc_path();
  6211. if (!path) {
  6212. btrfs_free_and_pin_reserved_extent(root, ins->objectid,
  6213. root->nodesize);
  6214. return -ENOMEM;
  6215. }
  6216. path->leave_spinning = 1;
  6217. ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
  6218. ins, size);
  6219. if (ret) {
  6220. btrfs_free_and_pin_reserved_extent(root, ins->objectid,
  6221. root->nodesize);
  6222. btrfs_free_path(path);
  6223. return ret;
  6224. }
  6225. leaf = path->nodes[0];
  6226. extent_item = btrfs_item_ptr(leaf, path->slots[0],
  6227. struct btrfs_extent_item);
  6228. btrfs_set_extent_refs(leaf, extent_item, 1);
  6229. btrfs_set_extent_generation(leaf, extent_item, trans->transid);
  6230. btrfs_set_extent_flags(leaf, extent_item,
  6231. flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
  6232. if (skinny_metadata) {
  6233. iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
  6234. num_bytes = root->nodesize;
  6235. } else {
  6236. block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
  6237. btrfs_set_tree_block_key(leaf, block_info, key);
  6238. btrfs_set_tree_block_level(leaf, block_info, level);
  6239. iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
  6240. }
  6241. if (parent > 0) {
  6242. BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
  6243. btrfs_set_extent_inline_ref_type(leaf, iref,
  6244. BTRFS_SHARED_BLOCK_REF_KEY);
  6245. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  6246. } else {
  6247. btrfs_set_extent_inline_ref_type(leaf, iref,
  6248. BTRFS_TREE_BLOCK_REF_KEY);
  6249. btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
  6250. }
  6251. btrfs_mark_buffer_dirty(leaf);
  6252. btrfs_free_path(path);
  6253. if (!no_quota) {
  6254. ret = btrfs_qgroup_record_ref(trans, fs_info, root_objectid,
  6255. ins->objectid, num_bytes,
  6256. BTRFS_QGROUP_OPER_ADD_EXCL, 0);
  6257. if (ret)
  6258. return ret;
  6259. }
  6260. ret = update_block_group(trans, root, ins->objectid, root->nodesize,
  6261. 1);
  6262. if (ret) { /* -ENOENT, logic error */
  6263. btrfs_err(fs_info, "update block group failed for %llu %llu",
  6264. ins->objectid, ins->offset);
  6265. BUG();
  6266. }
  6267. trace_btrfs_reserved_extent_alloc(root, ins->objectid, root->nodesize);
  6268. return ret;
  6269. }
  6270. int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
  6271. struct btrfs_root *root,
  6272. u64 root_objectid, u64 owner,
  6273. u64 offset, struct btrfs_key *ins)
  6274. {
  6275. int ret;
  6276. BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
  6277. ret = btrfs_add_delayed_data_ref(root->fs_info, trans, ins->objectid,
  6278. ins->offset, 0,
  6279. root_objectid, owner, offset,
  6280. BTRFS_ADD_DELAYED_EXTENT, NULL, 0);
  6281. return ret;
  6282. }
  6283. /*
  6284. * this is used by the tree logging recovery code. It records that
  6285. * an extent has been allocated and makes sure to clear the free
  6286. * space cache bits as well
  6287. */
  6288. int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
  6289. struct btrfs_root *root,
  6290. u64 root_objectid, u64 owner, u64 offset,
  6291. struct btrfs_key *ins)
  6292. {
  6293. int ret;
  6294. struct btrfs_block_group_cache *block_group;
  6295. /*
  6296. * Mixed block groups will exclude before processing the log so we only
  6297. * need to do the exlude dance if this fs isn't mixed.
  6298. */
  6299. if (!btrfs_fs_incompat(root->fs_info, MIXED_GROUPS)) {
  6300. ret = __exclude_logged_extent(root, ins->objectid, ins->offset);
  6301. if (ret)
  6302. return ret;
  6303. }
  6304. block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
  6305. if (!block_group)
  6306. return -EINVAL;
  6307. ret = btrfs_update_reserved_bytes(block_group, ins->offset,
  6308. RESERVE_ALLOC_NO_ACCOUNT, 0);
  6309. BUG_ON(ret); /* logic error */
  6310. ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
  6311. 0, owner, offset, ins, 1);
  6312. btrfs_put_block_group(block_group);
  6313. return ret;
  6314. }
  6315. static struct extent_buffer *
  6316. btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  6317. u64 bytenr, int level)
  6318. {
  6319. struct extent_buffer *buf;
  6320. buf = btrfs_find_create_tree_block(root, bytenr);
  6321. if (!buf)
  6322. return ERR_PTR(-ENOMEM);
  6323. btrfs_set_header_generation(buf, trans->transid);
  6324. btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
  6325. btrfs_tree_lock(buf);
  6326. clean_tree_block(trans, root, buf);
  6327. clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
  6328. btrfs_set_lock_blocking(buf);
  6329. btrfs_set_buffer_uptodate(buf);
  6330. if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
  6331. buf->log_index = root->log_transid % 2;
  6332. /*
  6333. * we allow two log transactions at a time, use different
  6334. * EXENT bit to differentiate dirty pages.
  6335. */
  6336. if (buf->log_index == 0)
  6337. set_extent_dirty(&root->dirty_log_pages, buf->start,
  6338. buf->start + buf->len - 1, GFP_NOFS);
  6339. else
  6340. set_extent_new(&root->dirty_log_pages, buf->start,
  6341. buf->start + buf->len - 1, GFP_NOFS);
  6342. } else {
  6343. buf->log_index = -1;
  6344. set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
  6345. buf->start + buf->len - 1, GFP_NOFS);
  6346. }
  6347. trans->blocks_used++;
  6348. /* this returns a buffer locked for blocking */
  6349. return buf;
  6350. }
  6351. static struct btrfs_block_rsv *
  6352. use_block_rsv(struct btrfs_trans_handle *trans,
  6353. struct btrfs_root *root, u32 blocksize)
  6354. {
  6355. struct btrfs_block_rsv *block_rsv;
  6356. struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
  6357. int ret;
  6358. bool global_updated = false;
  6359. block_rsv = get_block_rsv(trans, root);
  6360. if (unlikely(block_rsv->size == 0))
  6361. goto try_reserve;
  6362. again:
  6363. ret = block_rsv_use_bytes(block_rsv, blocksize);
  6364. if (!ret)
  6365. return block_rsv;
  6366. if (block_rsv->failfast)
  6367. return ERR_PTR(ret);
  6368. if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
  6369. global_updated = true;
  6370. update_global_block_rsv(root->fs_info);
  6371. goto again;
  6372. }
  6373. if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
  6374. static DEFINE_RATELIMIT_STATE(_rs,
  6375. DEFAULT_RATELIMIT_INTERVAL * 10,
  6376. /*DEFAULT_RATELIMIT_BURST*/ 1);
  6377. if (__ratelimit(&_rs))
  6378. WARN(1, KERN_DEBUG
  6379. "BTRFS: block rsv returned %d\n", ret);
  6380. }
  6381. try_reserve:
  6382. ret = reserve_metadata_bytes(root, block_rsv, blocksize,
  6383. BTRFS_RESERVE_NO_FLUSH);
  6384. if (!ret)
  6385. return block_rsv;
  6386. /*
  6387. * If we couldn't reserve metadata bytes try and use some from
  6388. * the global reserve if its space type is the same as the global
  6389. * reservation.
  6390. */
  6391. if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
  6392. block_rsv->space_info == global_rsv->space_info) {
  6393. ret = block_rsv_use_bytes(global_rsv, blocksize);
  6394. if (!ret)
  6395. return global_rsv;
  6396. }
  6397. return ERR_PTR(ret);
  6398. }
  6399. static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
  6400. struct btrfs_block_rsv *block_rsv, u32 blocksize)
  6401. {
  6402. block_rsv_add_bytes(block_rsv, blocksize, 0);
  6403. block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
  6404. }
  6405. /*
  6406. * finds a free extent and does all the dirty work required for allocation
  6407. * returns the key for the extent through ins, and a tree buffer for
  6408. * the first block of the extent through buf.
  6409. *
  6410. * returns the tree buffer or NULL.
  6411. */
  6412. struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
  6413. struct btrfs_root *root,
  6414. u64 parent, u64 root_objectid,
  6415. struct btrfs_disk_key *key, int level,
  6416. u64 hint, u64 empty_size)
  6417. {
  6418. struct btrfs_key ins;
  6419. struct btrfs_block_rsv *block_rsv;
  6420. struct extent_buffer *buf;
  6421. u64 flags = 0;
  6422. int ret;
  6423. u32 blocksize = root->nodesize;
  6424. bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
  6425. SKINNY_METADATA);
  6426. if (btrfs_test_is_dummy_root(root)) {
  6427. buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
  6428. level);
  6429. if (!IS_ERR(buf))
  6430. root->alloc_bytenr += blocksize;
  6431. return buf;
  6432. }
  6433. block_rsv = use_block_rsv(trans, root, blocksize);
  6434. if (IS_ERR(block_rsv))
  6435. return ERR_CAST(block_rsv);
  6436. ret = btrfs_reserve_extent(root, blocksize, blocksize,
  6437. empty_size, hint, &ins, 0, 0);
  6438. if (ret) {
  6439. unuse_block_rsv(root->fs_info, block_rsv, blocksize);
  6440. return ERR_PTR(ret);
  6441. }
  6442. buf = btrfs_init_new_buffer(trans, root, ins.objectid, level);
  6443. BUG_ON(IS_ERR(buf)); /* -ENOMEM */
  6444. if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
  6445. if (parent == 0)
  6446. parent = ins.objectid;
  6447. flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
  6448. } else
  6449. BUG_ON(parent > 0);
  6450. if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
  6451. struct btrfs_delayed_extent_op *extent_op;
  6452. extent_op = btrfs_alloc_delayed_extent_op();
  6453. BUG_ON(!extent_op); /* -ENOMEM */
  6454. if (key)
  6455. memcpy(&extent_op->key, key, sizeof(extent_op->key));
  6456. else
  6457. memset(&extent_op->key, 0, sizeof(extent_op->key));
  6458. extent_op->flags_to_set = flags;
  6459. if (skinny_metadata)
  6460. extent_op->update_key = 0;
  6461. else
  6462. extent_op->update_key = 1;
  6463. extent_op->update_flags = 1;
  6464. extent_op->is_data = 0;
  6465. extent_op->level = level;
  6466. ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
  6467. ins.objectid,
  6468. ins.offset, parent, root_objectid,
  6469. level, BTRFS_ADD_DELAYED_EXTENT,
  6470. extent_op, 0);
  6471. BUG_ON(ret); /* -ENOMEM */
  6472. }
  6473. return buf;
  6474. }
  6475. struct walk_control {
  6476. u64 refs[BTRFS_MAX_LEVEL];
  6477. u64 flags[BTRFS_MAX_LEVEL];
  6478. struct btrfs_key update_progress;
  6479. int stage;
  6480. int level;
  6481. int shared_level;
  6482. int update_ref;
  6483. int keep_locks;
  6484. int reada_slot;
  6485. int reada_count;
  6486. int for_reloc;
  6487. };
  6488. #define DROP_REFERENCE 1
  6489. #define UPDATE_BACKREF 2
  6490. static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
  6491. struct btrfs_root *root,
  6492. struct walk_control *wc,
  6493. struct btrfs_path *path)
  6494. {
  6495. u64 bytenr;
  6496. u64 generation;
  6497. u64 refs;
  6498. u64 flags;
  6499. u32 nritems;
  6500. u32 blocksize;
  6501. struct btrfs_key key;
  6502. struct extent_buffer *eb;
  6503. int ret;
  6504. int slot;
  6505. int nread = 0;
  6506. if (path->slots[wc->level] < wc->reada_slot) {
  6507. wc->reada_count = wc->reada_count * 2 / 3;
  6508. wc->reada_count = max(wc->reada_count, 2);
  6509. } else {
  6510. wc->reada_count = wc->reada_count * 3 / 2;
  6511. wc->reada_count = min_t(int, wc->reada_count,
  6512. BTRFS_NODEPTRS_PER_BLOCK(root));
  6513. }
  6514. eb = path->nodes[wc->level];
  6515. nritems = btrfs_header_nritems(eb);
  6516. blocksize = root->nodesize;
  6517. for (slot = path->slots[wc->level]; slot < nritems; slot++) {
  6518. if (nread >= wc->reada_count)
  6519. break;
  6520. cond_resched();
  6521. bytenr = btrfs_node_blockptr(eb, slot);
  6522. generation = btrfs_node_ptr_generation(eb, slot);
  6523. if (slot == path->slots[wc->level])
  6524. goto reada;
  6525. if (wc->stage == UPDATE_BACKREF &&
  6526. generation <= root->root_key.offset)
  6527. continue;
  6528. /* We don't lock the tree block, it's OK to be racy here */
  6529. ret = btrfs_lookup_extent_info(trans, root, bytenr,
  6530. wc->level - 1, 1, &refs,
  6531. &flags);
  6532. /* We don't care about errors in readahead. */
  6533. if (ret < 0)
  6534. continue;
  6535. BUG_ON(refs == 0);
  6536. if (wc->stage == DROP_REFERENCE) {
  6537. if (refs == 1)
  6538. goto reada;
  6539. if (wc->level == 1 &&
  6540. (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  6541. continue;
  6542. if (!wc->update_ref ||
  6543. generation <= root->root_key.offset)
  6544. continue;
  6545. btrfs_node_key_to_cpu(eb, &key, slot);
  6546. ret = btrfs_comp_cpu_keys(&key,
  6547. &wc->update_progress);
  6548. if (ret < 0)
  6549. continue;
  6550. } else {
  6551. if (wc->level == 1 &&
  6552. (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  6553. continue;
  6554. }
  6555. reada:
  6556. readahead_tree_block(root, bytenr);
  6557. nread++;
  6558. }
  6559. wc->reada_slot = slot;
  6560. }
  6561. static int account_leaf_items(struct btrfs_trans_handle *trans,
  6562. struct btrfs_root *root,
  6563. struct extent_buffer *eb)
  6564. {
  6565. int nr = btrfs_header_nritems(eb);
  6566. int i, extent_type, ret;
  6567. struct btrfs_key key;
  6568. struct btrfs_file_extent_item *fi;
  6569. u64 bytenr, num_bytes;
  6570. for (i = 0; i < nr; i++) {
  6571. btrfs_item_key_to_cpu(eb, &key, i);
  6572. if (key.type != BTRFS_EXTENT_DATA_KEY)
  6573. continue;
  6574. fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
  6575. /* filter out non qgroup-accountable extents */
  6576. extent_type = btrfs_file_extent_type(eb, fi);
  6577. if (extent_type == BTRFS_FILE_EXTENT_INLINE)
  6578. continue;
  6579. bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
  6580. if (!bytenr)
  6581. continue;
  6582. num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
  6583. ret = btrfs_qgroup_record_ref(trans, root->fs_info,
  6584. root->objectid,
  6585. bytenr, num_bytes,
  6586. BTRFS_QGROUP_OPER_SUB_SUBTREE, 0);
  6587. if (ret)
  6588. return ret;
  6589. }
  6590. return 0;
  6591. }
  6592. /*
  6593. * Walk up the tree from the bottom, freeing leaves and any interior
  6594. * nodes which have had all slots visited. If a node (leaf or
  6595. * interior) is freed, the node above it will have it's slot
  6596. * incremented. The root node will never be freed.
  6597. *
  6598. * At the end of this function, we should have a path which has all
  6599. * slots incremented to the next position for a search. If we need to
  6600. * read a new node it will be NULL and the node above it will have the
  6601. * correct slot selected for a later read.
  6602. *
  6603. * If we increment the root nodes slot counter past the number of
  6604. * elements, 1 is returned to signal completion of the search.
  6605. */
  6606. static int adjust_slots_upwards(struct btrfs_root *root,
  6607. struct btrfs_path *path, int root_level)
  6608. {
  6609. int level = 0;
  6610. int nr, slot;
  6611. struct extent_buffer *eb;
  6612. if (root_level == 0)
  6613. return 1;
  6614. while (level <= root_level) {
  6615. eb = path->nodes[level];
  6616. nr = btrfs_header_nritems(eb);
  6617. path->slots[level]++;
  6618. slot = path->slots[level];
  6619. if (slot >= nr || level == 0) {
  6620. /*
  6621. * Don't free the root - we will detect this
  6622. * condition after our loop and return a
  6623. * positive value for caller to stop walking the tree.
  6624. */
  6625. if (level != root_level) {
  6626. btrfs_tree_unlock_rw(eb, path->locks[level]);
  6627. path->locks[level] = 0;
  6628. free_extent_buffer(eb);
  6629. path->nodes[level] = NULL;
  6630. path->slots[level] = 0;
  6631. }
  6632. } else {
  6633. /*
  6634. * We have a valid slot to walk back down
  6635. * from. Stop here so caller can process these
  6636. * new nodes.
  6637. */
  6638. break;
  6639. }
  6640. level++;
  6641. }
  6642. eb = path->nodes[root_level];
  6643. if (path->slots[root_level] >= btrfs_header_nritems(eb))
  6644. return 1;
  6645. return 0;
  6646. }
  6647. /*
  6648. * root_eb is the subtree root and is locked before this function is called.
  6649. */
  6650. static int account_shared_subtree(struct btrfs_trans_handle *trans,
  6651. struct btrfs_root *root,
  6652. struct extent_buffer *root_eb,
  6653. u64 root_gen,
  6654. int root_level)
  6655. {
  6656. int ret = 0;
  6657. int level;
  6658. struct extent_buffer *eb = root_eb;
  6659. struct btrfs_path *path = NULL;
  6660. BUG_ON(root_level < 0 || root_level > BTRFS_MAX_LEVEL);
  6661. BUG_ON(root_eb == NULL);
  6662. if (!root->fs_info->quota_enabled)
  6663. return 0;
  6664. if (!extent_buffer_uptodate(root_eb)) {
  6665. ret = btrfs_read_buffer(root_eb, root_gen);
  6666. if (ret)
  6667. goto out;
  6668. }
  6669. if (root_level == 0) {
  6670. ret = account_leaf_items(trans, root, root_eb);
  6671. goto out;
  6672. }
  6673. path = btrfs_alloc_path();
  6674. if (!path)
  6675. return -ENOMEM;
  6676. /*
  6677. * Walk down the tree. Missing extent blocks are filled in as
  6678. * we go. Metadata is accounted every time we read a new
  6679. * extent block.
  6680. *
  6681. * When we reach a leaf, we account for file extent items in it,
  6682. * walk back up the tree (adjusting slot pointers as we go)
  6683. * and restart the search process.
  6684. */
  6685. extent_buffer_get(root_eb); /* For path */
  6686. path->nodes[root_level] = root_eb;
  6687. path->slots[root_level] = 0;
  6688. path->locks[root_level] = 0; /* so release_path doesn't try to unlock */
  6689. walk_down:
  6690. level = root_level;
  6691. while (level >= 0) {
  6692. if (path->nodes[level] == NULL) {
  6693. int parent_slot;
  6694. u64 child_gen;
  6695. u64 child_bytenr;
  6696. /* We need to get child blockptr/gen from
  6697. * parent before we can read it. */
  6698. eb = path->nodes[level + 1];
  6699. parent_slot = path->slots[level + 1];
  6700. child_bytenr = btrfs_node_blockptr(eb, parent_slot);
  6701. child_gen = btrfs_node_ptr_generation(eb, parent_slot);
  6702. eb = read_tree_block(root, child_bytenr, child_gen);
  6703. if (!eb || !extent_buffer_uptodate(eb)) {
  6704. ret = -EIO;
  6705. goto out;
  6706. }
  6707. path->nodes[level] = eb;
  6708. path->slots[level] = 0;
  6709. btrfs_tree_read_lock(eb);
  6710. btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
  6711. path->locks[level] = BTRFS_READ_LOCK_BLOCKING;
  6712. ret = btrfs_qgroup_record_ref(trans, root->fs_info,
  6713. root->objectid,
  6714. child_bytenr,
  6715. root->nodesize,
  6716. BTRFS_QGROUP_OPER_SUB_SUBTREE,
  6717. 0);
  6718. if (ret)
  6719. goto out;
  6720. }
  6721. if (level == 0) {
  6722. ret = account_leaf_items(trans, root, path->nodes[level]);
  6723. if (ret)
  6724. goto out;
  6725. /* Nonzero return here means we completed our search */
  6726. ret = adjust_slots_upwards(root, path, root_level);
  6727. if (ret)
  6728. break;
  6729. /* Restart search with new slots */
  6730. goto walk_down;
  6731. }
  6732. level--;
  6733. }
  6734. ret = 0;
  6735. out:
  6736. btrfs_free_path(path);
  6737. return ret;
  6738. }
  6739. /*
  6740. * helper to process tree block while walking down the tree.
  6741. *
  6742. * when wc->stage == UPDATE_BACKREF, this function updates
  6743. * back refs for pointers in the block.
  6744. *
  6745. * NOTE: return value 1 means we should stop walking down.
  6746. */
  6747. static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
  6748. struct btrfs_root *root,
  6749. struct btrfs_path *path,
  6750. struct walk_control *wc, int lookup_info)
  6751. {
  6752. int level = wc->level;
  6753. struct extent_buffer *eb = path->nodes[level];
  6754. u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  6755. int ret;
  6756. if (wc->stage == UPDATE_BACKREF &&
  6757. btrfs_header_owner(eb) != root->root_key.objectid)
  6758. return 1;
  6759. /*
  6760. * when reference count of tree block is 1, it won't increase
  6761. * again. once full backref flag is set, we never clear it.
  6762. */
  6763. if (lookup_info &&
  6764. ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
  6765. (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
  6766. BUG_ON(!path->locks[level]);
  6767. ret = btrfs_lookup_extent_info(trans, root,
  6768. eb->start, level, 1,
  6769. &wc->refs[level],
  6770. &wc->flags[level]);
  6771. BUG_ON(ret == -ENOMEM);
  6772. if (ret)
  6773. return ret;
  6774. BUG_ON(wc->refs[level] == 0);
  6775. }
  6776. if (wc->stage == DROP_REFERENCE) {
  6777. if (wc->refs[level] > 1)
  6778. return 1;
  6779. if (path->locks[level] && !wc->keep_locks) {
  6780. btrfs_tree_unlock_rw(eb, path->locks[level]);
  6781. path->locks[level] = 0;
  6782. }
  6783. return 0;
  6784. }
  6785. /* wc->stage == UPDATE_BACKREF */
  6786. if (!(wc->flags[level] & flag)) {
  6787. BUG_ON(!path->locks[level]);
  6788. ret = btrfs_inc_ref(trans, root, eb, 1);
  6789. BUG_ON(ret); /* -ENOMEM */
  6790. ret = btrfs_dec_ref(trans, root, eb, 0);
  6791. BUG_ON(ret); /* -ENOMEM */
  6792. ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
  6793. eb->len, flag,
  6794. btrfs_header_level(eb), 0);
  6795. BUG_ON(ret); /* -ENOMEM */
  6796. wc->flags[level] |= flag;
  6797. }
  6798. /*
  6799. * the block is shared by multiple trees, so it's not good to
  6800. * keep the tree lock
  6801. */
  6802. if (path->locks[level] && level > 0) {
  6803. btrfs_tree_unlock_rw(eb, path->locks[level]);
  6804. path->locks[level] = 0;
  6805. }
  6806. return 0;
  6807. }
  6808. /*
  6809. * helper to process tree block pointer.
  6810. *
  6811. * when wc->stage == DROP_REFERENCE, this function checks
  6812. * reference count of the block pointed to. if the block
  6813. * is shared and we need update back refs for the subtree
  6814. * rooted at the block, this function changes wc->stage to
  6815. * UPDATE_BACKREF. if the block is shared and there is no
  6816. * need to update back, this function drops the reference
  6817. * to the block.
  6818. *
  6819. * NOTE: return value 1 means we should stop walking down.
  6820. */
  6821. static noinline int do_walk_down(struct btrfs_trans_handle *trans,
  6822. struct btrfs_root *root,
  6823. struct btrfs_path *path,
  6824. struct walk_control *wc, int *lookup_info)
  6825. {
  6826. u64 bytenr;
  6827. u64 generation;
  6828. u64 parent;
  6829. u32 blocksize;
  6830. struct btrfs_key key;
  6831. struct extent_buffer *next;
  6832. int level = wc->level;
  6833. int reada = 0;
  6834. int ret = 0;
  6835. bool need_account = false;
  6836. generation = btrfs_node_ptr_generation(path->nodes[level],
  6837. path->slots[level]);
  6838. /*
  6839. * if the lower level block was created before the snapshot
  6840. * was created, we know there is no need to update back refs
  6841. * for the subtree
  6842. */
  6843. if (wc->stage == UPDATE_BACKREF &&
  6844. generation <= root->root_key.offset) {
  6845. *lookup_info = 1;
  6846. return 1;
  6847. }
  6848. bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
  6849. blocksize = root->nodesize;
  6850. next = btrfs_find_tree_block(root, bytenr);
  6851. if (!next) {
  6852. next = btrfs_find_create_tree_block(root, bytenr);
  6853. if (!next)
  6854. return -ENOMEM;
  6855. btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
  6856. level - 1);
  6857. reada = 1;
  6858. }
  6859. btrfs_tree_lock(next);
  6860. btrfs_set_lock_blocking(next);
  6861. ret = btrfs_lookup_extent_info(trans, root, bytenr, level - 1, 1,
  6862. &wc->refs[level - 1],
  6863. &wc->flags[level - 1]);
  6864. if (ret < 0) {
  6865. btrfs_tree_unlock(next);
  6866. return ret;
  6867. }
  6868. if (unlikely(wc->refs[level - 1] == 0)) {
  6869. btrfs_err(root->fs_info, "Missing references.");
  6870. BUG();
  6871. }
  6872. *lookup_info = 0;
  6873. if (wc->stage == DROP_REFERENCE) {
  6874. if (wc->refs[level - 1] > 1) {
  6875. need_account = true;
  6876. if (level == 1 &&
  6877. (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  6878. goto skip;
  6879. if (!wc->update_ref ||
  6880. generation <= root->root_key.offset)
  6881. goto skip;
  6882. btrfs_node_key_to_cpu(path->nodes[level], &key,
  6883. path->slots[level]);
  6884. ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
  6885. if (ret < 0)
  6886. goto skip;
  6887. wc->stage = UPDATE_BACKREF;
  6888. wc->shared_level = level - 1;
  6889. }
  6890. } else {
  6891. if (level == 1 &&
  6892. (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  6893. goto skip;
  6894. }
  6895. if (!btrfs_buffer_uptodate(next, generation, 0)) {
  6896. btrfs_tree_unlock(next);
  6897. free_extent_buffer(next);
  6898. next = NULL;
  6899. *lookup_info = 1;
  6900. }
  6901. if (!next) {
  6902. if (reada && level == 1)
  6903. reada_walk_down(trans, root, wc, path);
  6904. next = read_tree_block(root, bytenr, generation);
  6905. if (!next || !extent_buffer_uptodate(next)) {
  6906. free_extent_buffer(next);
  6907. return -EIO;
  6908. }
  6909. btrfs_tree_lock(next);
  6910. btrfs_set_lock_blocking(next);
  6911. }
  6912. level--;
  6913. BUG_ON(level != btrfs_header_level(next));
  6914. path->nodes[level] = next;
  6915. path->slots[level] = 0;
  6916. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  6917. wc->level = level;
  6918. if (wc->level == 1)
  6919. wc->reada_slot = 0;
  6920. return 0;
  6921. skip:
  6922. wc->refs[level - 1] = 0;
  6923. wc->flags[level - 1] = 0;
  6924. if (wc->stage == DROP_REFERENCE) {
  6925. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
  6926. parent = path->nodes[level]->start;
  6927. } else {
  6928. BUG_ON(root->root_key.objectid !=
  6929. btrfs_header_owner(path->nodes[level]));
  6930. parent = 0;
  6931. }
  6932. if (need_account) {
  6933. ret = account_shared_subtree(trans, root, next,
  6934. generation, level - 1);
  6935. if (ret) {
  6936. printk_ratelimited(KERN_ERR "BTRFS: %s Error "
  6937. "%d accounting shared subtree. Quota "
  6938. "is out of sync, rescan required.\n",
  6939. root->fs_info->sb->s_id, ret);
  6940. }
  6941. }
  6942. ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
  6943. root->root_key.objectid, level - 1, 0, 0);
  6944. BUG_ON(ret); /* -ENOMEM */
  6945. }
  6946. btrfs_tree_unlock(next);
  6947. free_extent_buffer(next);
  6948. *lookup_info = 1;
  6949. return 1;
  6950. }
  6951. /*
  6952. * helper to process tree block while walking up the tree.
  6953. *
  6954. * when wc->stage == DROP_REFERENCE, this function drops
  6955. * reference count on the block.
  6956. *
  6957. * when wc->stage == UPDATE_BACKREF, this function changes
  6958. * wc->stage back to DROP_REFERENCE if we changed wc->stage
  6959. * to UPDATE_BACKREF previously while processing the block.
  6960. *
  6961. * NOTE: return value 1 means we should stop walking up.
  6962. */
  6963. static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
  6964. struct btrfs_root *root,
  6965. struct btrfs_path *path,
  6966. struct walk_control *wc)
  6967. {
  6968. int ret;
  6969. int level = wc->level;
  6970. struct extent_buffer *eb = path->nodes[level];
  6971. u64 parent = 0;
  6972. if (wc->stage == UPDATE_BACKREF) {
  6973. BUG_ON(wc->shared_level < level);
  6974. if (level < wc->shared_level)
  6975. goto out;
  6976. ret = find_next_key(path, level + 1, &wc->update_progress);
  6977. if (ret > 0)
  6978. wc->update_ref = 0;
  6979. wc->stage = DROP_REFERENCE;
  6980. wc->shared_level = -1;
  6981. path->slots[level] = 0;
  6982. /*
  6983. * check reference count again if the block isn't locked.
  6984. * we should start walking down the tree again if reference
  6985. * count is one.
  6986. */
  6987. if (!path->locks[level]) {
  6988. BUG_ON(level == 0);
  6989. btrfs_tree_lock(eb);
  6990. btrfs_set_lock_blocking(eb);
  6991. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  6992. ret = btrfs_lookup_extent_info(trans, root,
  6993. eb->start, level, 1,
  6994. &wc->refs[level],
  6995. &wc->flags[level]);
  6996. if (ret < 0) {
  6997. btrfs_tree_unlock_rw(eb, path->locks[level]);
  6998. path->locks[level] = 0;
  6999. return ret;
  7000. }
  7001. BUG_ON(wc->refs[level] == 0);
  7002. if (wc->refs[level] == 1) {
  7003. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7004. path->locks[level] = 0;
  7005. return 1;
  7006. }
  7007. }
  7008. }
  7009. /* wc->stage == DROP_REFERENCE */
  7010. BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
  7011. if (wc->refs[level] == 1) {
  7012. if (level == 0) {
  7013. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  7014. ret = btrfs_dec_ref(trans, root, eb, 1);
  7015. else
  7016. ret = btrfs_dec_ref(trans, root, eb, 0);
  7017. BUG_ON(ret); /* -ENOMEM */
  7018. ret = account_leaf_items(trans, root, eb);
  7019. if (ret) {
  7020. printk_ratelimited(KERN_ERR "BTRFS: %s Error "
  7021. "%d accounting leaf items. Quota "
  7022. "is out of sync, rescan required.\n",
  7023. root->fs_info->sb->s_id, ret);
  7024. }
  7025. }
  7026. /* make block locked assertion in clean_tree_block happy */
  7027. if (!path->locks[level] &&
  7028. btrfs_header_generation(eb) == trans->transid) {
  7029. btrfs_tree_lock(eb);
  7030. btrfs_set_lock_blocking(eb);
  7031. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7032. }
  7033. clean_tree_block(trans, root, eb);
  7034. }
  7035. if (eb == root->node) {
  7036. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  7037. parent = eb->start;
  7038. else
  7039. BUG_ON(root->root_key.objectid !=
  7040. btrfs_header_owner(eb));
  7041. } else {
  7042. if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  7043. parent = path->nodes[level + 1]->start;
  7044. else
  7045. BUG_ON(root->root_key.objectid !=
  7046. btrfs_header_owner(path->nodes[level + 1]));
  7047. }
  7048. btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
  7049. out:
  7050. wc->refs[level] = 0;
  7051. wc->flags[level] = 0;
  7052. return 0;
  7053. }
  7054. static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
  7055. struct btrfs_root *root,
  7056. struct btrfs_path *path,
  7057. struct walk_control *wc)
  7058. {
  7059. int level = wc->level;
  7060. int lookup_info = 1;
  7061. int ret;
  7062. while (level >= 0) {
  7063. ret = walk_down_proc(trans, root, path, wc, lookup_info);
  7064. if (ret > 0)
  7065. break;
  7066. if (level == 0)
  7067. break;
  7068. if (path->slots[level] >=
  7069. btrfs_header_nritems(path->nodes[level]))
  7070. break;
  7071. ret = do_walk_down(trans, root, path, wc, &lookup_info);
  7072. if (ret > 0) {
  7073. path->slots[level]++;
  7074. continue;
  7075. } else if (ret < 0)
  7076. return ret;
  7077. level = wc->level;
  7078. }
  7079. return 0;
  7080. }
  7081. static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
  7082. struct btrfs_root *root,
  7083. struct btrfs_path *path,
  7084. struct walk_control *wc, int max_level)
  7085. {
  7086. int level = wc->level;
  7087. int ret;
  7088. path->slots[level] = btrfs_header_nritems(path->nodes[level]);
  7089. while (level < max_level && path->nodes[level]) {
  7090. wc->level = level;
  7091. if (path->slots[level] + 1 <
  7092. btrfs_header_nritems(path->nodes[level])) {
  7093. path->slots[level]++;
  7094. return 0;
  7095. } else {
  7096. ret = walk_up_proc(trans, root, path, wc);
  7097. if (ret > 0)
  7098. return 0;
  7099. if (path->locks[level]) {
  7100. btrfs_tree_unlock_rw(path->nodes[level],
  7101. path->locks[level]);
  7102. path->locks[level] = 0;
  7103. }
  7104. free_extent_buffer(path->nodes[level]);
  7105. path->nodes[level] = NULL;
  7106. level++;
  7107. }
  7108. }
  7109. return 1;
  7110. }
  7111. /*
  7112. * drop a subvolume tree.
  7113. *
  7114. * this function traverses the tree freeing any blocks that only
  7115. * referenced by the tree.
  7116. *
  7117. * when a shared tree block is found. this function decreases its
  7118. * reference count by one. if update_ref is true, this function
  7119. * also make sure backrefs for the shared block and all lower level
  7120. * blocks are properly updated.
  7121. *
  7122. * If called with for_reloc == 0, may exit early with -EAGAIN
  7123. */
  7124. int btrfs_drop_snapshot(struct btrfs_root *root,
  7125. struct btrfs_block_rsv *block_rsv, int update_ref,
  7126. int for_reloc)
  7127. {
  7128. struct btrfs_path *path;
  7129. struct btrfs_trans_handle *trans;
  7130. struct btrfs_root *tree_root = root->fs_info->tree_root;
  7131. struct btrfs_root_item *root_item = &root->root_item;
  7132. struct walk_control *wc;
  7133. struct btrfs_key key;
  7134. int err = 0;
  7135. int ret;
  7136. int level;
  7137. bool root_dropped = false;
  7138. btrfs_debug(root->fs_info, "Drop subvolume %llu", root->objectid);
  7139. path = btrfs_alloc_path();
  7140. if (!path) {
  7141. err = -ENOMEM;
  7142. goto out;
  7143. }
  7144. wc = kzalloc(sizeof(*wc), GFP_NOFS);
  7145. if (!wc) {
  7146. btrfs_free_path(path);
  7147. err = -ENOMEM;
  7148. goto out;
  7149. }
  7150. trans = btrfs_start_transaction(tree_root, 0);
  7151. if (IS_ERR(trans)) {
  7152. err = PTR_ERR(trans);
  7153. goto out_free;
  7154. }
  7155. if (block_rsv)
  7156. trans->block_rsv = block_rsv;
  7157. if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
  7158. level = btrfs_header_level(root->node);
  7159. path->nodes[level] = btrfs_lock_root_node(root);
  7160. btrfs_set_lock_blocking(path->nodes[level]);
  7161. path->slots[level] = 0;
  7162. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7163. memset(&wc->update_progress, 0,
  7164. sizeof(wc->update_progress));
  7165. } else {
  7166. btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
  7167. memcpy(&wc->update_progress, &key,
  7168. sizeof(wc->update_progress));
  7169. level = root_item->drop_level;
  7170. BUG_ON(level == 0);
  7171. path->lowest_level = level;
  7172. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  7173. path->lowest_level = 0;
  7174. if (ret < 0) {
  7175. err = ret;
  7176. goto out_end_trans;
  7177. }
  7178. WARN_ON(ret > 0);
  7179. /*
  7180. * unlock our path, this is safe because only this
  7181. * function is allowed to delete this snapshot
  7182. */
  7183. btrfs_unlock_up_safe(path, 0);
  7184. level = btrfs_header_level(root->node);
  7185. while (1) {
  7186. btrfs_tree_lock(path->nodes[level]);
  7187. btrfs_set_lock_blocking(path->nodes[level]);
  7188. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7189. ret = btrfs_lookup_extent_info(trans, root,
  7190. path->nodes[level]->start,
  7191. level, 1, &wc->refs[level],
  7192. &wc->flags[level]);
  7193. if (ret < 0) {
  7194. err = ret;
  7195. goto out_end_trans;
  7196. }
  7197. BUG_ON(wc->refs[level] == 0);
  7198. if (level == root_item->drop_level)
  7199. break;
  7200. btrfs_tree_unlock(path->nodes[level]);
  7201. path->locks[level] = 0;
  7202. WARN_ON(wc->refs[level] != 1);
  7203. level--;
  7204. }
  7205. }
  7206. wc->level = level;
  7207. wc->shared_level = -1;
  7208. wc->stage = DROP_REFERENCE;
  7209. wc->update_ref = update_ref;
  7210. wc->keep_locks = 0;
  7211. wc->for_reloc = for_reloc;
  7212. wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
  7213. while (1) {
  7214. ret = walk_down_tree(trans, root, path, wc);
  7215. if (ret < 0) {
  7216. err = ret;
  7217. break;
  7218. }
  7219. ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
  7220. if (ret < 0) {
  7221. err = ret;
  7222. break;
  7223. }
  7224. if (ret > 0) {
  7225. BUG_ON(wc->stage != DROP_REFERENCE);
  7226. break;
  7227. }
  7228. if (wc->stage == DROP_REFERENCE) {
  7229. level = wc->level;
  7230. btrfs_node_key(path->nodes[level],
  7231. &root_item->drop_progress,
  7232. path->slots[level]);
  7233. root_item->drop_level = level;
  7234. }
  7235. BUG_ON(wc->level == 0);
  7236. if (btrfs_should_end_transaction(trans, tree_root) ||
  7237. (!for_reloc && btrfs_need_cleaner_sleep(root))) {
  7238. ret = btrfs_update_root(trans, tree_root,
  7239. &root->root_key,
  7240. root_item);
  7241. if (ret) {
  7242. btrfs_abort_transaction(trans, tree_root, ret);
  7243. err = ret;
  7244. goto out_end_trans;
  7245. }
  7246. /*
  7247. * Qgroup update accounting is run from
  7248. * delayed ref handling. This usually works
  7249. * out because delayed refs are normally the
  7250. * only way qgroup updates are added. However,
  7251. * we may have added updates during our tree
  7252. * walk so run qgroups here to make sure we
  7253. * don't lose any updates.
  7254. */
  7255. ret = btrfs_delayed_qgroup_accounting(trans,
  7256. root->fs_info);
  7257. if (ret)
  7258. printk_ratelimited(KERN_ERR "BTRFS: Failure %d "
  7259. "running qgroup updates "
  7260. "during snapshot delete. "
  7261. "Quota is out of sync, "
  7262. "rescan required.\n", ret);
  7263. btrfs_end_transaction_throttle(trans, tree_root);
  7264. if (!for_reloc && btrfs_need_cleaner_sleep(root)) {
  7265. pr_debug("BTRFS: drop snapshot early exit\n");
  7266. err = -EAGAIN;
  7267. goto out_free;
  7268. }
  7269. trans = btrfs_start_transaction(tree_root, 0);
  7270. if (IS_ERR(trans)) {
  7271. err = PTR_ERR(trans);
  7272. goto out_free;
  7273. }
  7274. if (block_rsv)
  7275. trans->block_rsv = block_rsv;
  7276. }
  7277. }
  7278. btrfs_release_path(path);
  7279. if (err)
  7280. goto out_end_trans;
  7281. ret = btrfs_del_root(trans, tree_root, &root->root_key);
  7282. if (ret) {
  7283. btrfs_abort_transaction(trans, tree_root, ret);
  7284. goto out_end_trans;
  7285. }
  7286. if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
  7287. ret = btrfs_find_root(tree_root, &root->root_key, path,
  7288. NULL, NULL);
  7289. if (ret < 0) {
  7290. btrfs_abort_transaction(trans, tree_root, ret);
  7291. err = ret;
  7292. goto out_end_trans;
  7293. } else if (ret > 0) {
  7294. /* if we fail to delete the orphan item this time
  7295. * around, it'll get picked up the next time.
  7296. *
  7297. * The most common failure here is just -ENOENT.
  7298. */
  7299. btrfs_del_orphan_item(trans, tree_root,
  7300. root->root_key.objectid);
  7301. }
  7302. }
  7303. if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
  7304. btrfs_drop_and_free_fs_root(tree_root->fs_info, root);
  7305. } else {
  7306. free_extent_buffer(root->node);
  7307. free_extent_buffer(root->commit_root);
  7308. btrfs_put_fs_root(root);
  7309. }
  7310. root_dropped = true;
  7311. out_end_trans:
  7312. ret = btrfs_delayed_qgroup_accounting(trans, tree_root->fs_info);
  7313. if (ret)
  7314. printk_ratelimited(KERN_ERR "BTRFS: Failure %d "
  7315. "running qgroup updates "
  7316. "during snapshot delete. "
  7317. "Quota is out of sync, "
  7318. "rescan required.\n", ret);
  7319. btrfs_end_transaction_throttle(trans, tree_root);
  7320. out_free:
  7321. kfree(wc);
  7322. btrfs_free_path(path);
  7323. out:
  7324. /*
  7325. * So if we need to stop dropping the snapshot for whatever reason we
  7326. * need to make sure to add it back to the dead root list so that we
  7327. * keep trying to do the work later. This also cleans up roots if we
  7328. * don't have it in the radix (like when we recover after a power fail
  7329. * or unmount) so we don't leak memory.
  7330. */
  7331. if (!for_reloc && root_dropped == false)
  7332. btrfs_add_dead_root(root);
  7333. if (err && err != -EAGAIN)
  7334. btrfs_std_error(root->fs_info, err);
  7335. return err;
  7336. }
  7337. /*
  7338. * drop subtree rooted at tree block 'node'.
  7339. *
  7340. * NOTE: this function will unlock and release tree block 'node'
  7341. * only used by relocation code
  7342. */
  7343. int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
  7344. struct btrfs_root *root,
  7345. struct extent_buffer *node,
  7346. struct extent_buffer *parent)
  7347. {
  7348. struct btrfs_path *path;
  7349. struct walk_control *wc;
  7350. int level;
  7351. int parent_level;
  7352. int ret = 0;
  7353. int wret;
  7354. BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
  7355. path = btrfs_alloc_path();
  7356. if (!path)
  7357. return -ENOMEM;
  7358. wc = kzalloc(sizeof(*wc), GFP_NOFS);
  7359. if (!wc) {
  7360. btrfs_free_path(path);
  7361. return -ENOMEM;
  7362. }
  7363. btrfs_assert_tree_locked(parent);
  7364. parent_level = btrfs_header_level(parent);
  7365. extent_buffer_get(parent);
  7366. path->nodes[parent_level] = parent;
  7367. path->slots[parent_level] = btrfs_header_nritems(parent);
  7368. btrfs_assert_tree_locked(node);
  7369. level = btrfs_header_level(node);
  7370. path->nodes[level] = node;
  7371. path->slots[level] = 0;
  7372. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7373. wc->refs[parent_level] = 1;
  7374. wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  7375. wc->level = level;
  7376. wc->shared_level = -1;
  7377. wc->stage = DROP_REFERENCE;
  7378. wc->update_ref = 0;
  7379. wc->keep_locks = 1;
  7380. wc->for_reloc = 1;
  7381. wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
  7382. while (1) {
  7383. wret = walk_down_tree(trans, root, path, wc);
  7384. if (wret < 0) {
  7385. ret = wret;
  7386. break;
  7387. }
  7388. wret = walk_up_tree(trans, root, path, wc, parent_level);
  7389. if (wret < 0)
  7390. ret = wret;
  7391. if (wret != 0)
  7392. break;
  7393. }
  7394. kfree(wc);
  7395. btrfs_free_path(path);
  7396. return ret;
  7397. }
  7398. static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
  7399. {
  7400. u64 num_devices;
  7401. u64 stripped;
  7402. /*
  7403. * if restripe for this chunk_type is on pick target profile and
  7404. * return, otherwise do the usual balance
  7405. */
  7406. stripped = get_restripe_target(root->fs_info, flags);
  7407. if (stripped)
  7408. return extended_to_chunk(stripped);
  7409. num_devices = root->fs_info->fs_devices->rw_devices;
  7410. stripped = BTRFS_BLOCK_GROUP_RAID0 |
  7411. BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
  7412. BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
  7413. if (num_devices == 1) {
  7414. stripped |= BTRFS_BLOCK_GROUP_DUP;
  7415. stripped = flags & ~stripped;
  7416. /* turn raid0 into single device chunks */
  7417. if (flags & BTRFS_BLOCK_GROUP_RAID0)
  7418. return stripped;
  7419. /* turn mirroring into duplication */
  7420. if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
  7421. BTRFS_BLOCK_GROUP_RAID10))
  7422. return stripped | BTRFS_BLOCK_GROUP_DUP;
  7423. } else {
  7424. /* they already had raid on here, just return */
  7425. if (flags & stripped)
  7426. return flags;
  7427. stripped |= BTRFS_BLOCK_GROUP_DUP;
  7428. stripped = flags & ~stripped;
  7429. /* switch duplicated blocks with raid1 */
  7430. if (flags & BTRFS_BLOCK_GROUP_DUP)
  7431. return stripped | BTRFS_BLOCK_GROUP_RAID1;
  7432. /* this is drive concat, leave it alone */
  7433. }
  7434. return flags;
  7435. }
  7436. static int set_block_group_ro(struct btrfs_block_group_cache *cache, int force)
  7437. {
  7438. struct btrfs_space_info *sinfo = cache->space_info;
  7439. u64 num_bytes;
  7440. u64 min_allocable_bytes;
  7441. int ret = -ENOSPC;
  7442. /*
  7443. * We need some metadata space and system metadata space for
  7444. * allocating chunks in some corner cases until we force to set
  7445. * it to be readonly.
  7446. */
  7447. if ((sinfo->flags &
  7448. (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
  7449. !force)
  7450. min_allocable_bytes = 1 * 1024 * 1024;
  7451. else
  7452. min_allocable_bytes = 0;
  7453. spin_lock(&sinfo->lock);
  7454. spin_lock(&cache->lock);
  7455. if (cache->ro) {
  7456. ret = 0;
  7457. goto out;
  7458. }
  7459. num_bytes = cache->key.offset - cache->reserved - cache->pinned -
  7460. cache->bytes_super - btrfs_block_group_used(&cache->item);
  7461. if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
  7462. sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
  7463. min_allocable_bytes <= sinfo->total_bytes) {
  7464. sinfo->bytes_readonly += num_bytes;
  7465. cache->ro = 1;
  7466. list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
  7467. ret = 0;
  7468. }
  7469. out:
  7470. spin_unlock(&cache->lock);
  7471. spin_unlock(&sinfo->lock);
  7472. return ret;
  7473. }
  7474. int btrfs_set_block_group_ro(struct btrfs_root *root,
  7475. struct btrfs_block_group_cache *cache)
  7476. {
  7477. struct btrfs_trans_handle *trans;
  7478. u64 alloc_flags;
  7479. int ret;
  7480. BUG_ON(cache->ro);
  7481. trans = btrfs_join_transaction(root);
  7482. if (IS_ERR(trans))
  7483. return PTR_ERR(trans);
  7484. ret = set_block_group_ro(cache, 0);
  7485. if (!ret)
  7486. goto out;
  7487. alloc_flags = get_alloc_profile(root, cache->space_info->flags);
  7488. ret = do_chunk_alloc(trans, root, alloc_flags,
  7489. CHUNK_ALLOC_FORCE);
  7490. if (ret < 0)
  7491. goto out;
  7492. ret = set_block_group_ro(cache, 0);
  7493. out:
  7494. if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
  7495. alloc_flags = update_block_group_flags(root, cache->flags);
  7496. check_system_chunk(trans, root, alloc_flags);
  7497. }
  7498. btrfs_end_transaction(trans, root);
  7499. return ret;
  7500. }
  7501. int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
  7502. struct btrfs_root *root, u64 type)
  7503. {
  7504. u64 alloc_flags = get_alloc_profile(root, type);
  7505. return do_chunk_alloc(trans, root, alloc_flags,
  7506. CHUNK_ALLOC_FORCE);
  7507. }
  7508. /*
  7509. * helper to account the unused space of all the readonly block group in the
  7510. * space_info. takes mirrors into account.
  7511. */
  7512. u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
  7513. {
  7514. struct btrfs_block_group_cache *block_group;
  7515. u64 free_bytes = 0;
  7516. int factor;
  7517. /* It's df, we don't care if it's racey */
  7518. if (list_empty(&sinfo->ro_bgs))
  7519. return 0;
  7520. spin_lock(&sinfo->lock);
  7521. list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
  7522. spin_lock(&block_group->lock);
  7523. if (!block_group->ro) {
  7524. spin_unlock(&block_group->lock);
  7525. continue;
  7526. }
  7527. if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
  7528. BTRFS_BLOCK_GROUP_RAID10 |
  7529. BTRFS_BLOCK_GROUP_DUP))
  7530. factor = 2;
  7531. else
  7532. factor = 1;
  7533. free_bytes += (block_group->key.offset -
  7534. btrfs_block_group_used(&block_group->item)) *
  7535. factor;
  7536. spin_unlock(&block_group->lock);
  7537. }
  7538. spin_unlock(&sinfo->lock);
  7539. return free_bytes;
  7540. }
  7541. void btrfs_set_block_group_rw(struct btrfs_root *root,
  7542. struct btrfs_block_group_cache *cache)
  7543. {
  7544. struct btrfs_space_info *sinfo = cache->space_info;
  7545. u64 num_bytes;
  7546. BUG_ON(!cache->ro);
  7547. spin_lock(&sinfo->lock);
  7548. spin_lock(&cache->lock);
  7549. num_bytes = cache->key.offset - cache->reserved - cache->pinned -
  7550. cache->bytes_super - btrfs_block_group_used(&cache->item);
  7551. sinfo->bytes_readonly -= num_bytes;
  7552. cache->ro = 0;
  7553. list_del_init(&cache->ro_list);
  7554. spin_unlock(&cache->lock);
  7555. spin_unlock(&sinfo->lock);
  7556. }
  7557. /*
  7558. * checks to see if its even possible to relocate this block group.
  7559. *
  7560. * @return - -1 if it's not a good idea to relocate this block group, 0 if its
  7561. * ok to go ahead and try.
  7562. */
  7563. int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
  7564. {
  7565. struct btrfs_block_group_cache *block_group;
  7566. struct btrfs_space_info *space_info;
  7567. struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
  7568. struct btrfs_device *device;
  7569. struct btrfs_trans_handle *trans;
  7570. u64 min_free;
  7571. u64 dev_min = 1;
  7572. u64 dev_nr = 0;
  7573. u64 target;
  7574. int index;
  7575. int full = 0;
  7576. int ret = 0;
  7577. block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
  7578. /* odd, couldn't find the block group, leave it alone */
  7579. if (!block_group)
  7580. return -1;
  7581. min_free = btrfs_block_group_used(&block_group->item);
  7582. /* no bytes used, we're good */
  7583. if (!min_free)
  7584. goto out;
  7585. space_info = block_group->space_info;
  7586. spin_lock(&space_info->lock);
  7587. full = space_info->full;
  7588. /*
  7589. * if this is the last block group we have in this space, we can't
  7590. * relocate it unless we're able to allocate a new chunk below.
  7591. *
  7592. * Otherwise, we need to make sure we have room in the space to handle
  7593. * all of the extents from this block group. If we can, we're good
  7594. */
  7595. if ((space_info->total_bytes != block_group->key.offset) &&
  7596. (space_info->bytes_used + space_info->bytes_reserved +
  7597. space_info->bytes_pinned + space_info->bytes_readonly +
  7598. min_free < space_info->total_bytes)) {
  7599. spin_unlock(&space_info->lock);
  7600. goto out;
  7601. }
  7602. spin_unlock(&space_info->lock);
  7603. /*
  7604. * ok we don't have enough space, but maybe we have free space on our
  7605. * devices to allocate new chunks for relocation, so loop through our
  7606. * alloc devices and guess if we have enough space. if this block
  7607. * group is going to be restriped, run checks against the target
  7608. * profile instead of the current one.
  7609. */
  7610. ret = -1;
  7611. /*
  7612. * index:
  7613. * 0: raid10
  7614. * 1: raid1
  7615. * 2: dup
  7616. * 3: raid0
  7617. * 4: single
  7618. */
  7619. target = get_restripe_target(root->fs_info, block_group->flags);
  7620. if (target) {
  7621. index = __get_raid_index(extended_to_chunk(target));
  7622. } else {
  7623. /*
  7624. * this is just a balance, so if we were marked as full
  7625. * we know there is no space for a new chunk
  7626. */
  7627. if (full)
  7628. goto out;
  7629. index = get_block_group_index(block_group);
  7630. }
  7631. if (index == BTRFS_RAID_RAID10) {
  7632. dev_min = 4;
  7633. /* Divide by 2 */
  7634. min_free >>= 1;
  7635. } else if (index == BTRFS_RAID_RAID1) {
  7636. dev_min = 2;
  7637. } else if (index == BTRFS_RAID_DUP) {
  7638. /* Multiply by 2 */
  7639. min_free <<= 1;
  7640. } else if (index == BTRFS_RAID_RAID0) {
  7641. dev_min = fs_devices->rw_devices;
  7642. do_div(min_free, dev_min);
  7643. }
  7644. /* We need to do this so that we can look at pending chunks */
  7645. trans = btrfs_join_transaction(root);
  7646. if (IS_ERR(trans)) {
  7647. ret = PTR_ERR(trans);
  7648. goto out;
  7649. }
  7650. mutex_lock(&root->fs_info->chunk_mutex);
  7651. list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
  7652. u64 dev_offset;
  7653. /*
  7654. * check to make sure we can actually find a chunk with enough
  7655. * space to fit our block group in.
  7656. */
  7657. if (device->total_bytes > device->bytes_used + min_free &&
  7658. !device->is_tgtdev_for_dev_replace) {
  7659. ret = find_free_dev_extent(trans, device, min_free,
  7660. &dev_offset, NULL);
  7661. if (!ret)
  7662. dev_nr++;
  7663. if (dev_nr >= dev_min)
  7664. break;
  7665. ret = -1;
  7666. }
  7667. }
  7668. mutex_unlock(&root->fs_info->chunk_mutex);
  7669. btrfs_end_transaction(trans, root);
  7670. out:
  7671. btrfs_put_block_group(block_group);
  7672. return ret;
  7673. }
  7674. static int find_first_block_group(struct btrfs_root *root,
  7675. struct btrfs_path *path, struct btrfs_key *key)
  7676. {
  7677. int ret = 0;
  7678. struct btrfs_key found_key;
  7679. struct extent_buffer *leaf;
  7680. int slot;
  7681. ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
  7682. if (ret < 0)
  7683. goto out;
  7684. while (1) {
  7685. slot = path->slots[0];
  7686. leaf = path->nodes[0];
  7687. if (slot >= btrfs_header_nritems(leaf)) {
  7688. ret = btrfs_next_leaf(root, path);
  7689. if (ret == 0)
  7690. continue;
  7691. if (ret < 0)
  7692. goto out;
  7693. break;
  7694. }
  7695. btrfs_item_key_to_cpu(leaf, &found_key, slot);
  7696. if (found_key.objectid >= key->objectid &&
  7697. found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
  7698. ret = 0;
  7699. goto out;
  7700. }
  7701. path->slots[0]++;
  7702. }
  7703. out:
  7704. return ret;
  7705. }
  7706. void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
  7707. {
  7708. struct btrfs_block_group_cache *block_group;
  7709. u64 last = 0;
  7710. while (1) {
  7711. struct inode *inode;
  7712. block_group = btrfs_lookup_first_block_group(info, last);
  7713. while (block_group) {
  7714. spin_lock(&block_group->lock);
  7715. if (block_group->iref)
  7716. break;
  7717. spin_unlock(&block_group->lock);
  7718. block_group = next_block_group(info->tree_root,
  7719. block_group);
  7720. }
  7721. if (!block_group) {
  7722. if (last == 0)
  7723. break;
  7724. last = 0;
  7725. continue;
  7726. }
  7727. inode = block_group->inode;
  7728. block_group->iref = 0;
  7729. block_group->inode = NULL;
  7730. spin_unlock(&block_group->lock);
  7731. iput(inode);
  7732. last = block_group->key.objectid + block_group->key.offset;
  7733. btrfs_put_block_group(block_group);
  7734. }
  7735. }
  7736. int btrfs_free_block_groups(struct btrfs_fs_info *info)
  7737. {
  7738. struct btrfs_block_group_cache *block_group;
  7739. struct btrfs_space_info *space_info;
  7740. struct btrfs_caching_control *caching_ctl;
  7741. struct rb_node *n;
  7742. down_write(&info->commit_root_sem);
  7743. while (!list_empty(&info->caching_block_groups)) {
  7744. caching_ctl = list_entry(info->caching_block_groups.next,
  7745. struct btrfs_caching_control, list);
  7746. list_del(&caching_ctl->list);
  7747. put_caching_control(caching_ctl);
  7748. }
  7749. up_write(&info->commit_root_sem);
  7750. spin_lock(&info->unused_bgs_lock);
  7751. while (!list_empty(&info->unused_bgs)) {
  7752. block_group = list_first_entry(&info->unused_bgs,
  7753. struct btrfs_block_group_cache,
  7754. bg_list);
  7755. list_del_init(&block_group->bg_list);
  7756. btrfs_put_block_group(block_group);
  7757. }
  7758. spin_unlock(&info->unused_bgs_lock);
  7759. spin_lock(&info->block_group_cache_lock);
  7760. while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
  7761. block_group = rb_entry(n, struct btrfs_block_group_cache,
  7762. cache_node);
  7763. rb_erase(&block_group->cache_node,
  7764. &info->block_group_cache_tree);
  7765. RB_CLEAR_NODE(&block_group->cache_node);
  7766. spin_unlock(&info->block_group_cache_lock);
  7767. down_write(&block_group->space_info->groups_sem);
  7768. list_del(&block_group->list);
  7769. up_write(&block_group->space_info->groups_sem);
  7770. if (block_group->cached == BTRFS_CACHE_STARTED)
  7771. wait_block_group_cache_done(block_group);
  7772. /*
  7773. * We haven't cached this block group, which means we could
  7774. * possibly have excluded extents on this block group.
  7775. */
  7776. if (block_group->cached == BTRFS_CACHE_NO ||
  7777. block_group->cached == BTRFS_CACHE_ERROR)
  7778. free_excluded_extents(info->extent_root, block_group);
  7779. btrfs_remove_free_space_cache(block_group);
  7780. btrfs_put_block_group(block_group);
  7781. spin_lock(&info->block_group_cache_lock);
  7782. }
  7783. spin_unlock(&info->block_group_cache_lock);
  7784. /* now that all the block groups are freed, go through and
  7785. * free all the space_info structs. This is only called during
  7786. * the final stages of unmount, and so we know nobody is
  7787. * using them. We call synchronize_rcu() once before we start,
  7788. * just to be on the safe side.
  7789. */
  7790. synchronize_rcu();
  7791. release_global_block_rsv(info);
  7792. while (!list_empty(&info->space_info)) {
  7793. int i;
  7794. space_info = list_entry(info->space_info.next,
  7795. struct btrfs_space_info,
  7796. list);
  7797. if (btrfs_test_opt(info->tree_root, ENOSPC_DEBUG)) {
  7798. if (WARN_ON(space_info->bytes_pinned > 0 ||
  7799. space_info->bytes_reserved > 0 ||
  7800. space_info->bytes_may_use > 0)) {
  7801. dump_space_info(space_info, 0, 0);
  7802. }
  7803. }
  7804. list_del(&space_info->list);
  7805. for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
  7806. struct kobject *kobj;
  7807. kobj = space_info->block_group_kobjs[i];
  7808. space_info->block_group_kobjs[i] = NULL;
  7809. if (kobj) {
  7810. kobject_del(kobj);
  7811. kobject_put(kobj);
  7812. }
  7813. }
  7814. kobject_del(&space_info->kobj);
  7815. kobject_put(&space_info->kobj);
  7816. }
  7817. return 0;
  7818. }
  7819. static void __link_block_group(struct btrfs_space_info *space_info,
  7820. struct btrfs_block_group_cache *cache)
  7821. {
  7822. int index = get_block_group_index(cache);
  7823. bool first = false;
  7824. down_write(&space_info->groups_sem);
  7825. if (list_empty(&space_info->block_groups[index]))
  7826. first = true;
  7827. list_add_tail(&cache->list, &space_info->block_groups[index]);
  7828. up_write(&space_info->groups_sem);
  7829. if (first) {
  7830. struct raid_kobject *rkobj;
  7831. int ret;
  7832. rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
  7833. if (!rkobj)
  7834. goto out_err;
  7835. rkobj->raid_type = index;
  7836. kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
  7837. ret = kobject_add(&rkobj->kobj, &space_info->kobj,
  7838. "%s", get_raid_name(index));
  7839. if (ret) {
  7840. kobject_put(&rkobj->kobj);
  7841. goto out_err;
  7842. }
  7843. space_info->block_group_kobjs[index] = &rkobj->kobj;
  7844. }
  7845. return;
  7846. out_err:
  7847. pr_warn("BTRFS: failed to add kobject for block cache. ignoring.\n");
  7848. }
  7849. static struct btrfs_block_group_cache *
  7850. btrfs_create_block_group_cache(struct btrfs_root *root, u64 start, u64 size)
  7851. {
  7852. struct btrfs_block_group_cache *cache;
  7853. cache = kzalloc(sizeof(*cache), GFP_NOFS);
  7854. if (!cache)
  7855. return NULL;
  7856. cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
  7857. GFP_NOFS);
  7858. if (!cache->free_space_ctl) {
  7859. kfree(cache);
  7860. return NULL;
  7861. }
  7862. cache->key.objectid = start;
  7863. cache->key.offset = size;
  7864. cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
  7865. cache->sectorsize = root->sectorsize;
  7866. cache->fs_info = root->fs_info;
  7867. cache->full_stripe_len = btrfs_full_stripe_len(root,
  7868. &root->fs_info->mapping_tree,
  7869. start);
  7870. atomic_set(&cache->count, 1);
  7871. spin_lock_init(&cache->lock);
  7872. init_rwsem(&cache->data_rwsem);
  7873. INIT_LIST_HEAD(&cache->list);
  7874. INIT_LIST_HEAD(&cache->cluster_list);
  7875. INIT_LIST_HEAD(&cache->bg_list);
  7876. INIT_LIST_HEAD(&cache->ro_list);
  7877. INIT_LIST_HEAD(&cache->dirty_list);
  7878. btrfs_init_free_space_ctl(cache);
  7879. atomic_set(&cache->trimming, 0);
  7880. return cache;
  7881. }
  7882. int btrfs_read_block_groups(struct btrfs_root *root)
  7883. {
  7884. struct btrfs_path *path;
  7885. int ret;
  7886. struct btrfs_block_group_cache *cache;
  7887. struct btrfs_fs_info *info = root->fs_info;
  7888. struct btrfs_space_info *space_info;
  7889. struct btrfs_key key;
  7890. struct btrfs_key found_key;
  7891. struct extent_buffer *leaf;
  7892. int need_clear = 0;
  7893. u64 cache_gen;
  7894. root = info->extent_root;
  7895. key.objectid = 0;
  7896. key.offset = 0;
  7897. key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
  7898. path = btrfs_alloc_path();
  7899. if (!path)
  7900. return -ENOMEM;
  7901. path->reada = 1;
  7902. cache_gen = btrfs_super_cache_generation(root->fs_info->super_copy);
  7903. if (btrfs_test_opt(root, SPACE_CACHE) &&
  7904. btrfs_super_generation(root->fs_info->super_copy) != cache_gen)
  7905. need_clear = 1;
  7906. if (btrfs_test_opt(root, CLEAR_CACHE))
  7907. need_clear = 1;
  7908. while (1) {
  7909. ret = find_first_block_group(root, path, &key);
  7910. if (ret > 0)
  7911. break;
  7912. if (ret != 0)
  7913. goto error;
  7914. leaf = path->nodes[0];
  7915. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  7916. cache = btrfs_create_block_group_cache(root, found_key.objectid,
  7917. found_key.offset);
  7918. if (!cache) {
  7919. ret = -ENOMEM;
  7920. goto error;
  7921. }
  7922. if (need_clear) {
  7923. /*
  7924. * When we mount with old space cache, we need to
  7925. * set BTRFS_DC_CLEAR and set dirty flag.
  7926. *
  7927. * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
  7928. * truncate the old free space cache inode and
  7929. * setup a new one.
  7930. * b) Setting 'dirty flag' makes sure that we flush
  7931. * the new space cache info onto disk.
  7932. */
  7933. if (btrfs_test_opt(root, SPACE_CACHE))
  7934. cache->disk_cache_state = BTRFS_DC_CLEAR;
  7935. }
  7936. read_extent_buffer(leaf, &cache->item,
  7937. btrfs_item_ptr_offset(leaf, path->slots[0]),
  7938. sizeof(cache->item));
  7939. cache->flags = btrfs_block_group_flags(&cache->item);
  7940. key.objectid = found_key.objectid + found_key.offset;
  7941. btrfs_release_path(path);
  7942. /*
  7943. * We need to exclude the super stripes now so that the space
  7944. * info has super bytes accounted for, otherwise we'll think
  7945. * we have more space than we actually do.
  7946. */
  7947. ret = exclude_super_stripes(root, cache);
  7948. if (ret) {
  7949. /*
  7950. * We may have excluded something, so call this just in
  7951. * case.
  7952. */
  7953. free_excluded_extents(root, cache);
  7954. btrfs_put_block_group(cache);
  7955. goto error;
  7956. }
  7957. /*
  7958. * check for two cases, either we are full, and therefore
  7959. * don't need to bother with the caching work since we won't
  7960. * find any space, or we are empty, and we can just add all
  7961. * the space in and be done with it. This saves us _alot_ of
  7962. * time, particularly in the full case.
  7963. */
  7964. if (found_key.offset == btrfs_block_group_used(&cache->item)) {
  7965. cache->last_byte_to_unpin = (u64)-1;
  7966. cache->cached = BTRFS_CACHE_FINISHED;
  7967. free_excluded_extents(root, cache);
  7968. } else if (btrfs_block_group_used(&cache->item) == 0) {
  7969. cache->last_byte_to_unpin = (u64)-1;
  7970. cache->cached = BTRFS_CACHE_FINISHED;
  7971. add_new_free_space(cache, root->fs_info,
  7972. found_key.objectid,
  7973. found_key.objectid +
  7974. found_key.offset);
  7975. free_excluded_extents(root, cache);
  7976. }
  7977. ret = btrfs_add_block_group_cache(root->fs_info, cache);
  7978. if (ret) {
  7979. btrfs_remove_free_space_cache(cache);
  7980. btrfs_put_block_group(cache);
  7981. goto error;
  7982. }
  7983. ret = update_space_info(info, cache->flags, found_key.offset,
  7984. btrfs_block_group_used(&cache->item),
  7985. &space_info);
  7986. if (ret) {
  7987. btrfs_remove_free_space_cache(cache);
  7988. spin_lock(&info->block_group_cache_lock);
  7989. rb_erase(&cache->cache_node,
  7990. &info->block_group_cache_tree);
  7991. RB_CLEAR_NODE(&cache->cache_node);
  7992. spin_unlock(&info->block_group_cache_lock);
  7993. btrfs_put_block_group(cache);
  7994. goto error;
  7995. }
  7996. cache->space_info = space_info;
  7997. spin_lock(&cache->space_info->lock);
  7998. cache->space_info->bytes_readonly += cache->bytes_super;
  7999. spin_unlock(&cache->space_info->lock);
  8000. __link_block_group(space_info, cache);
  8001. set_avail_alloc_bits(root->fs_info, cache->flags);
  8002. if (btrfs_chunk_readonly(root, cache->key.objectid)) {
  8003. set_block_group_ro(cache, 1);
  8004. } else if (btrfs_block_group_used(&cache->item) == 0) {
  8005. spin_lock(&info->unused_bgs_lock);
  8006. /* Should always be true but just in case. */
  8007. if (list_empty(&cache->bg_list)) {
  8008. btrfs_get_block_group(cache);
  8009. list_add_tail(&cache->bg_list,
  8010. &info->unused_bgs);
  8011. }
  8012. spin_unlock(&info->unused_bgs_lock);
  8013. }
  8014. }
  8015. list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
  8016. if (!(get_alloc_profile(root, space_info->flags) &
  8017. (BTRFS_BLOCK_GROUP_RAID10 |
  8018. BTRFS_BLOCK_GROUP_RAID1 |
  8019. BTRFS_BLOCK_GROUP_RAID5 |
  8020. BTRFS_BLOCK_GROUP_RAID6 |
  8021. BTRFS_BLOCK_GROUP_DUP)))
  8022. continue;
  8023. /*
  8024. * avoid allocating from un-mirrored block group if there are
  8025. * mirrored block groups.
  8026. */
  8027. list_for_each_entry(cache,
  8028. &space_info->block_groups[BTRFS_RAID_RAID0],
  8029. list)
  8030. set_block_group_ro(cache, 1);
  8031. list_for_each_entry(cache,
  8032. &space_info->block_groups[BTRFS_RAID_SINGLE],
  8033. list)
  8034. set_block_group_ro(cache, 1);
  8035. }
  8036. init_global_block_rsv(info);
  8037. ret = 0;
  8038. error:
  8039. btrfs_free_path(path);
  8040. return ret;
  8041. }
  8042. void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
  8043. struct btrfs_root *root)
  8044. {
  8045. struct btrfs_block_group_cache *block_group, *tmp;
  8046. struct btrfs_root *extent_root = root->fs_info->extent_root;
  8047. struct btrfs_block_group_item item;
  8048. struct btrfs_key key;
  8049. int ret = 0;
  8050. list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
  8051. if (ret)
  8052. goto next;
  8053. spin_lock(&block_group->lock);
  8054. memcpy(&item, &block_group->item, sizeof(item));
  8055. memcpy(&key, &block_group->key, sizeof(key));
  8056. spin_unlock(&block_group->lock);
  8057. ret = btrfs_insert_item(trans, extent_root, &key, &item,
  8058. sizeof(item));
  8059. if (ret)
  8060. btrfs_abort_transaction(trans, extent_root, ret);
  8061. ret = btrfs_finish_chunk_alloc(trans, extent_root,
  8062. key.objectid, key.offset);
  8063. if (ret)
  8064. btrfs_abort_transaction(trans, extent_root, ret);
  8065. next:
  8066. list_del_init(&block_group->bg_list);
  8067. }
  8068. }
  8069. int btrfs_make_block_group(struct btrfs_trans_handle *trans,
  8070. struct btrfs_root *root, u64 bytes_used,
  8071. u64 type, u64 chunk_objectid, u64 chunk_offset,
  8072. u64 size)
  8073. {
  8074. int ret;
  8075. struct btrfs_root *extent_root;
  8076. struct btrfs_block_group_cache *cache;
  8077. extent_root = root->fs_info->extent_root;
  8078. btrfs_set_log_full_commit(root->fs_info, trans);
  8079. cache = btrfs_create_block_group_cache(root, chunk_offset, size);
  8080. if (!cache)
  8081. return -ENOMEM;
  8082. btrfs_set_block_group_used(&cache->item, bytes_used);
  8083. btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
  8084. btrfs_set_block_group_flags(&cache->item, type);
  8085. cache->flags = type;
  8086. cache->last_byte_to_unpin = (u64)-1;
  8087. cache->cached = BTRFS_CACHE_FINISHED;
  8088. ret = exclude_super_stripes(root, cache);
  8089. if (ret) {
  8090. /*
  8091. * We may have excluded something, so call this just in
  8092. * case.
  8093. */
  8094. free_excluded_extents(root, cache);
  8095. btrfs_put_block_group(cache);
  8096. return ret;
  8097. }
  8098. add_new_free_space(cache, root->fs_info, chunk_offset,
  8099. chunk_offset + size);
  8100. free_excluded_extents(root, cache);
  8101. ret = btrfs_add_block_group_cache(root->fs_info, cache);
  8102. if (ret) {
  8103. btrfs_remove_free_space_cache(cache);
  8104. btrfs_put_block_group(cache);
  8105. return ret;
  8106. }
  8107. ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
  8108. &cache->space_info);
  8109. if (ret) {
  8110. btrfs_remove_free_space_cache(cache);
  8111. spin_lock(&root->fs_info->block_group_cache_lock);
  8112. rb_erase(&cache->cache_node,
  8113. &root->fs_info->block_group_cache_tree);
  8114. RB_CLEAR_NODE(&cache->cache_node);
  8115. spin_unlock(&root->fs_info->block_group_cache_lock);
  8116. btrfs_put_block_group(cache);
  8117. return ret;
  8118. }
  8119. update_global_block_rsv(root->fs_info);
  8120. spin_lock(&cache->space_info->lock);
  8121. cache->space_info->bytes_readonly += cache->bytes_super;
  8122. spin_unlock(&cache->space_info->lock);
  8123. __link_block_group(cache->space_info, cache);
  8124. list_add_tail(&cache->bg_list, &trans->new_bgs);
  8125. set_avail_alloc_bits(extent_root->fs_info, type);
  8126. return 0;
  8127. }
  8128. static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
  8129. {
  8130. u64 extra_flags = chunk_to_extended(flags) &
  8131. BTRFS_EXTENDED_PROFILE_MASK;
  8132. write_seqlock(&fs_info->profiles_lock);
  8133. if (flags & BTRFS_BLOCK_GROUP_DATA)
  8134. fs_info->avail_data_alloc_bits &= ~extra_flags;
  8135. if (flags & BTRFS_BLOCK_GROUP_METADATA)
  8136. fs_info->avail_metadata_alloc_bits &= ~extra_flags;
  8137. if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
  8138. fs_info->avail_system_alloc_bits &= ~extra_flags;
  8139. write_sequnlock(&fs_info->profiles_lock);
  8140. }
  8141. int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
  8142. struct btrfs_root *root, u64 group_start,
  8143. struct extent_map *em)
  8144. {
  8145. struct btrfs_path *path;
  8146. struct btrfs_block_group_cache *block_group;
  8147. struct btrfs_free_cluster *cluster;
  8148. struct btrfs_root *tree_root = root->fs_info->tree_root;
  8149. struct btrfs_key key;
  8150. struct inode *inode;
  8151. struct kobject *kobj = NULL;
  8152. int ret;
  8153. int index;
  8154. int factor;
  8155. struct btrfs_caching_control *caching_ctl = NULL;
  8156. bool remove_em;
  8157. root = root->fs_info->extent_root;
  8158. block_group = btrfs_lookup_block_group(root->fs_info, group_start);
  8159. BUG_ON(!block_group);
  8160. BUG_ON(!block_group->ro);
  8161. /*
  8162. * Free the reserved super bytes from this block group before
  8163. * remove it.
  8164. */
  8165. free_excluded_extents(root, block_group);
  8166. memcpy(&key, &block_group->key, sizeof(key));
  8167. index = get_block_group_index(block_group);
  8168. if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
  8169. BTRFS_BLOCK_GROUP_RAID1 |
  8170. BTRFS_BLOCK_GROUP_RAID10))
  8171. factor = 2;
  8172. else
  8173. factor = 1;
  8174. /* make sure this block group isn't part of an allocation cluster */
  8175. cluster = &root->fs_info->data_alloc_cluster;
  8176. spin_lock(&cluster->refill_lock);
  8177. btrfs_return_cluster_to_free_space(block_group, cluster);
  8178. spin_unlock(&cluster->refill_lock);
  8179. /*
  8180. * make sure this block group isn't part of a metadata
  8181. * allocation cluster
  8182. */
  8183. cluster = &root->fs_info->meta_alloc_cluster;
  8184. spin_lock(&cluster->refill_lock);
  8185. btrfs_return_cluster_to_free_space(block_group, cluster);
  8186. spin_unlock(&cluster->refill_lock);
  8187. path = btrfs_alloc_path();
  8188. if (!path) {
  8189. ret = -ENOMEM;
  8190. goto out;
  8191. }
  8192. inode = lookup_free_space_inode(tree_root, block_group, path);
  8193. if (!IS_ERR(inode)) {
  8194. ret = btrfs_orphan_add(trans, inode);
  8195. if (ret) {
  8196. btrfs_add_delayed_iput(inode);
  8197. goto out;
  8198. }
  8199. clear_nlink(inode);
  8200. /* One for the block groups ref */
  8201. spin_lock(&block_group->lock);
  8202. if (block_group->iref) {
  8203. block_group->iref = 0;
  8204. block_group->inode = NULL;
  8205. spin_unlock(&block_group->lock);
  8206. iput(inode);
  8207. } else {
  8208. spin_unlock(&block_group->lock);
  8209. }
  8210. /* One for our lookup ref */
  8211. btrfs_add_delayed_iput(inode);
  8212. }
  8213. key.objectid = BTRFS_FREE_SPACE_OBJECTID;
  8214. key.offset = block_group->key.objectid;
  8215. key.type = 0;
  8216. ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
  8217. if (ret < 0)
  8218. goto out;
  8219. if (ret > 0)
  8220. btrfs_release_path(path);
  8221. if (ret == 0) {
  8222. ret = btrfs_del_item(trans, tree_root, path);
  8223. if (ret)
  8224. goto out;
  8225. btrfs_release_path(path);
  8226. }
  8227. spin_lock(&root->fs_info->block_group_cache_lock);
  8228. rb_erase(&block_group->cache_node,
  8229. &root->fs_info->block_group_cache_tree);
  8230. RB_CLEAR_NODE(&block_group->cache_node);
  8231. if (root->fs_info->first_logical_byte == block_group->key.objectid)
  8232. root->fs_info->first_logical_byte = (u64)-1;
  8233. spin_unlock(&root->fs_info->block_group_cache_lock);
  8234. down_write(&block_group->space_info->groups_sem);
  8235. /*
  8236. * we must use list_del_init so people can check to see if they
  8237. * are still on the list after taking the semaphore
  8238. */
  8239. list_del_init(&block_group->list);
  8240. if (list_empty(&block_group->space_info->block_groups[index])) {
  8241. kobj = block_group->space_info->block_group_kobjs[index];
  8242. block_group->space_info->block_group_kobjs[index] = NULL;
  8243. clear_avail_alloc_bits(root->fs_info, block_group->flags);
  8244. }
  8245. up_write(&block_group->space_info->groups_sem);
  8246. if (kobj) {
  8247. kobject_del(kobj);
  8248. kobject_put(kobj);
  8249. }
  8250. if (block_group->has_caching_ctl)
  8251. caching_ctl = get_caching_control(block_group);
  8252. if (block_group->cached == BTRFS_CACHE_STARTED)
  8253. wait_block_group_cache_done(block_group);
  8254. if (block_group->has_caching_ctl) {
  8255. down_write(&root->fs_info->commit_root_sem);
  8256. if (!caching_ctl) {
  8257. struct btrfs_caching_control *ctl;
  8258. list_for_each_entry(ctl,
  8259. &root->fs_info->caching_block_groups, list)
  8260. if (ctl->block_group == block_group) {
  8261. caching_ctl = ctl;
  8262. atomic_inc(&caching_ctl->count);
  8263. break;
  8264. }
  8265. }
  8266. if (caching_ctl)
  8267. list_del_init(&caching_ctl->list);
  8268. up_write(&root->fs_info->commit_root_sem);
  8269. if (caching_ctl) {
  8270. /* Once for the caching bgs list and once for us. */
  8271. put_caching_control(caching_ctl);
  8272. put_caching_control(caching_ctl);
  8273. }
  8274. }
  8275. spin_lock(&trans->transaction->dirty_bgs_lock);
  8276. if (!list_empty(&block_group->dirty_list)) {
  8277. list_del_init(&block_group->dirty_list);
  8278. btrfs_put_block_group(block_group);
  8279. }
  8280. spin_unlock(&trans->transaction->dirty_bgs_lock);
  8281. btrfs_remove_free_space_cache(block_group);
  8282. spin_lock(&block_group->space_info->lock);
  8283. list_del_init(&block_group->ro_list);
  8284. block_group->space_info->total_bytes -= block_group->key.offset;
  8285. block_group->space_info->bytes_readonly -= block_group->key.offset;
  8286. block_group->space_info->disk_total -= block_group->key.offset * factor;
  8287. spin_unlock(&block_group->space_info->lock);
  8288. memcpy(&key, &block_group->key, sizeof(key));
  8289. lock_chunks(root);
  8290. if (!list_empty(&em->list)) {
  8291. /* We're in the transaction->pending_chunks list. */
  8292. free_extent_map(em);
  8293. }
  8294. spin_lock(&block_group->lock);
  8295. block_group->removed = 1;
  8296. /*
  8297. * At this point trimming can't start on this block group, because we
  8298. * removed the block group from the tree fs_info->block_group_cache_tree
  8299. * so no one can't find it anymore and even if someone already got this
  8300. * block group before we removed it from the rbtree, they have already
  8301. * incremented block_group->trimming - if they didn't, they won't find
  8302. * any free space entries because we already removed them all when we
  8303. * called btrfs_remove_free_space_cache().
  8304. *
  8305. * And we must not remove the extent map from the fs_info->mapping_tree
  8306. * to prevent the same logical address range and physical device space
  8307. * ranges from being reused for a new block group. This is because our
  8308. * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
  8309. * completely transactionless, so while it is trimming a range the
  8310. * currently running transaction might finish and a new one start,
  8311. * allowing for new block groups to be created that can reuse the same
  8312. * physical device locations unless we take this special care.
  8313. */
  8314. remove_em = (atomic_read(&block_group->trimming) == 0);
  8315. /*
  8316. * Make sure a trimmer task always sees the em in the pinned_chunks list
  8317. * if it sees block_group->removed == 1 (needs to lock block_group->lock
  8318. * before checking block_group->removed).
  8319. */
  8320. if (!remove_em) {
  8321. /*
  8322. * Our em might be in trans->transaction->pending_chunks which
  8323. * is protected by fs_info->chunk_mutex ([lock|unlock]_chunks),
  8324. * and so is the fs_info->pinned_chunks list.
  8325. *
  8326. * So at this point we must be holding the chunk_mutex to avoid
  8327. * any races with chunk allocation (more specifically at
  8328. * volumes.c:contains_pending_extent()), to ensure it always
  8329. * sees the em, either in the pending_chunks list or in the
  8330. * pinned_chunks list.
  8331. */
  8332. list_move_tail(&em->list, &root->fs_info->pinned_chunks);
  8333. }
  8334. spin_unlock(&block_group->lock);
  8335. if (remove_em) {
  8336. struct extent_map_tree *em_tree;
  8337. em_tree = &root->fs_info->mapping_tree.map_tree;
  8338. write_lock(&em_tree->lock);
  8339. /*
  8340. * The em might be in the pending_chunks list, so make sure the
  8341. * chunk mutex is locked, since remove_extent_mapping() will
  8342. * delete us from that list.
  8343. */
  8344. remove_extent_mapping(em_tree, em);
  8345. write_unlock(&em_tree->lock);
  8346. /* once for the tree */
  8347. free_extent_map(em);
  8348. }
  8349. unlock_chunks(root);
  8350. btrfs_put_block_group(block_group);
  8351. btrfs_put_block_group(block_group);
  8352. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  8353. if (ret > 0)
  8354. ret = -EIO;
  8355. if (ret < 0)
  8356. goto out;
  8357. ret = btrfs_del_item(trans, root, path);
  8358. out:
  8359. btrfs_free_path(path);
  8360. return ret;
  8361. }
  8362. /*
  8363. * Process the unused_bgs list and remove any that don't have any allocated
  8364. * space inside of them.
  8365. */
  8366. void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
  8367. {
  8368. struct btrfs_block_group_cache *block_group;
  8369. struct btrfs_space_info *space_info;
  8370. struct btrfs_root *root = fs_info->extent_root;
  8371. struct btrfs_trans_handle *trans;
  8372. int ret = 0;
  8373. if (!fs_info->open)
  8374. return;
  8375. spin_lock(&fs_info->unused_bgs_lock);
  8376. while (!list_empty(&fs_info->unused_bgs)) {
  8377. u64 start, end;
  8378. block_group = list_first_entry(&fs_info->unused_bgs,
  8379. struct btrfs_block_group_cache,
  8380. bg_list);
  8381. space_info = block_group->space_info;
  8382. list_del_init(&block_group->bg_list);
  8383. if (ret || btrfs_mixed_space_info(space_info)) {
  8384. btrfs_put_block_group(block_group);
  8385. continue;
  8386. }
  8387. spin_unlock(&fs_info->unused_bgs_lock);
  8388. /* Don't want to race with allocators so take the groups_sem */
  8389. down_write(&space_info->groups_sem);
  8390. spin_lock(&block_group->lock);
  8391. if (block_group->reserved ||
  8392. btrfs_block_group_used(&block_group->item) ||
  8393. block_group->ro) {
  8394. /*
  8395. * We want to bail if we made new allocations or have
  8396. * outstanding allocations in this block group. We do
  8397. * the ro check in case balance is currently acting on
  8398. * this block group.
  8399. */
  8400. spin_unlock(&block_group->lock);
  8401. up_write(&space_info->groups_sem);
  8402. goto next;
  8403. }
  8404. spin_unlock(&block_group->lock);
  8405. /* We don't want to force the issue, only flip if it's ok. */
  8406. ret = set_block_group_ro(block_group, 0);
  8407. up_write(&space_info->groups_sem);
  8408. if (ret < 0) {
  8409. ret = 0;
  8410. goto next;
  8411. }
  8412. /*
  8413. * Want to do this before we do anything else so we can recover
  8414. * properly if we fail to join the transaction.
  8415. */
  8416. /* 1 for btrfs_orphan_reserve_metadata() */
  8417. trans = btrfs_start_transaction(root, 1);
  8418. if (IS_ERR(trans)) {
  8419. btrfs_set_block_group_rw(root, block_group);
  8420. ret = PTR_ERR(trans);
  8421. goto next;
  8422. }
  8423. /*
  8424. * We could have pending pinned extents for this block group,
  8425. * just delete them, we don't care about them anymore.
  8426. */
  8427. start = block_group->key.objectid;
  8428. end = start + block_group->key.offset - 1;
  8429. /*
  8430. * Hold the unused_bg_unpin_mutex lock to avoid racing with
  8431. * btrfs_finish_extent_commit(). If we are at transaction N,
  8432. * another task might be running finish_extent_commit() for the
  8433. * previous transaction N - 1, and have seen a range belonging
  8434. * to the block group in freed_extents[] before we were able to
  8435. * clear the whole block group range from freed_extents[]. This
  8436. * means that task can lookup for the block group after we
  8437. * unpinned it from freed_extents[] and removed it, leading to
  8438. * a BUG_ON() at btrfs_unpin_extent_range().
  8439. */
  8440. mutex_lock(&fs_info->unused_bg_unpin_mutex);
  8441. ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
  8442. EXTENT_DIRTY, GFP_NOFS);
  8443. if (ret) {
  8444. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  8445. btrfs_set_block_group_rw(root, block_group);
  8446. goto end_trans;
  8447. }
  8448. ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
  8449. EXTENT_DIRTY, GFP_NOFS);
  8450. if (ret) {
  8451. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  8452. btrfs_set_block_group_rw(root, block_group);
  8453. goto end_trans;
  8454. }
  8455. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  8456. /* Reset pinned so btrfs_put_block_group doesn't complain */
  8457. block_group->pinned = 0;
  8458. /*
  8459. * Btrfs_remove_chunk will abort the transaction if things go
  8460. * horribly wrong.
  8461. */
  8462. ret = btrfs_remove_chunk(trans, root,
  8463. block_group->key.objectid);
  8464. end_trans:
  8465. btrfs_end_transaction(trans, root);
  8466. next:
  8467. btrfs_put_block_group(block_group);
  8468. spin_lock(&fs_info->unused_bgs_lock);
  8469. }
  8470. spin_unlock(&fs_info->unused_bgs_lock);
  8471. }
  8472. int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
  8473. {
  8474. struct btrfs_space_info *space_info;
  8475. struct btrfs_super_block *disk_super;
  8476. u64 features;
  8477. u64 flags;
  8478. int mixed = 0;
  8479. int ret;
  8480. disk_super = fs_info->super_copy;
  8481. if (!btrfs_super_root(disk_super))
  8482. return 1;
  8483. features = btrfs_super_incompat_flags(disk_super);
  8484. if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
  8485. mixed = 1;
  8486. flags = BTRFS_BLOCK_GROUP_SYSTEM;
  8487. ret = update_space_info(fs_info, flags, 0, 0, &space_info);
  8488. if (ret)
  8489. goto out;
  8490. if (mixed) {
  8491. flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
  8492. ret = update_space_info(fs_info, flags, 0, 0, &space_info);
  8493. } else {
  8494. flags = BTRFS_BLOCK_GROUP_METADATA;
  8495. ret = update_space_info(fs_info, flags, 0, 0, &space_info);
  8496. if (ret)
  8497. goto out;
  8498. flags = BTRFS_BLOCK_GROUP_DATA;
  8499. ret = update_space_info(fs_info, flags, 0, 0, &space_info);
  8500. }
  8501. out:
  8502. return ret;
  8503. }
  8504. int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
  8505. {
  8506. return unpin_extent_range(root, start, end, false);
  8507. }
  8508. int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
  8509. {
  8510. struct btrfs_fs_info *fs_info = root->fs_info;
  8511. struct btrfs_block_group_cache *cache = NULL;
  8512. u64 group_trimmed;
  8513. u64 start;
  8514. u64 end;
  8515. u64 trimmed = 0;
  8516. u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
  8517. int ret = 0;
  8518. /*
  8519. * try to trim all FS space, our block group may start from non-zero.
  8520. */
  8521. if (range->len == total_bytes)
  8522. cache = btrfs_lookup_first_block_group(fs_info, range->start);
  8523. else
  8524. cache = btrfs_lookup_block_group(fs_info, range->start);
  8525. while (cache) {
  8526. if (cache->key.objectid >= (range->start + range->len)) {
  8527. btrfs_put_block_group(cache);
  8528. break;
  8529. }
  8530. start = max(range->start, cache->key.objectid);
  8531. end = min(range->start + range->len,
  8532. cache->key.objectid + cache->key.offset);
  8533. if (end - start >= range->minlen) {
  8534. if (!block_group_cache_done(cache)) {
  8535. ret = cache_block_group(cache, 0);
  8536. if (ret) {
  8537. btrfs_put_block_group(cache);
  8538. break;
  8539. }
  8540. ret = wait_block_group_cache_done(cache);
  8541. if (ret) {
  8542. btrfs_put_block_group(cache);
  8543. break;
  8544. }
  8545. }
  8546. ret = btrfs_trim_block_group(cache,
  8547. &group_trimmed,
  8548. start,
  8549. end,
  8550. range->minlen);
  8551. trimmed += group_trimmed;
  8552. if (ret) {
  8553. btrfs_put_block_group(cache);
  8554. break;
  8555. }
  8556. }
  8557. cache = next_block_group(fs_info->tree_root, cache);
  8558. }
  8559. range->len = trimmed;
  8560. return ret;
  8561. }
  8562. /*
  8563. * btrfs_{start,end}_write_no_snapshoting() are similar to
  8564. * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
  8565. * data into the page cache through nocow before the subvolume is snapshoted,
  8566. * but flush the data into disk after the snapshot creation, or to prevent
  8567. * operations while snapshoting is ongoing and that cause the snapshot to be
  8568. * inconsistent (writes followed by expanding truncates for example).
  8569. */
  8570. void btrfs_end_write_no_snapshoting(struct btrfs_root *root)
  8571. {
  8572. percpu_counter_dec(&root->subv_writers->counter);
  8573. /*
  8574. * Make sure counter is updated before we wake up
  8575. * waiters.
  8576. */
  8577. smp_mb();
  8578. if (waitqueue_active(&root->subv_writers->wait))
  8579. wake_up(&root->subv_writers->wait);
  8580. }
  8581. int btrfs_start_write_no_snapshoting(struct btrfs_root *root)
  8582. {
  8583. if (atomic_read(&root->will_be_snapshoted))
  8584. return 0;
  8585. percpu_counter_inc(&root->subv_writers->counter);
  8586. /*
  8587. * Make sure counter is updated before we check for snapshot creation.
  8588. */
  8589. smp_mb();
  8590. if (atomic_read(&root->will_be_snapshoted)) {
  8591. btrfs_end_write_no_snapshoting(root);
  8592. return 0;
  8593. }
  8594. return 1;
  8595. }