extent-tree.c 301 KB

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