extent-tree.c 301 KB

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