extent-tree.c 303 KB

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