extent-tree.c 302 KB

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