extent-tree.c 305 KB

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