extent-tree.c 301 KB

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