extent-tree.c 299 KB

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