extent-tree.c 305 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247
  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. /*
  3025. * We want to set the generation to 0, that way if anything goes wrong
  3026. * from here on out we know not to trust this cache when we load up next
  3027. * time.
  3028. */
  3029. BTRFS_I(inode)->generation = 0;
  3030. ret = btrfs_update_inode(trans, root, inode);
  3031. if (ret) {
  3032. /*
  3033. * So theoretically we could recover from this, simply set the
  3034. * super cache generation to 0 so we know to invalidate the
  3035. * cache, but then we'd have to keep track of the block groups
  3036. * that fail this way so we know we _have_ to reset this cache
  3037. * before the next commit or risk reading stale cache. So to
  3038. * limit our exposure to horrible edge cases lets just abort the
  3039. * transaction, this only happens in really bad situations
  3040. * anyway.
  3041. */
  3042. btrfs_abort_transaction(trans, ret);
  3043. goto out_put;
  3044. }
  3045. WARN_ON(ret);
  3046. /* We've already setup this transaction, go ahead and exit */
  3047. if (block_group->cache_generation == trans->transid &&
  3048. i_size_read(inode)) {
  3049. dcs = BTRFS_DC_SETUP;
  3050. goto out_put;
  3051. }
  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. cond_resched();
  4018. goto again;
  4019. }
  4020. trans->allocating_chunk = true;
  4021. /*
  4022. * If we have mixed data/metadata chunks we want to make sure we keep
  4023. * allocating mixed chunks instead of individual chunks.
  4024. */
  4025. if (btrfs_mixed_space_info(space_info))
  4026. flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
  4027. /*
  4028. * if we're doing a data chunk, go ahead and make sure that
  4029. * we keep a reasonable number of metadata chunks allocated in the
  4030. * FS as well.
  4031. */
  4032. if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
  4033. fs_info->data_chunk_allocations++;
  4034. if (!(fs_info->data_chunk_allocations %
  4035. fs_info->metadata_ratio))
  4036. force_metadata_allocation(fs_info);
  4037. }
  4038. /*
  4039. * Check if we have enough space in SYSTEM chunk because we may need
  4040. * to update devices.
  4041. */
  4042. check_system_chunk(trans, extent_root, flags);
  4043. ret = btrfs_alloc_chunk(trans, extent_root, flags);
  4044. trans->allocating_chunk = false;
  4045. spin_lock(&space_info->lock);
  4046. if (ret < 0 && ret != -ENOSPC)
  4047. goto out;
  4048. if (ret)
  4049. space_info->full = 1;
  4050. else
  4051. ret = 1;
  4052. space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
  4053. out:
  4054. space_info->chunk_alloc = 0;
  4055. spin_unlock(&space_info->lock);
  4056. mutex_unlock(&fs_info->chunk_mutex);
  4057. /*
  4058. * When we allocate a new chunk we reserve space in the chunk block
  4059. * reserve to make sure we can COW nodes/leafs in the chunk tree or
  4060. * add new nodes/leafs to it if we end up needing to do it when
  4061. * inserting the chunk item and updating device items as part of the
  4062. * second phase of chunk allocation, performed by
  4063. * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
  4064. * large number of new block groups to create in our transaction
  4065. * handle's new_bgs list to avoid exhausting the chunk block reserve
  4066. * in extreme cases - like having a single transaction create many new
  4067. * block groups when starting to write out the free space caches of all
  4068. * the block groups that were made dirty during the lifetime of the
  4069. * transaction.
  4070. */
  4071. if (trans->can_flush_pending_bgs &&
  4072. trans->chunk_bytes_reserved >= (u64)SZ_2M) {
  4073. btrfs_create_pending_block_groups(trans, extent_root);
  4074. btrfs_trans_release_chunk_metadata(trans);
  4075. }
  4076. return ret;
  4077. }
  4078. static int can_overcommit(struct btrfs_root *root,
  4079. struct btrfs_space_info *space_info, u64 bytes,
  4080. enum btrfs_reserve_flush_enum flush)
  4081. {
  4082. struct btrfs_block_rsv *global_rsv;
  4083. u64 profile;
  4084. u64 space_size;
  4085. u64 avail;
  4086. u64 used;
  4087. /* Don't overcommit when in mixed mode. */
  4088. if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
  4089. return 0;
  4090. BUG_ON(root->fs_info == NULL);
  4091. global_rsv = &root->fs_info->global_block_rsv;
  4092. profile = btrfs_get_alloc_profile(root, 0);
  4093. used = space_info->bytes_used + space_info->bytes_reserved +
  4094. space_info->bytes_pinned + space_info->bytes_readonly;
  4095. /*
  4096. * We only want to allow over committing if we have lots of actual space
  4097. * free, but if we don't have enough space to handle the global reserve
  4098. * space then we could end up having a real enospc problem when trying
  4099. * to allocate a chunk or some other such important allocation.
  4100. */
  4101. spin_lock(&global_rsv->lock);
  4102. space_size = calc_global_rsv_need_space(global_rsv);
  4103. spin_unlock(&global_rsv->lock);
  4104. if (used + space_size >= space_info->total_bytes)
  4105. return 0;
  4106. used += space_info->bytes_may_use;
  4107. spin_lock(&root->fs_info->free_chunk_lock);
  4108. avail = root->fs_info->free_chunk_space;
  4109. spin_unlock(&root->fs_info->free_chunk_lock);
  4110. /*
  4111. * If we have dup, raid1 or raid10 then only half of the free
  4112. * space is actually useable. For raid56, the space info used
  4113. * doesn't include the parity drive, so we don't have to
  4114. * change the math
  4115. */
  4116. if (profile & (BTRFS_BLOCK_GROUP_DUP |
  4117. BTRFS_BLOCK_GROUP_RAID1 |
  4118. BTRFS_BLOCK_GROUP_RAID10))
  4119. avail >>= 1;
  4120. /*
  4121. * If we aren't flushing all things, let us overcommit up to
  4122. * 1/2th of the space. If we can flush, don't let us overcommit
  4123. * too much, let it overcommit up to 1/8 of the space.
  4124. */
  4125. if (flush == BTRFS_RESERVE_FLUSH_ALL)
  4126. avail >>= 3;
  4127. else
  4128. avail >>= 1;
  4129. if (used + bytes < space_info->total_bytes + avail)
  4130. return 1;
  4131. return 0;
  4132. }
  4133. static void btrfs_writeback_inodes_sb_nr(struct btrfs_root *root,
  4134. unsigned long nr_pages, int nr_items)
  4135. {
  4136. struct super_block *sb = root->fs_info->sb;
  4137. if (down_read_trylock(&sb->s_umount)) {
  4138. writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
  4139. up_read(&sb->s_umount);
  4140. } else {
  4141. /*
  4142. * We needn't worry the filesystem going from r/w to r/o though
  4143. * we don't acquire ->s_umount mutex, because the filesystem
  4144. * should guarantee the delalloc inodes list be empty after
  4145. * the filesystem is readonly(all dirty pages are written to
  4146. * the disk).
  4147. */
  4148. btrfs_start_delalloc_roots(root->fs_info, 0, nr_items);
  4149. if (!current->journal_info)
  4150. btrfs_wait_ordered_roots(root->fs_info, nr_items,
  4151. 0, (u64)-1);
  4152. }
  4153. }
  4154. static inline int calc_reclaim_items_nr(struct btrfs_root *root, u64 to_reclaim)
  4155. {
  4156. u64 bytes;
  4157. int nr;
  4158. bytes = btrfs_calc_trans_metadata_size(root, 1);
  4159. nr = (int)div64_u64(to_reclaim, bytes);
  4160. if (!nr)
  4161. nr = 1;
  4162. return nr;
  4163. }
  4164. #define EXTENT_SIZE_PER_ITEM SZ_256K
  4165. /*
  4166. * shrink metadata reservation for delalloc
  4167. */
  4168. static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
  4169. bool wait_ordered)
  4170. {
  4171. struct btrfs_block_rsv *block_rsv;
  4172. struct btrfs_space_info *space_info;
  4173. struct btrfs_trans_handle *trans;
  4174. u64 delalloc_bytes;
  4175. u64 max_reclaim;
  4176. long time_left;
  4177. unsigned long nr_pages;
  4178. int loops;
  4179. int items;
  4180. enum btrfs_reserve_flush_enum flush;
  4181. /* Calc the number of the pages we need flush for space reservation */
  4182. items = calc_reclaim_items_nr(root, to_reclaim);
  4183. to_reclaim = (u64)items * EXTENT_SIZE_PER_ITEM;
  4184. trans = (struct btrfs_trans_handle *)current->journal_info;
  4185. block_rsv = &root->fs_info->delalloc_block_rsv;
  4186. space_info = block_rsv->space_info;
  4187. delalloc_bytes = percpu_counter_sum_positive(
  4188. &root->fs_info->delalloc_bytes);
  4189. if (delalloc_bytes == 0) {
  4190. if (trans)
  4191. return;
  4192. if (wait_ordered)
  4193. btrfs_wait_ordered_roots(root->fs_info, items,
  4194. 0, (u64)-1);
  4195. return;
  4196. }
  4197. loops = 0;
  4198. while (delalloc_bytes && loops < 3) {
  4199. max_reclaim = min(delalloc_bytes, to_reclaim);
  4200. nr_pages = max_reclaim >> PAGE_SHIFT;
  4201. btrfs_writeback_inodes_sb_nr(root, nr_pages, items);
  4202. /*
  4203. * We need to wait for the async pages to actually start before
  4204. * we do anything.
  4205. */
  4206. max_reclaim = atomic_read(&root->fs_info->async_delalloc_pages);
  4207. if (!max_reclaim)
  4208. goto skip_async;
  4209. if (max_reclaim <= nr_pages)
  4210. max_reclaim = 0;
  4211. else
  4212. max_reclaim -= nr_pages;
  4213. wait_event(root->fs_info->async_submit_wait,
  4214. atomic_read(&root->fs_info->async_delalloc_pages) <=
  4215. (int)max_reclaim);
  4216. skip_async:
  4217. if (!trans)
  4218. flush = BTRFS_RESERVE_FLUSH_ALL;
  4219. else
  4220. flush = BTRFS_RESERVE_NO_FLUSH;
  4221. spin_lock(&space_info->lock);
  4222. if (list_empty(&space_info->tickets) &&
  4223. list_empty(&space_info->priority_tickets)) {
  4224. spin_unlock(&space_info->lock);
  4225. break;
  4226. }
  4227. spin_unlock(&space_info->lock);
  4228. loops++;
  4229. if (wait_ordered && !trans) {
  4230. btrfs_wait_ordered_roots(root->fs_info, items,
  4231. 0, (u64)-1);
  4232. } else {
  4233. time_left = schedule_timeout_killable(1);
  4234. if (time_left)
  4235. break;
  4236. }
  4237. delalloc_bytes = percpu_counter_sum_positive(
  4238. &root->fs_info->delalloc_bytes);
  4239. }
  4240. }
  4241. /**
  4242. * maybe_commit_transaction - possibly commit the transaction if its ok to
  4243. * @root - the root we're allocating for
  4244. * @bytes - the number of bytes we want to reserve
  4245. * @force - force the commit
  4246. *
  4247. * This will check to make sure that committing the transaction will actually
  4248. * get us somewhere and then commit the transaction if it does. Otherwise it
  4249. * will return -ENOSPC.
  4250. */
  4251. static int may_commit_transaction(struct btrfs_root *root,
  4252. struct btrfs_space_info *space_info,
  4253. u64 bytes, int force)
  4254. {
  4255. struct btrfs_block_rsv *delayed_rsv = &root->fs_info->delayed_block_rsv;
  4256. struct btrfs_trans_handle *trans;
  4257. trans = (struct btrfs_trans_handle *)current->journal_info;
  4258. if (trans)
  4259. return -EAGAIN;
  4260. if (force)
  4261. goto commit;
  4262. /* See if there is enough pinned space to make this reservation */
  4263. if (percpu_counter_compare(&space_info->total_bytes_pinned,
  4264. bytes) >= 0)
  4265. goto commit;
  4266. /*
  4267. * See if there is some space in the delayed insertion reservation for
  4268. * this reservation.
  4269. */
  4270. if (space_info != delayed_rsv->space_info)
  4271. return -ENOSPC;
  4272. spin_lock(&delayed_rsv->lock);
  4273. if (percpu_counter_compare(&space_info->total_bytes_pinned,
  4274. bytes - delayed_rsv->size) >= 0) {
  4275. spin_unlock(&delayed_rsv->lock);
  4276. return -ENOSPC;
  4277. }
  4278. spin_unlock(&delayed_rsv->lock);
  4279. commit:
  4280. trans = btrfs_join_transaction(root);
  4281. if (IS_ERR(trans))
  4282. return -ENOSPC;
  4283. return btrfs_commit_transaction(trans, root);
  4284. }
  4285. struct reserve_ticket {
  4286. u64 bytes;
  4287. int error;
  4288. struct list_head list;
  4289. wait_queue_head_t wait;
  4290. };
  4291. static int flush_space(struct btrfs_root *root,
  4292. struct btrfs_space_info *space_info, u64 num_bytes,
  4293. u64 orig_bytes, int state)
  4294. {
  4295. struct btrfs_trans_handle *trans;
  4296. int nr;
  4297. int ret = 0;
  4298. switch (state) {
  4299. case FLUSH_DELAYED_ITEMS_NR:
  4300. case FLUSH_DELAYED_ITEMS:
  4301. if (state == FLUSH_DELAYED_ITEMS_NR)
  4302. nr = calc_reclaim_items_nr(root, num_bytes) * 2;
  4303. else
  4304. nr = -1;
  4305. trans = btrfs_join_transaction(root);
  4306. if (IS_ERR(trans)) {
  4307. ret = PTR_ERR(trans);
  4308. break;
  4309. }
  4310. ret = btrfs_run_delayed_items_nr(trans, root, nr);
  4311. btrfs_end_transaction(trans, root);
  4312. break;
  4313. case FLUSH_DELALLOC:
  4314. case FLUSH_DELALLOC_WAIT:
  4315. shrink_delalloc(root, num_bytes * 2, orig_bytes,
  4316. state == FLUSH_DELALLOC_WAIT);
  4317. break;
  4318. case ALLOC_CHUNK:
  4319. trans = btrfs_join_transaction(root);
  4320. if (IS_ERR(trans)) {
  4321. ret = PTR_ERR(trans);
  4322. break;
  4323. }
  4324. ret = do_chunk_alloc(trans, root->fs_info->extent_root,
  4325. btrfs_get_alloc_profile(root, 0),
  4326. CHUNK_ALLOC_NO_FORCE);
  4327. btrfs_end_transaction(trans, root);
  4328. if (ret > 0 || ret == -ENOSPC)
  4329. ret = 0;
  4330. break;
  4331. case COMMIT_TRANS:
  4332. ret = may_commit_transaction(root, space_info, orig_bytes, 0);
  4333. break;
  4334. default:
  4335. ret = -ENOSPC;
  4336. break;
  4337. }
  4338. trace_btrfs_flush_space(root->fs_info, space_info->flags, num_bytes,
  4339. orig_bytes, state, ret);
  4340. return ret;
  4341. }
  4342. static inline u64
  4343. btrfs_calc_reclaim_metadata_size(struct btrfs_root *root,
  4344. struct btrfs_space_info *space_info)
  4345. {
  4346. struct reserve_ticket *ticket;
  4347. u64 used;
  4348. u64 expected;
  4349. u64 to_reclaim = 0;
  4350. list_for_each_entry(ticket, &space_info->tickets, list)
  4351. to_reclaim += ticket->bytes;
  4352. list_for_each_entry(ticket, &space_info->priority_tickets, list)
  4353. to_reclaim += ticket->bytes;
  4354. if (to_reclaim)
  4355. return to_reclaim;
  4356. to_reclaim = min_t(u64, num_online_cpus() * SZ_1M, SZ_16M);
  4357. if (can_overcommit(root, space_info, to_reclaim,
  4358. BTRFS_RESERVE_FLUSH_ALL))
  4359. return 0;
  4360. used = space_info->bytes_used + space_info->bytes_reserved +
  4361. space_info->bytes_pinned + space_info->bytes_readonly +
  4362. space_info->bytes_may_use;
  4363. if (can_overcommit(root, space_info, SZ_1M, BTRFS_RESERVE_FLUSH_ALL))
  4364. expected = div_factor_fine(space_info->total_bytes, 95);
  4365. else
  4366. expected = div_factor_fine(space_info->total_bytes, 90);
  4367. if (used > expected)
  4368. to_reclaim = used - expected;
  4369. else
  4370. to_reclaim = 0;
  4371. to_reclaim = min(to_reclaim, space_info->bytes_may_use +
  4372. space_info->bytes_reserved);
  4373. return to_reclaim;
  4374. }
  4375. static inline int need_do_async_reclaim(struct btrfs_space_info *space_info,
  4376. struct btrfs_root *root, u64 used)
  4377. {
  4378. u64 thresh = div_factor_fine(space_info->total_bytes, 98);
  4379. /* If we're just plain full then async reclaim just slows us down. */
  4380. if ((space_info->bytes_used + space_info->bytes_reserved) >= thresh)
  4381. return 0;
  4382. if (!btrfs_calc_reclaim_metadata_size(root, space_info))
  4383. return 0;
  4384. return (used >= thresh && !btrfs_fs_closing(root->fs_info) &&
  4385. !test_bit(BTRFS_FS_STATE_REMOUNTING,
  4386. &root->fs_info->fs_state));
  4387. }
  4388. static void wake_all_tickets(struct list_head *head)
  4389. {
  4390. struct reserve_ticket *ticket;
  4391. while (!list_empty(head)) {
  4392. ticket = list_first_entry(head, struct reserve_ticket, list);
  4393. list_del_init(&ticket->list);
  4394. ticket->error = -ENOSPC;
  4395. wake_up(&ticket->wait);
  4396. }
  4397. }
  4398. /*
  4399. * This is for normal flushers, we can wait all goddamned day if we want to. We
  4400. * will loop and continuously try to flush as long as we are making progress.
  4401. * We count progress as clearing off tickets each time we have to loop.
  4402. */
  4403. static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
  4404. {
  4405. struct btrfs_fs_info *fs_info;
  4406. struct btrfs_space_info *space_info;
  4407. u64 to_reclaim;
  4408. int flush_state;
  4409. int commit_cycles = 0;
  4410. u64 last_tickets_id;
  4411. fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
  4412. space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
  4413. spin_lock(&space_info->lock);
  4414. to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
  4415. space_info);
  4416. if (!to_reclaim) {
  4417. space_info->flush = 0;
  4418. spin_unlock(&space_info->lock);
  4419. return;
  4420. }
  4421. last_tickets_id = space_info->tickets_id;
  4422. spin_unlock(&space_info->lock);
  4423. flush_state = FLUSH_DELAYED_ITEMS_NR;
  4424. do {
  4425. struct reserve_ticket *ticket;
  4426. int ret;
  4427. ret = flush_space(fs_info->fs_root, space_info, to_reclaim,
  4428. to_reclaim, flush_state);
  4429. spin_lock(&space_info->lock);
  4430. if (list_empty(&space_info->tickets)) {
  4431. space_info->flush = 0;
  4432. spin_unlock(&space_info->lock);
  4433. return;
  4434. }
  4435. to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
  4436. space_info);
  4437. ticket = list_first_entry(&space_info->tickets,
  4438. struct reserve_ticket, list);
  4439. if (last_tickets_id == space_info->tickets_id) {
  4440. flush_state++;
  4441. } else {
  4442. last_tickets_id = space_info->tickets_id;
  4443. flush_state = FLUSH_DELAYED_ITEMS_NR;
  4444. if (commit_cycles)
  4445. commit_cycles--;
  4446. }
  4447. if (flush_state > COMMIT_TRANS) {
  4448. commit_cycles++;
  4449. if (commit_cycles > 2) {
  4450. wake_all_tickets(&space_info->tickets);
  4451. space_info->flush = 0;
  4452. } else {
  4453. flush_state = FLUSH_DELAYED_ITEMS_NR;
  4454. }
  4455. }
  4456. spin_unlock(&space_info->lock);
  4457. } while (flush_state <= COMMIT_TRANS);
  4458. }
  4459. void btrfs_init_async_reclaim_work(struct work_struct *work)
  4460. {
  4461. INIT_WORK(work, btrfs_async_reclaim_metadata_space);
  4462. }
  4463. static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
  4464. struct btrfs_space_info *space_info,
  4465. struct reserve_ticket *ticket)
  4466. {
  4467. u64 to_reclaim;
  4468. int flush_state = FLUSH_DELAYED_ITEMS_NR;
  4469. spin_lock(&space_info->lock);
  4470. to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
  4471. space_info);
  4472. if (!to_reclaim) {
  4473. spin_unlock(&space_info->lock);
  4474. return;
  4475. }
  4476. spin_unlock(&space_info->lock);
  4477. do {
  4478. flush_space(fs_info->fs_root, space_info, to_reclaim,
  4479. to_reclaim, flush_state);
  4480. flush_state++;
  4481. spin_lock(&space_info->lock);
  4482. if (ticket->bytes == 0) {
  4483. spin_unlock(&space_info->lock);
  4484. return;
  4485. }
  4486. spin_unlock(&space_info->lock);
  4487. /*
  4488. * Priority flushers can't wait on delalloc without
  4489. * deadlocking.
  4490. */
  4491. if (flush_state == FLUSH_DELALLOC ||
  4492. flush_state == FLUSH_DELALLOC_WAIT)
  4493. flush_state = ALLOC_CHUNK;
  4494. } while (flush_state < COMMIT_TRANS);
  4495. }
  4496. static int wait_reserve_ticket(struct btrfs_fs_info *fs_info,
  4497. struct btrfs_space_info *space_info,
  4498. struct reserve_ticket *ticket, u64 orig_bytes)
  4499. {
  4500. DEFINE_WAIT(wait);
  4501. int ret = 0;
  4502. spin_lock(&space_info->lock);
  4503. while (ticket->bytes > 0 && ticket->error == 0) {
  4504. ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
  4505. if (ret) {
  4506. ret = -EINTR;
  4507. break;
  4508. }
  4509. spin_unlock(&space_info->lock);
  4510. schedule();
  4511. finish_wait(&ticket->wait, &wait);
  4512. spin_lock(&space_info->lock);
  4513. }
  4514. if (!ret)
  4515. ret = ticket->error;
  4516. if (!list_empty(&ticket->list))
  4517. list_del_init(&ticket->list);
  4518. if (ticket->bytes && ticket->bytes < orig_bytes) {
  4519. u64 num_bytes = orig_bytes - ticket->bytes;
  4520. space_info->bytes_may_use -= num_bytes;
  4521. trace_btrfs_space_reservation(fs_info, "space_info",
  4522. space_info->flags, num_bytes, 0);
  4523. }
  4524. spin_unlock(&space_info->lock);
  4525. return ret;
  4526. }
  4527. /**
  4528. * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
  4529. * @root - the root we're allocating for
  4530. * @space_info - the space info we want to allocate from
  4531. * @orig_bytes - the number of bytes we want
  4532. * @flush - whether or not we can flush to make our reservation
  4533. *
  4534. * This will reserve orig_bytes number of bytes from the space info associated
  4535. * with the block_rsv. If there is not enough space it will make an attempt to
  4536. * flush out space to make room. It will do this by flushing delalloc if
  4537. * possible or committing the transaction. If flush is 0 then no attempts to
  4538. * regain reservations will be made and this will fail if there is not enough
  4539. * space already.
  4540. */
  4541. static int __reserve_metadata_bytes(struct btrfs_root *root,
  4542. struct btrfs_space_info *space_info,
  4543. u64 orig_bytes,
  4544. enum btrfs_reserve_flush_enum flush)
  4545. {
  4546. struct reserve_ticket ticket;
  4547. u64 used;
  4548. int ret = 0;
  4549. ASSERT(orig_bytes);
  4550. ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
  4551. spin_lock(&space_info->lock);
  4552. ret = -ENOSPC;
  4553. used = space_info->bytes_used + space_info->bytes_reserved +
  4554. space_info->bytes_pinned + space_info->bytes_readonly +
  4555. space_info->bytes_may_use;
  4556. /*
  4557. * If we have enough space then hooray, make our reservation and carry
  4558. * on. If not see if we can overcommit, and if we can, hooray carry on.
  4559. * If not things get more complicated.
  4560. */
  4561. if (used + orig_bytes <= space_info->total_bytes) {
  4562. space_info->bytes_may_use += orig_bytes;
  4563. trace_btrfs_space_reservation(root->fs_info, "space_info",
  4564. space_info->flags, orig_bytes,
  4565. 1);
  4566. ret = 0;
  4567. } else if (can_overcommit(root, space_info, orig_bytes, flush)) {
  4568. space_info->bytes_may_use += orig_bytes;
  4569. trace_btrfs_space_reservation(root->fs_info, "space_info",
  4570. space_info->flags, orig_bytes,
  4571. 1);
  4572. ret = 0;
  4573. }
  4574. /*
  4575. * If we couldn't make a reservation then setup our reservation ticket
  4576. * and kick the async worker if it's not already running.
  4577. *
  4578. * If we are a priority flusher then we just need to add our ticket to
  4579. * the list and we will do our own flushing further down.
  4580. */
  4581. if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
  4582. ticket.bytes = orig_bytes;
  4583. ticket.error = 0;
  4584. init_waitqueue_head(&ticket.wait);
  4585. if (flush == BTRFS_RESERVE_FLUSH_ALL) {
  4586. list_add_tail(&ticket.list, &space_info->tickets);
  4587. if (!space_info->flush) {
  4588. space_info->flush = 1;
  4589. trace_btrfs_trigger_flush(root->fs_info,
  4590. space_info->flags,
  4591. orig_bytes, flush,
  4592. "enospc");
  4593. queue_work(system_unbound_wq,
  4594. &root->fs_info->async_reclaim_work);
  4595. }
  4596. } else {
  4597. list_add_tail(&ticket.list,
  4598. &space_info->priority_tickets);
  4599. }
  4600. } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
  4601. used += orig_bytes;
  4602. /*
  4603. * We will do the space reservation dance during log replay,
  4604. * which means we won't have fs_info->fs_root set, so don't do
  4605. * the async reclaim as we will panic.
  4606. */
  4607. if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags) &&
  4608. need_do_async_reclaim(space_info, root, used) &&
  4609. !work_busy(&root->fs_info->async_reclaim_work)) {
  4610. trace_btrfs_trigger_flush(root->fs_info,
  4611. space_info->flags,
  4612. orig_bytes, flush,
  4613. "preempt");
  4614. queue_work(system_unbound_wq,
  4615. &root->fs_info->async_reclaim_work);
  4616. }
  4617. }
  4618. spin_unlock(&space_info->lock);
  4619. if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
  4620. return ret;
  4621. if (flush == BTRFS_RESERVE_FLUSH_ALL)
  4622. return wait_reserve_ticket(root->fs_info, space_info, &ticket,
  4623. orig_bytes);
  4624. ret = 0;
  4625. priority_reclaim_metadata_space(root->fs_info, space_info, &ticket);
  4626. spin_lock(&space_info->lock);
  4627. if (ticket.bytes) {
  4628. if (ticket.bytes < orig_bytes) {
  4629. u64 num_bytes = orig_bytes - ticket.bytes;
  4630. space_info->bytes_may_use -= num_bytes;
  4631. trace_btrfs_space_reservation(root->fs_info,
  4632. "space_info", space_info->flags,
  4633. num_bytes, 0);
  4634. }
  4635. list_del_init(&ticket.list);
  4636. ret = -ENOSPC;
  4637. }
  4638. spin_unlock(&space_info->lock);
  4639. ASSERT(list_empty(&ticket.list));
  4640. return ret;
  4641. }
  4642. /**
  4643. * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
  4644. * @root - the root we're allocating for
  4645. * @block_rsv - the block_rsv we're allocating for
  4646. * @orig_bytes - the number of bytes we want
  4647. * @flush - whether or not we can flush to make our reservation
  4648. *
  4649. * This will reserve orgi_bytes number of bytes from the space info associated
  4650. * with the block_rsv. If there is not enough space it will make an attempt to
  4651. * flush out space to make room. It will do this by flushing delalloc if
  4652. * possible or committing the transaction. If flush is 0 then no attempts to
  4653. * regain reservations will be made and this will fail if there is not enough
  4654. * space already.
  4655. */
  4656. static int reserve_metadata_bytes(struct btrfs_root *root,
  4657. struct btrfs_block_rsv *block_rsv,
  4658. u64 orig_bytes,
  4659. enum btrfs_reserve_flush_enum flush)
  4660. {
  4661. int ret;
  4662. ret = __reserve_metadata_bytes(root, block_rsv->space_info, orig_bytes,
  4663. flush);
  4664. if (ret == -ENOSPC &&
  4665. unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
  4666. struct btrfs_block_rsv *global_rsv =
  4667. &root->fs_info->global_block_rsv;
  4668. if (block_rsv != global_rsv &&
  4669. !block_rsv_use_bytes(global_rsv, orig_bytes))
  4670. ret = 0;
  4671. }
  4672. if (ret == -ENOSPC)
  4673. trace_btrfs_space_reservation(root->fs_info,
  4674. "space_info:enospc",
  4675. block_rsv->space_info->flags,
  4676. orig_bytes, 1);
  4677. return ret;
  4678. }
  4679. static struct btrfs_block_rsv *get_block_rsv(
  4680. const struct btrfs_trans_handle *trans,
  4681. const struct btrfs_root *root)
  4682. {
  4683. struct btrfs_block_rsv *block_rsv = NULL;
  4684. if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
  4685. (root == root->fs_info->csum_root && trans->adding_csums) ||
  4686. (root == root->fs_info->uuid_root))
  4687. block_rsv = trans->block_rsv;
  4688. if (!block_rsv)
  4689. block_rsv = root->block_rsv;
  4690. if (!block_rsv)
  4691. block_rsv = &root->fs_info->empty_block_rsv;
  4692. return block_rsv;
  4693. }
  4694. static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
  4695. u64 num_bytes)
  4696. {
  4697. int ret = -ENOSPC;
  4698. spin_lock(&block_rsv->lock);
  4699. if (block_rsv->reserved >= num_bytes) {
  4700. block_rsv->reserved -= num_bytes;
  4701. if (block_rsv->reserved < block_rsv->size)
  4702. block_rsv->full = 0;
  4703. ret = 0;
  4704. }
  4705. spin_unlock(&block_rsv->lock);
  4706. return ret;
  4707. }
  4708. static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
  4709. u64 num_bytes, int update_size)
  4710. {
  4711. spin_lock(&block_rsv->lock);
  4712. block_rsv->reserved += num_bytes;
  4713. if (update_size)
  4714. block_rsv->size += num_bytes;
  4715. else if (block_rsv->reserved >= block_rsv->size)
  4716. block_rsv->full = 1;
  4717. spin_unlock(&block_rsv->lock);
  4718. }
  4719. int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
  4720. struct btrfs_block_rsv *dest, u64 num_bytes,
  4721. int min_factor)
  4722. {
  4723. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  4724. u64 min_bytes;
  4725. if (global_rsv->space_info != dest->space_info)
  4726. return -ENOSPC;
  4727. spin_lock(&global_rsv->lock);
  4728. min_bytes = div_factor(global_rsv->size, min_factor);
  4729. if (global_rsv->reserved < min_bytes + num_bytes) {
  4730. spin_unlock(&global_rsv->lock);
  4731. return -ENOSPC;
  4732. }
  4733. global_rsv->reserved -= num_bytes;
  4734. if (global_rsv->reserved < global_rsv->size)
  4735. global_rsv->full = 0;
  4736. spin_unlock(&global_rsv->lock);
  4737. block_rsv_add_bytes(dest, num_bytes, 1);
  4738. return 0;
  4739. }
  4740. /*
  4741. * This is for space we already have accounted in space_info->bytes_may_use, so
  4742. * basically when we're returning space from block_rsv's.
  4743. */
  4744. static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
  4745. struct btrfs_space_info *space_info,
  4746. u64 num_bytes)
  4747. {
  4748. struct reserve_ticket *ticket;
  4749. struct list_head *head;
  4750. u64 used;
  4751. enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
  4752. bool check_overcommit = false;
  4753. spin_lock(&space_info->lock);
  4754. head = &space_info->priority_tickets;
  4755. /*
  4756. * If we are over our limit then we need to check and see if we can
  4757. * overcommit, and if we can't then we just need to free up our space
  4758. * and not satisfy any requests.
  4759. */
  4760. used = space_info->bytes_used + space_info->bytes_reserved +
  4761. space_info->bytes_pinned + space_info->bytes_readonly +
  4762. space_info->bytes_may_use;
  4763. if (used - num_bytes >= space_info->total_bytes)
  4764. check_overcommit = true;
  4765. again:
  4766. while (!list_empty(head) && num_bytes) {
  4767. ticket = list_first_entry(head, struct reserve_ticket,
  4768. list);
  4769. /*
  4770. * We use 0 bytes because this space is already reserved, so
  4771. * adding the ticket space would be a double count.
  4772. */
  4773. if (check_overcommit &&
  4774. !can_overcommit(fs_info->extent_root, space_info, 0,
  4775. flush))
  4776. break;
  4777. if (num_bytes >= ticket->bytes) {
  4778. list_del_init(&ticket->list);
  4779. num_bytes -= ticket->bytes;
  4780. ticket->bytes = 0;
  4781. space_info->tickets_id++;
  4782. wake_up(&ticket->wait);
  4783. } else {
  4784. ticket->bytes -= num_bytes;
  4785. num_bytes = 0;
  4786. }
  4787. }
  4788. if (num_bytes && head == &space_info->priority_tickets) {
  4789. head = &space_info->tickets;
  4790. flush = BTRFS_RESERVE_FLUSH_ALL;
  4791. goto again;
  4792. }
  4793. space_info->bytes_may_use -= num_bytes;
  4794. trace_btrfs_space_reservation(fs_info, "space_info",
  4795. space_info->flags, num_bytes, 0);
  4796. spin_unlock(&space_info->lock);
  4797. }
  4798. /*
  4799. * This is for newly allocated space that isn't accounted in
  4800. * space_info->bytes_may_use yet. So if we allocate a chunk or unpin an extent
  4801. * we use this helper.
  4802. */
  4803. static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
  4804. struct btrfs_space_info *space_info,
  4805. u64 num_bytes)
  4806. {
  4807. struct reserve_ticket *ticket;
  4808. struct list_head *head = &space_info->priority_tickets;
  4809. again:
  4810. while (!list_empty(head) && num_bytes) {
  4811. ticket = list_first_entry(head, struct reserve_ticket,
  4812. list);
  4813. if (num_bytes >= ticket->bytes) {
  4814. trace_btrfs_space_reservation(fs_info, "space_info",
  4815. space_info->flags,
  4816. ticket->bytes, 1);
  4817. list_del_init(&ticket->list);
  4818. num_bytes -= ticket->bytes;
  4819. space_info->bytes_may_use += ticket->bytes;
  4820. ticket->bytes = 0;
  4821. space_info->tickets_id++;
  4822. wake_up(&ticket->wait);
  4823. } else {
  4824. trace_btrfs_space_reservation(fs_info, "space_info",
  4825. space_info->flags,
  4826. num_bytes, 1);
  4827. space_info->bytes_may_use += num_bytes;
  4828. ticket->bytes -= num_bytes;
  4829. num_bytes = 0;
  4830. }
  4831. }
  4832. if (num_bytes && head == &space_info->priority_tickets) {
  4833. head = &space_info->tickets;
  4834. goto again;
  4835. }
  4836. }
  4837. static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
  4838. struct btrfs_block_rsv *block_rsv,
  4839. struct btrfs_block_rsv *dest, u64 num_bytes)
  4840. {
  4841. struct btrfs_space_info *space_info = block_rsv->space_info;
  4842. spin_lock(&block_rsv->lock);
  4843. if (num_bytes == (u64)-1)
  4844. num_bytes = block_rsv->size;
  4845. block_rsv->size -= num_bytes;
  4846. if (block_rsv->reserved >= block_rsv->size) {
  4847. num_bytes = block_rsv->reserved - block_rsv->size;
  4848. block_rsv->reserved = block_rsv->size;
  4849. block_rsv->full = 1;
  4850. } else {
  4851. num_bytes = 0;
  4852. }
  4853. spin_unlock(&block_rsv->lock);
  4854. if (num_bytes > 0) {
  4855. if (dest) {
  4856. spin_lock(&dest->lock);
  4857. if (!dest->full) {
  4858. u64 bytes_to_add;
  4859. bytes_to_add = dest->size - dest->reserved;
  4860. bytes_to_add = min(num_bytes, bytes_to_add);
  4861. dest->reserved += bytes_to_add;
  4862. if (dest->reserved >= dest->size)
  4863. dest->full = 1;
  4864. num_bytes -= bytes_to_add;
  4865. }
  4866. spin_unlock(&dest->lock);
  4867. }
  4868. if (num_bytes)
  4869. space_info_add_old_bytes(fs_info, space_info,
  4870. num_bytes);
  4871. }
  4872. }
  4873. int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
  4874. struct btrfs_block_rsv *dst, u64 num_bytes,
  4875. int update_size)
  4876. {
  4877. int ret;
  4878. ret = block_rsv_use_bytes(src, num_bytes);
  4879. if (ret)
  4880. return ret;
  4881. block_rsv_add_bytes(dst, num_bytes, update_size);
  4882. return 0;
  4883. }
  4884. void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
  4885. {
  4886. memset(rsv, 0, sizeof(*rsv));
  4887. spin_lock_init(&rsv->lock);
  4888. rsv->type = type;
  4889. }
  4890. struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root,
  4891. unsigned short type)
  4892. {
  4893. struct btrfs_block_rsv *block_rsv;
  4894. struct btrfs_fs_info *fs_info = root->fs_info;
  4895. block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
  4896. if (!block_rsv)
  4897. return NULL;
  4898. btrfs_init_block_rsv(block_rsv, type);
  4899. block_rsv->space_info = __find_space_info(fs_info,
  4900. BTRFS_BLOCK_GROUP_METADATA);
  4901. return block_rsv;
  4902. }
  4903. void btrfs_free_block_rsv(struct btrfs_root *root,
  4904. struct btrfs_block_rsv *rsv)
  4905. {
  4906. if (!rsv)
  4907. return;
  4908. btrfs_block_rsv_release(root, rsv, (u64)-1);
  4909. kfree(rsv);
  4910. }
  4911. void __btrfs_free_block_rsv(struct btrfs_block_rsv *rsv)
  4912. {
  4913. kfree(rsv);
  4914. }
  4915. int btrfs_block_rsv_add(struct btrfs_root *root,
  4916. struct btrfs_block_rsv *block_rsv, u64 num_bytes,
  4917. enum btrfs_reserve_flush_enum flush)
  4918. {
  4919. int ret;
  4920. if (num_bytes == 0)
  4921. return 0;
  4922. ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
  4923. if (!ret) {
  4924. block_rsv_add_bytes(block_rsv, num_bytes, 1);
  4925. return 0;
  4926. }
  4927. return ret;
  4928. }
  4929. int btrfs_block_rsv_check(struct btrfs_root *root,
  4930. struct btrfs_block_rsv *block_rsv, int min_factor)
  4931. {
  4932. u64 num_bytes = 0;
  4933. int ret = -ENOSPC;
  4934. if (!block_rsv)
  4935. return 0;
  4936. spin_lock(&block_rsv->lock);
  4937. num_bytes = div_factor(block_rsv->size, min_factor);
  4938. if (block_rsv->reserved >= num_bytes)
  4939. ret = 0;
  4940. spin_unlock(&block_rsv->lock);
  4941. return ret;
  4942. }
  4943. int btrfs_block_rsv_refill(struct btrfs_root *root,
  4944. struct btrfs_block_rsv *block_rsv, u64 min_reserved,
  4945. enum btrfs_reserve_flush_enum flush)
  4946. {
  4947. u64 num_bytes = 0;
  4948. int ret = -ENOSPC;
  4949. if (!block_rsv)
  4950. return 0;
  4951. spin_lock(&block_rsv->lock);
  4952. num_bytes = min_reserved;
  4953. if (block_rsv->reserved >= num_bytes)
  4954. ret = 0;
  4955. else
  4956. num_bytes -= block_rsv->reserved;
  4957. spin_unlock(&block_rsv->lock);
  4958. if (!ret)
  4959. return 0;
  4960. ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
  4961. if (!ret) {
  4962. block_rsv_add_bytes(block_rsv, num_bytes, 0);
  4963. return 0;
  4964. }
  4965. return ret;
  4966. }
  4967. void btrfs_block_rsv_release(struct btrfs_root *root,
  4968. struct btrfs_block_rsv *block_rsv,
  4969. u64 num_bytes)
  4970. {
  4971. struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
  4972. if (global_rsv == block_rsv ||
  4973. block_rsv->space_info != global_rsv->space_info)
  4974. global_rsv = NULL;
  4975. block_rsv_release_bytes(root->fs_info, block_rsv, global_rsv,
  4976. num_bytes);
  4977. }
  4978. static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
  4979. {
  4980. struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
  4981. struct btrfs_space_info *sinfo = block_rsv->space_info;
  4982. u64 num_bytes;
  4983. /*
  4984. * The global block rsv is based on the size of the extent tree, the
  4985. * checksum tree and the root tree. If the fs is empty we want to set
  4986. * it to a minimal amount for safety.
  4987. */
  4988. num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
  4989. btrfs_root_used(&fs_info->csum_root->root_item) +
  4990. btrfs_root_used(&fs_info->tree_root->root_item);
  4991. num_bytes = max_t(u64, num_bytes, SZ_16M);
  4992. spin_lock(&sinfo->lock);
  4993. spin_lock(&block_rsv->lock);
  4994. block_rsv->size = min_t(u64, num_bytes, SZ_512M);
  4995. if (block_rsv->reserved < block_rsv->size) {
  4996. num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
  4997. sinfo->bytes_reserved + sinfo->bytes_readonly +
  4998. sinfo->bytes_may_use;
  4999. if (sinfo->total_bytes > num_bytes) {
  5000. num_bytes = sinfo->total_bytes - num_bytes;
  5001. num_bytes = min(num_bytes,
  5002. block_rsv->size - block_rsv->reserved);
  5003. block_rsv->reserved += num_bytes;
  5004. sinfo->bytes_may_use += num_bytes;
  5005. trace_btrfs_space_reservation(fs_info, "space_info",
  5006. sinfo->flags, num_bytes,
  5007. 1);
  5008. }
  5009. } else if (block_rsv->reserved > block_rsv->size) {
  5010. num_bytes = block_rsv->reserved - block_rsv->size;
  5011. sinfo->bytes_may_use -= num_bytes;
  5012. trace_btrfs_space_reservation(fs_info, "space_info",
  5013. sinfo->flags, num_bytes, 0);
  5014. block_rsv->reserved = block_rsv->size;
  5015. }
  5016. if (block_rsv->reserved == block_rsv->size)
  5017. block_rsv->full = 1;
  5018. else
  5019. block_rsv->full = 0;
  5020. spin_unlock(&block_rsv->lock);
  5021. spin_unlock(&sinfo->lock);
  5022. }
  5023. static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
  5024. {
  5025. struct btrfs_space_info *space_info;
  5026. space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
  5027. fs_info->chunk_block_rsv.space_info = space_info;
  5028. space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
  5029. fs_info->global_block_rsv.space_info = space_info;
  5030. fs_info->delalloc_block_rsv.space_info = space_info;
  5031. fs_info->trans_block_rsv.space_info = space_info;
  5032. fs_info->empty_block_rsv.space_info = space_info;
  5033. fs_info->delayed_block_rsv.space_info = space_info;
  5034. fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
  5035. fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
  5036. fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
  5037. fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
  5038. if (fs_info->quota_root)
  5039. fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
  5040. fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
  5041. update_global_block_rsv(fs_info);
  5042. }
  5043. static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
  5044. {
  5045. block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
  5046. (u64)-1);
  5047. WARN_ON(fs_info->delalloc_block_rsv.size > 0);
  5048. WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
  5049. WARN_ON(fs_info->trans_block_rsv.size > 0);
  5050. WARN_ON(fs_info->trans_block_rsv.reserved > 0);
  5051. WARN_ON(fs_info->chunk_block_rsv.size > 0);
  5052. WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
  5053. WARN_ON(fs_info->delayed_block_rsv.size > 0);
  5054. WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
  5055. }
  5056. void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
  5057. struct btrfs_root *root)
  5058. {
  5059. if (!trans->block_rsv)
  5060. return;
  5061. if (!trans->bytes_reserved)
  5062. return;
  5063. trace_btrfs_space_reservation(root->fs_info, "transaction",
  5064. trans->transid, trans->bytes_reserved, 0);
  5065. btrfs_block_rsv_release(root, trans->block_rsv, trans->bytes_reserved);
  5066. trans->bytes_reserved = 0;
  5067. }
  5068. /*
  5069. * To be called after all the new block groups attached to the transaction
  5070. * handle have been created (btrfs_create_pending_block_groups()).
  5071. */
  5072. void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
  5073. {
  5074. struct btrfs_fs_info *fs_info = trans->fs_info;
  5075. if (!trans->chunk_bytes_reserved)
  5076. return;
  5077. WARN_ON_ONCE(!list_empty(&trans->new_bgs));
  5078. block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
  5079. trans->chunk_bytes_reserved);
  5080. trans->chunk_bytes_reserved = 0;
  5081. }
  5082. /* Can only return 0 or -ENOSPC */
  5083. int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
  5084. struct inode *inode)
  5085. {
  5086. struct btrfs_root *root = BTRFS_I(inode)->root;
  5087. /*
  5088. * We always use trans->block_rsv here as we will have reserved space
  5089. * for our orphan when starting the transaction, using get_block_rsv()
  5090. * here will sometimes make us choose the wrong block rsv as we could be
  5091. * doing a reloc inode for a non refcounted root.
  5092. */
  5093. struct btrfs_block_rsv *src_rsv = trans->block_rsv;
  5094. struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
  5095. /*
  5096. * We need to hold space in order to delete our orphan item once we've
  5097. * added it, so this takes the reservation so we can release it later
  5098. * when we are truly done with the orphan item.
  5099. */
  5100. u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
  5101. trace_btrfs_space_reservation(root->fs_info, "orphan",
  5102. btrfs_ino(inode), num_bytes, 1);
  5103. return btrfs_block_rsv_migrate(src_rsv, dst_rsv, num_bytes, 1);
  5104. }
  5105. void btrfs_orphan_release_metadata(struct inode *inode)
  5106. {
  5107. struct btrfs_root *root = BTRFS_I(inode)->root;
  5108. u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
  5109. trace_btrfs_space_reservation(root->fs_info, "orphan",
  5110. btrfs_ino(inode), num_bytes, 0);
  5111. btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
  5112. }
  5113. /*
  5114. * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
  5115. * root: the root of the parent directory
  5116. * rsv: block reservation
  5117. * items: the number of items that we need do reservation
  5118. * qgroup_reserved: used to return the reserved size in qgroup
  5119. *
  5120. * This function is used to reserve the space for snapshot/subvolume
  5121. * creation and deletion. Those operations are different with the
  5122. * common file/directory operations, they change two fs/file trees
  5123. * and root tree, the number of items that the qgroup reserves is
  5124. * different with the free space reservation. So we can not use
  5125. * the space reservation mechanism in start_transaction().
  5126. */
  5127. int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
  5128. struct btrfs_block_rsv *rsv,
  5129. int items,
  5130. u64 *qgroup_reserved,
  5131. bool use_global_rsv)
  5132. {
  5133. u64 num_bytes;
  5134. int ret;
  5135. struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
  5136. if (test_bit(BTRFS_FS_QUOTA_ENABLED, &root->fs_info->flags)) {
  5137. /* One for parent inode, two for dir entries */
  5138. num_bytes = 3 * root->nodesize;
  5139. ret = btrfs_qgroup_reserve_meta(root, num_bytes);
  5140. if (ret)
  5141. return ret;
  5142. } else {
  5143. num_bytes = 0;
  5144. }
  5145. *qgroup_reserved = num_bytes;
  5146. num_bytes = btrfs_calc_trans_metadata_size(root, items);
  5147. rsv->space_info = __find_space_info(root->fs_info,
  5148. BTRFS_BLOCK_GROUP_METADATA);
  5149. ret = btrfs_block_rsv_add(root, rsv, num_bytes,
  5150. BTRFS_RESERVE_FLUSH_ALL);
  5151. if (ret == -ENOSPC && use_global_rsv)
  5152. ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, 1);
  5153. if (ret && *qgroup_reserved)
  5154. btrfs_qgroup_free_meta(root, *qgroup_reserved);
  5155. return ret;
  5156. }
  5157. void btrfs_subvolume_release_metadata(struct btrfs_root *root,
  5158. struct btrfs_block_rsv *rsv,
  5159. u64 qgroup_reserved)
  5160. {
  5161. btrfs_block_rsv_release(root, rsv, (u64)-1);
  5162. }
  5163. /**
  5164. * drop_outstanding_extent - drop an outstanding extent
  5165. * @inode: the inode we're dropping the extent for
  5166. * @num_bytes: the number of bytes we're releasing.
  5167. *
  5168. * This is called when we are freeing up an outstanding extent, either called
  5169. * after an error or after an extent is written. This will return the number of
  5170. * reserved extents that need to be freed. This must be called with
  5171. * BTRFS_I(inode)->lock held.
  5172. */
  5173. static unsigned drop_outstanding_extent(struct inode *inode, u64 num_bytes)
  5174. {
  5175. unsigned drop_inode_space = 0;
  5176. unsigned dropped_extents = 0;
  5177. unsigned num_extents = 0;
  5178. num_extents = (unsigned)div64_u64(num_bytes +
  5179. BTRFS_MAX_EXTENT_SIZE - 1,
  5180. BTRFS_MAX_EXTENT_SIZE);
  5181. ASSERT(num_extents);
  5182. ASSERT(BTRFS_I(inode)->outstanding_extents >= num_extents);
  5183. BTRFS_I(inode)->outstanding_extents -= num_extents;
  5184. if (BTRFS_I(inode)->outstanding_extents == 0 &&
  5185. test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
  5186. &BTRFS_I(inode)->runtime_flags))
  5187. drop_inode_space = 1;
  5188. /*
  5189. * If we have more or the same amount of outstanding extents than we have
  5190. * reserved then we need to leave the reserved extents count alone.
  5191. */
  5192. if (BTRFS_I(inode)->outstanding_extents >=
  5193. BTRFS_I(inode)->reserved_extents)
  5194. return drop_inode_space;
  5195. dropped_extents = BTRFS_I(inode)->reserved_extents -
  5196. BTRFS_I(inode)->outstanding_extents;
  5197. BTRFS_I(inode)->reserved_extents -= dropped_extents;
  5198. return dropped_extents + drop_inode_space;
  5199. }
  5200. /**
  5201. * calc_csum_metadata_size - return the amount of metadata space that must be
  5202. * reserved/freed for the given bytes.
  5203. * @inode: the inode we're manipulating
  5204. * @num_bytes: the number of bytes in question
  5205. * @reserve: 1 if we are reserving space, 0 if we are freeing space
  5206. *
  5207. * This adjusts the number of csum_bytes in the inode and then returns the
  5208. * correct amount of metadata that must either be reserved or freed. We
  5209. * calculate how many checksums we can fit into one leaf and then divide the
  5210. * number of bytes that will need to be checksumed by this value to figure out
  5211. * how many checksums will be required. If we are adding bytes then the number
  5212. * may go up and we will return the number of additional bytes that must be
  5213. * reserved. If it is going down we will return the number of bytes that must
  5214. * be freed.
  5215. *
  5216. * This must be called with BTRFS_I(inode)->lock held.
  5217. */
  5218. static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
  5219. int reserve)
  5220. {
  5221. struct btrfs_root *root = BTRFS_I(inode)->root;
  5222. u64 old_csums, num_csums;
  5223. if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
  5224. BTRFS_I(inode)->csum_bytes == 0)
  5225. return 0;
  5226. old_csums = btrfs_csum_bytes_to_leaves(root, BTRFS_I(inode)->csum_bytes);
  5227. if (reserve)
  5228. BTRFS_I(inode)->csum_bytes += num_bytes;
  5229. else
  5230. BTRFS_I(inode)->csum_bytes -= num_bytes;
  5231. num_csums = btrfs_csum_bytes_to_leaves(root, BTRFS_I(inode)->csum_bytes);
  5232. /* No change, no need to reserve more */
  5233. if (old_csums == num_csums)
  5234. return 0;
  5235. if (reserve)
  5236. return btrfs_calc_trans_metadata_size(root,
  5237. num_csums - old_csums);
  5238. return btrfs_calc_trans_metadata_size(root, old_csums - num_csums);
  5239. }
  5240. int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
  5241. {
  5242. struct btrfs_root *root = BTRFS_I(inode)->root;
  5243. struct btrfs_block_rsv *block_rsv = &root->fs_info->delalloc_block_rsv;
  5244. u64 to_reserve = 0;
  5245. u64 csum_bytes;
  5246. unsigned nr_extents = 0;
  5247. enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
  5248. int ret = 0;
  5249. bool delalloc_lock = true;
  5250. u64 to_free = 0;
  5251. unsigned dropped;
  5252. bool release_extra = false;
  5253. /* If we are a free space inode we need to not flush since we will be in
  5254. * the middle of a transaction commit. We also don't need the delalloc
  5255. * mutex since we won't race with anybody. We need this mostly to make
  5256. * lockdep shut its filthy mouth.
  5257. *
  5258. * If we have a transaction open (can happen if we call truncate_block
  5259. * from truncate), then we need FLUSH_LIMIT so we don't deadlock.
  5260. */
  5261. if (btrfs_is_free_space_inode(inode)) {
  5262. flush = BTRFS_RESERVE_NO_FLUSH;
  5263. delalloc_lock = false;
  5264. } else if (current->journal_info) {
  5265. flush = BTRFS_RESERVE_FLUSH_LIMIT;
  5266. }
  5267. if (flush != BTRFS_RESERVE_NO_FLUSH &&
  5268. btrfs_transaction_in_commit(root->fs_info))
  5269. schedule_timeout(1);
  5270. if (delalloc_lock)
  5271. mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
  5272. num_bytes = ALIGN(num_bytes, root->sectorsize);
  5273. spin_lock(&BTRFS_I(inode)->lock);
  5274. nr_extents = (unsigned)div64_u64(num_bytes +
  5275. BTRFS_MAX_EXTENT_SIZE - 1,
  5276. BTRFS_MAX_EXTENT_SIZE);
  5277. BTRFS_I(inode)->outstanding_extents += nr_extents;
  5278. nr_extents = 0;
  5279. if (BTRFS_I(inode)->outstanding_extents >
  5280. BTRFS_I(inode)->reserved_extents)
  5281. nr_extents += BTRFS_I(inode)->outstanding_extents -
  5282. BTRFS_I(inode)->reserved_extents;
  5283. /* We always want to reserve a slot for updating the inode. */
  5284. to_reserve = btrfs_calc_trans_metadata_size(root, nr_extents + 1);
  5285. to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
  5286. csum_bytes = BTRFS_I(inode)->csum_bytes;
  5287. spin_unlock(&BTRFS_I(inode)->lock);
  5288. if (test_bit(BTRFS_FS_QUOTA_ENABLED, &root->fs_info->flags)) {
  5289. ret = btrfs_qgroup_reserve_meta(root,
  5290. nr_extents * root->nodesize);
  5291. if (ret)
  5292. goto out_fail;
  5293. }
  5294. ret = btrfs_block_rsv_add(root, block_rsv, to_reserve, flush);
  5295. if (unlikely(ret)) {
  5296. btrfs_qgroup_free_meta(root, nr_extents * root->nodesize);
  5297. goto out_fail;
  5298. }
  5299. spin_lock(&BTRFS_I(inode)->lock);
  5300. if (test_and_set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
  5301. &BTRFS_I(inode)->runtime_flags)) {
  5302. to_reserve -= btrfs_calc_trans_metadata_size(root, 1);
  5303. release_extra = true;
  5304. }
  5305. BTRFS_I(inode)->reserved_extents += nr_extents;
  5306. spin_unlock(&BTRFS_I(inode)->lock);
  5307. if (delalloc_lock)
  5308. mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
  5309. if (to_reserve)
  5310. trace_btrfs_space_reservation(root->fs_info, "delalloc",
  5311. btrfs_ino(inode), to_reserve, 1);
  5312. if (release_extra)
  5313. btrfs_block_rsv_release(root, block_rsv,
  5314. btrfs_calc_trans_metadata_size(root,
  5315. 1));
  5316. return 0;
  5317. out_fail:
  5318. spin_lock(&BTRFS_I(inode)->lock);
  5319. dropped = drop_outstanding_extent(inode, num_bytes);
  5320. /*
  5321. * If the inodes csum_bytes is the same as the original
  5322. * csum_bytes then we know we haven't raced with any free()ers
  5323. * so we can just reduce our inodes csum bytes and carry on.
  5324. */
  5325. if (BTRFS_I(inode)->csum_bytes == csum_bytes) {
  5326. calc_csum_metadata_size(inode, num_bytes, 0);
  5327. } else {
  5328. u64 orig_csum_bytes = BTRFS_I(inode)->csum_bytes;
  5329. u64 bytes;
  5330. /*
  5331. * This is tricky, but first we need to figure out how much we
  5332. * freed from any free-ers that occurred during this
  5333. * reservation, so we reset ->csum_bytes to the csum_bytes
  5334. * before we dropped our lock, and then call the free for the
  5335. * number of bytes that were freed while we were trying our
  5336. * reservation.
  5337. */
  5338. bytes = csum_bytes - BTRFS_I(inode)->csum_bytes;
  5339. BTRFS_I(inode)->csum_bytes = csum_bytes;
  5340. to_free = calc_csum_metadata_size(inode, bytes, 0);
  5341. /*
  5342. * Now we need to see how much we would have freed had we not
  5343. * been making this reservation and our ->csum_bytes were not
  5344. * artificially inflated.
  5345. */
  5346. BTRFS_I(inode)->csum_bytes = csum_bytes - num_bytes;
  5347. bytes = csum_bytes - orig_csum_bytes;
  5348. bytes = calc_csum_metadata_size(inode, bytes, 0);
  5349. /*
  5350. * Now reset ->csum_bytes to what it should be. If bytes is
  5351. * more than to_free then we would have freed more space had we
  5352. * not had an artificially high ->csum_bytes, so we need to free
  5353. * the remainder. If bytes is the same or less then we don't
  5354. * need to do anything, the other free-ers did the correct
  5355. * thing.
  5356. */
  5357. BTRFS_I(inode)->csum_bytes = orig_csum_bytes - num_bytes;
  5358. if (bytes > to_free)
  5359. to_free = bytes - to_free;
  5360. else
  5361. to_free = 0;
  5362. }
  5363. spin_unlock(&BTRFS_I(inode)->lock);
  5364. if (dropped)
  5365. to_free += btrfs_calc_trans_metadata_size(root, dropped);
  5366. if (to_free) {
  5367. btrfs_block_rsv_release(root, block_rsv, to_free);
  5368. trace_btrfs_space_reservation(root->fs_info, "delalloc",
  5369. btrfs_ino(inode), to_free, 0);
  5370. }
  5371. if (delalloc_lock)
  5372. mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
  5373. return ret;
  5374. }
  5375. /**
  5376. * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
  5377. * @inode: the inode to release the reservation for
  5378. * @num_bytes: the number of bytes we're releasing
  5379. *
  5380. * This will release the metadata reservation for an inode. This can be called
  5381. * once we complete IO for a given set of bytes to release their metadata
  5382. * reservations.
  5383. */
  5384. void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
  5385. {
  5386. struct btrfs_root *root = BTRFS_I(inode)->root;
  5387. u64 to_free = 0;
  5388. unsigned dropped;
  5389. num_bytes = ALIGN(num_bytes, root->sectorsize);
  5390. spin_lock(&BTRFS_I(inode)->lock);
  5391. dropped = drop_outstanding_extent(inode, num_bytes);
  5392. if (num_bytes)
  5393. to_free = calc_csum_metadata_size(inode, num_bytes, 0);
  5394. spin_unlock(&BTRFS_I(inode)->lock);
  5395. if (dropped > 0)
  5396. to_free += btrfs_calc_trans_metadata_size(root, dropped);
  5397. if (btrfs_is_testing(root->fs_info))
  5398. return;
  5399. trace_btrfs_space_reservation(root->fs_info, "delalloc",
  5400. btrfs_ino(inode), to_free, 0);
  5401. btrfs_block_rsv_release(root, &root->fs_info->delalloc_block_rsv,
  5402. to_free);
  5403. }
  5404. /**
  5405. * btrfs_delalloc_reserve_space - reserve data and metadata space for
  5406. * delalloc
  5407. * @inode: inode we're writing to
  5408. * @start: start range we are writing to
  5409. * @len: how long the range we are writing to
  5410. *
  5411. * This will do the following things
  5412. *
  5413. * o reserve space in data space info for num bytes
  5414. * and reserve precious corresponding qgroup space
  5415. * (Done in check_data_free_space)
  5416. *
  5417. * o reserve space for metadata space, based on the number of outstanding
  5418. * extents and how much csums will be needed
  5419. * also reserve metadata space in a per root over-reserve method.
  5420. * o add to the inodes->delalloc_bytes
  5421. * o add it to the fs_info's delalloc inodes list.
  5422. * (Above 3 all done in delalloc_reserve_metadata)
  5423. *
  5424. * Return 0 for success
  5425. * Return <0 for error(-ENOSPC or -EQUOT)
  5426. */
  5427. int btrfs_delalloc_reserve_space(struct inode *inode, u64 start, u64 len)
  5428. {
  5429. int ret;
  5430. ret = btrfs_check_data_free_space(inode, start, len);
  5431. if (ret < 0)
  5432. return ret;
  5433. ret = btrfs_delalloc_reserve_metadata(inode, len);
  5434. if (ret < 0)
  5435. btrfs_free_reserved_data_space(inode, start, len);
  5436. return ret;
  5437. }
  5438. /**
  5439. * btrfs_delalloc_release_space - release data and metadata space for delalloc
  5440. * @inode: inode we're releasing space for
  5441. * @start: start position of the space already reserved
  5442. * @len: the len of the space already reserved
  5443. *
  5444. * This must be matched with a call to btrfs_delalloc_reserve_space. This is
  5445. * called in the case that we don't need the metadata AND data reservations
  5446. * anymore. So if there is an error or we insert an inline extent.
  5447. *
  5448. * This function will release the metadata space that was not used and will
  5449. * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
  5450. * list if there are no delalloc bytes left.
  5451. * Also it will handle the qgroup reserved space.
  5452. */
  5453. void btrfs_delalloc_release_space(struct inode *inode, u64 start, u64 len)
  5454. {
  5455. btrfs_delalloc_release_metadata(inode, len);
  5456. btrfs_free_reserved_data_space(inode, start, len);
  5457. }
  5458. static int update_block_group(struct btrfs_trans_handle *trans,
  5459. struct btrfs_root *root, u64 bytenr,
  5460. u64 num_bytes, int alloc)
  5461. {
  5462. struct btrfs_block_group_cache *cache = NULL;
  5463. struct btrfs_fs_info *info = root->fs_info;
  5464. u64 total = num_bytes;
  5465. u64 old_val;
  5466. u64 byte_in_group;
  5467. int factor;
  5468. /* block accounting for super block */
  5469. spin_lock(&info->delalloc_root_lock);
  5470. old_val = btrfs_super_bytes_used(info->super_copy);
  5471. if (alloc)
  5472. old_val += num_bytes;
  5473. else
  5474. old_val -= num_bytes;
  5475. btrfs_set_super_bytes_used(info->super_copy, old_val);
  5476. spin_unlock(&info->delalloc_root_lock);
  5477. while (total) {
  5478. cache = btrfs_lookup_block_group(info, bytenr);
  5479. if (!cache)
  5480. return -ENOENT;
  5481. if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
  5482. BTRFS_BLOCK_GROUP_RAID1 |
  5483. BTRFS_BLOCK_GROUP_RAID10))
  5484. factor = 2;
  5485. else
  5486. factor = 1;
  5487. /*
  5488. * If this block group has free space cache written out, we
  5489. * need to make sure to load it if we are removing space. This
  5490. * is because we need the unpinning stage to actually add the
  5491. * space back to the block group, otherwise we will leak space.
  5492. */
  5493. if (!alloc && cache->cached == BTRFS_CACHE_NO)
  5494. cache_block_group(cache, 1);
  5495. byte_in_group = bytenr - cache->key.objectid;
  5496. WARN_ON(byte_in_group > cache->key.offset);
  5497. spin_lock(&cache->space_info->lock);
  5498. spin_lock(&cache->lock);
  5499. if (btrfs_test_opt(root->fs_info, SPACE_CACHE) &&
  5500. cache->disk_cache_state < BTRFS_DC_CLEAR)
  5501. cache->disk_cache_state = BTRFS_DC_CLEAR;
  5502. old_val = btrfs_block_group_used(&cache->item);
  5503. num_bytes = min(total, cache->key.offset - byte_in_group);
  5504. if (alloc) {
  5505. old_val += num_bytes;
  5506. btrfs_set_block_group_used(&cache->item, old_val);
  5507. cache->reserved -= num_bytes;
  5508. cache->space_info->bytes_reserved -= num_bytes;
  5509. cache->space_info->bytes_used += num_bytes;
  5510. cache->space_info->disk_used += num_bytes * factor;
  5511. spin_unlock(&cache->lock);
  5512. spin_unlock(&cache->space_info->lock);
  5513. } else {
  5514. old_val -= num_bytes;
  5515. btrfs_set_block_group_used(&cache->item, old_val);
  5516. cache->pinned += num_bytes;
  5517. cache->space_info->bytes_pinned += num_bytes;
  5518. cache->space_info->bytes_used -= num_bytes;
  5519. cache->space_info->disk_used -= num_bytes * factor;
  5520. spin_unlock(&cache->lock);
  5521. spin_unlock(&cache->space_info->lock);
  5522. trace_btrfs_space_reservation(root->fs_info, "pinned",
  5523. cache->space_info->flags,
  5524. num_bytes, 1);
  5525. set_extent_dirty(info->pinned_extents,
  5526. bytenr, bytenr + num_bytes - 1,
  5527. GFP_NOFS | __GFP_NOFAIL);
  5528. }
  5529. spin_lock(&trans->transaction->dirty_bgs_lock);
  5530. if (list_empty(&cache->dirty_list)) {
  5531. list_add_tail(&cache->dirty_list,
  5532. &trans->transaction->dirty_bgs);
  5533. trans->transaction->num_dirty_bgs++;
  5534. btrfs_get_block_group(cache);
  5535. }
  5536. spin_unlock(&trans->transaction->dirty_bgs_lock);
  5537. /*
  5538. * No longer have used bytes in this block group, queue it for
  5539. * deletion. We do this after adding the block group to the
  5540. * dirty list to avoid races between cleaner kthread and space
  5541. * cache writeout.
  5542. */
  5543. if (!alloc && old_val == 0) {
  5544. spin_lock(&info->unused_bgs_lock);
  5545. if (list_empty(&cache->bg_list)) {
  5546. btrfs_get_block_group(cache);
  5547. list_add_tail(&cache->bg_list,
  5548. &info->unused_bgs);
  5549. }
  5550. spin_unlock(&info->unused_bgs_lock);
  5551. }
  5552. btrfs_put_block_group(cache);
  5553. total -= num_bytes;
  5554. bytenr += num_bytes;
  5555. }
  5556. return 0;
  5557. }
  5558. static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
  5559. {
  5560. struct btrfs_block_group_cache *cache;
  5561. u64 bytenr;
  5562. spin_lock(&root->fs_info->block_group_cache_lock);
  5563. bytenr = root->fs_info->first_logical_byte;
  5564. spin_unlock(&root->fs_info->block_group_cache_lock);
  5565. if (bytenr < (u64)-1)
  5566. return bytenr;
  5567. cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
  5568. if (!cache)
  5569. return 0;
  5570. bytenr = cache->key.objectid;
  5571. btrfs_put_block_group(cache);
  5572. return bytenr;
  5573. }
  5574. static int pin_down_extent(struct btrfs_root *root,
  5575. struct btrfs_block_group_cache *cache,
  5576. u64 bytenr, u64 num_bytes, int reserved)
  5577. {
  5578. spin_lock(&cache->space_info->lock);
  5579. spin_lock(&cache->lock);
  5580. cache->pinned += num_bytes;
  5581. cache->space_info->bytes_pinned += num_bytes;
  5582. if (reserved) {
  5583. cache->reserved -= num_bytes;
  5584. cache->space_info->bytes_reserved -= num_bytes;
  5585. }
  5586. spin_unlock(&cache->lock);
  5587. spin_unlock(&cache->space_info->lock);
  5588. trace_btrfs_space_reservation(root->fs_info, "pinned",
  5589. cache->space_info->flags, num_bytes, 1);
  5590. set_extent_dirty(root->fs_info->pinned_extents, bytenr,
  5591. bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
  5592. return 0;
  5593. }
  5594. /*
  5595. * this function must be called within transaction
  5596. */
  5597. int btrfs_pin_extent(struct btrfs_root *root,
  5598. u64 bytenr, u64 num_bytes, int reserved)
  5599. {
  5600. struct btrfs_block_group_cache *cache;
  5601. cache = btrfs_lookup_block_group(root->fs_info, bytenr);
  5602. BUG_ON(!cache); /* Logic error */
  5603. pin_down_extent(root, cache, bytenr, num_bytes, reserved);
  5604. btrfs_put_block_group(cache);
  5605. return 0;
  5606. }
  5607. /*
  5608. * this function must be called within transaction
  5609. */
  5610. int btrfs_pin_extent_for_log_replay(struct btrfs_root *root,
  5611. u64 bytenr, u64 num_bytes)
  5612. {
  5613. struct btrfs_block_group_cache *cache;
  5614. int ret;
  5615. cache = btrfs_lookup_block_group(root->fs_info, bytenr);
  5616. if (!cache)
  5617. return -EINVAL;
  5618. /*
  5619. * pull in the free space cache (if any) so that our pin
  5620. * removes the free space from the cache. We have load_only set
  5621. * to one because the slow code to read in the free extents does check
  5622. * the pinned extents.
  5623. */
  5624. cache_block_group(cache, 1);
  5625. pin_down_extent(root, cache, bytenr, num_bytes, 0);
  5626. /* remove us from the free space cache (if we're there at all) */
  5627. ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
  5628. btrfs_put_block_group(cache);
  5629. return ret;
  5630. }
  5631. static int __exclude_logged_extent(struct btrfs_root *root, u64 start, u64 num_bytes)
  5632. {
  5633. int ret;
  5634. struct btrfs_block_group_cache *block_group;
  5635. struct btrfs_caching_control *caching_ctl;
  5636. block_group = btrfs_lookup_block_group(root->fs_info, start);
  5637. if (!block_group)
  5638. return -EINVAL;
  5639. cache_block_group(block_group, 0);
  5640. caching_ctl = get_caching_control(block_group);
  5641. if (!caching_ctl) {
  5642. /* Logic error */
  5643. BUG_ON(!block_group_cache_done(block_group));
  5644. ret = btrfs_remove_free_space(block_group, start, num_bytes);
  5645. } else {
  5646. mutex_lock(&caching_ctl->mutex);
  5647. if (start >= caching_ctl->progress) {
  5648. ret = add_excluded_extent(root, start, num_bytes);
  5649. } else if (start + num_bytes <= caching_ctl->progress) {
  5650. ret = btrfs_remove_free_space(block_group,
  5651. start, num_bytes);
  5652. } else {
  5653. num_bytes = caching_ctl->progress - start;
  5654. ret = btrfs_remove_free_space(block_group,
  5655. start, num_bytes);
  5656. if (ret)
  5657. goto out_lock;
  5658. num_bytes = (start + num_bytes) -
  5659. caching_ctl->progress;
  5660. start = caching_ctl->progress;
  5661. ret = add_excluded_extent(root, start, num_bytes);
  5662. }
  5663. out_lock:
  5664. mutex_unlock(&caching_ctl->mutex);
  5665. put_caching_control(caching_ctl);
  5666. }
  5667. btrfs_put_block_group(block_group);
  5668. return ret;
  5669. }
  5670. int btrfs_exclude_logged_extents(struct btrfs_root *log,
  5671. struct extent_buffer *eb)
  5672. {
  5673. struct btrfs_file_extent_item *item;
  5674. struct btrfs_key key;
  5675. int found_type;
  5676. int i;
  5677. if (!btrfs_fs_incompat(log->fs_info, MIXED_GROUPS))
  5678. return 0;
  5679. for (i = 0; i < btrfs_header_nritems(eb); i++) {
  5680. btrfs_item_key_to_cpu(eb, &key, i);
  5681. if (key.type != BTRFS_EXTENT_DATA_KEY)
  5682. continue;
  5683. item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
  5684. found_type = btrfs_file_extent_type(eb, item);
  5685. if (found_type == BTRFS_FILE_EXTENT_INLINE)
  5686. continue;
  5687. if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
  5688. continue;
  5689. key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
  5690. key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
  5691. __exclude_logged_extent(log, key.objectid, key.offset);
  5692. }
  5693. return 0;
  5694. }
  5695. static void
  5696. btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
  5697. {
  5698. atomic_inc(&bg->reservations);
  5699. }
  5700. void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
  5701. const u64 start)
  5702. {
  5703. struct btrfs_block_group_cache *bg;
  5704. bg = btrfs_lookup_block_group(fs_info, start);
  5705. ASSERT(bg);
  5706. if (atomic_dec_and_test(&bg->reservations))
  5707. wake_up_atomic_t(&bg->reservations);
  5708. btrfs_put_block_group(bg);
  5709. }
  5710. static int btrfs_wait_bg_reservations_atomic_t(atomic_t *a)
  5711. {
  5712. schedule();
  5713. return 0;
  5714. }
  5715. void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
  5716. {
  5717. struct btrfs_space_info *space_info = bg->space_info;
  5718. ASSERT(bg->ro);
  5719. if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
  5720. return;
  5721. /*
  5722. * Our block group is read only but before we set it to read only,
  5723. * some task might have had allocated an extent from it already, but it
  5724. * has not yet created a respective ordered extent (and added it to a
  5725. * root's list of ordered extents).
  5726. * Therefore wait for any task currently allocating extents, since the
  5727. * block group's reservations counter is incremented while a read lock
  5728. * on the groups' semaphore is held and decremented after releasing
  5729. * the read access on that semaphore and creating the ordered extent.
  5730. */
  5731. down_write(&space_info->groups_sem);
  5732. up_write(&space_info->groups_sem);
  5733. wait_on_atomic_t(&bg->reservations,
  5734. btrfs_wait_bg_reservations_atomic_t,
  5735. TASK_UNINTERRUPTIBLE);
  5736. }
  5737. /**
  5738. * btrfs_add_reserved_bytes - update the block_group and space info counters
  5739. * @cache: The cache we are manipulating
  5740. * @ram_bytes: The number of bytes of file content, and will be same to
  5741. * @num_bytes except for the compress path.
  5742. * @num_bytes: The number of bytes in question
  5743. * @delalloc: The blocks are allocated for the delalloc write
  5744. *
  5745. * This is called by the allocator when it reserves space. Metadata
  5746. * reservations should be called with RESERVE_ALLOC so we do the proper
  5747. * ENOSPC accounting. For data we handle the reservation through clearing the
  5748. * delalloc bits in the io_tree. We have to do this since we could end up
  5749. * allocating less disk space for the amount of data we have reserved in the
  5750. * case of compression.
  5751. *
  5752. * If this is a reservation and the block group has become read only we cannot
  5753. * make the reservation and return -EAGAIN, otherwise this function always
  5754. * succeeds.
  5755. */
  5756. static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
  5757. u64 ram_bytes, u64 num_bytes, int delalloc)
  5758. {
  5759. struct btrfs_space_info *space_info = cache->space_info;
  5760. int ret = 0;
  5761. spin_lock(&space_info->lock);
  5762. spin_lock(&cache->lock);
  5763. if (cache->ro) {
  5764. ret = -EAGAIN;
  5765. } else {
  5766. cache->reserved += num_bytes;
  5767. space_info->bytes_reserved += num_bytes;
  5768. trace_btrfs_space_reservation(cache->fs_info,
  5769. "space_info", space_info->flags,
  5770. ram_bytes, 0);
  5771. space_info->bytes_may_use -= ram_bytes;
  5772. if (delalloc)
  5773. cache->delalloc_bytes += num_bytes;
  5774. }
  5775. spin_unlock(&cache->lock);
  5776. spin_unlock(&space_info->lock);
  5777. return ret;
  5778. }
  5779. /**
  5780. * btrfs_free_reserved_bytes - update the block_group and space info counters
  5781. * @cache: The cache we are manipulating
  5782. * @num_bytes: The number of bytes in question
  5783. * @delalloc: The blocks are allocated for the delalloc write
  5784. *
  5785. * This is called by somebody who is freeing space that was never actually used
  5786. * on disk. For example if you reserve some space for a new leaf in transaction
  5787. * A and before transaction A commits you free that leaf, you call this with
  5788. * reserve set to 0 in order to clear the reservation.
  5789. */
  5790. static int btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
  5791. u64 num_bytes, int delalloc)
  5792. {
  5793. struct btrfs_space_info *space_info = cache->space_info;
  5794. int ret = 0;
  5795. spin_lock(&space_info->lock);
  5796. spin_lock(&cache->lock);
  5797. if (cache->ro)
  5798. space_info->bytes_readonly += num_bytes;
  5799. cache->reserved -= num_bytes;
  5800. space_info->bytes_reserved -= num_bytes;
  5801. if (delalloc)
  5802. cache->delalloc_bytes -= num_bytes;
  5803. spin_unlock(&cache->lock);
  5804. spin_unlock(&space_info->lock);
  5805. return ret;
  5806. }
  5807. void btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
  5808. struct btrfs_root *root)
  5809. {
  5810. struct btrfs_fs_info *fs_info = root->fs_info;
  5811. struct btrfs_caching_control *next;
  5812. struct btrfs_caching_control *caching_ctl;
  5813. struct btrfs_block_group_cache *cache;
  5814. down_write(&fs_info->commit_root_sem);
  5815. list_for_each_entry_safe(caching_ctl, next,
  5816. &fs_info->caching_block_groups, list) {
  5817. cache = caching_ctl->block_group;
  5818. if (block_group_cache_done(cache)) {
  5819. cache->last_byte_to_unpin = (u64)-1;
  5820. list_del_init(&caching_ctl->list);
  5821. put_caching_control(caching_ctl);
  5822. } else {
  5823. cache->last_byte_to_unpin = caching_ctl->progress;
  5824. }
  5825. }
  5826. if (fs_info->pinned_extents == &fs_info->freed_extents[0])
  5827. fs_info->pinned_extents = &fs_info->freed_extents[1];
  5828. else
  5829. fs_info->pinned_extents = &fs_info->freed_extents[0];
  5830. up_write(&fs_info->commit_root_sem);
  5831. update_global_block_rsv(fs_info);
  5832. }
  5833. /*
  5834. * Returns the free cluster for the given space info and sets empty_cluster to
  5835. * what it should be based on the mount options.
  5836. */
  5837. static struct btrfs_free_cluster *
  5838. fetch_cluster_info(struct btrfs_root *root, struct btrfs_space_info *space_info,
  5839. u64 *empty_cluster)
  5840. {
  5841. struct btrfs_free_cluster *ret = NULL;
  5842. bool ssd = btrfs_test_opt(root->fs_info, SSD);
  5843. *empty_cluster = 0;
  5844. if (btrfs_mixed_space_info(space_info))
  5845. return ret;
  5846. if (ssd)
  5847. *empty_cluster = SZ_2M;
  5848. if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
  5849. ret = &root->fs_info->meta_alloc_cluster;
  5850. if (!ssd)
  5851. *empty_cluster = SZ_64K;
  5852. } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) && ssd) {
  5853. ret = &root->fs_info->data_alloc_cluster;
  5854. }
  5855. return ret;
  5856. }
  5857. static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end,
  5858. const bool return_free_space)
  5859. {
  5860. struct btrfs_fs_info *fs_info = root->fs_info;
  5861. struct btrfs_block_group_cache *cache = NULL;
  5862. struct btrfs_space_info *space_info;
  5863. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  5864. struct btrfs_free_cluster *cluster = NULL;
  5865. u64 len;
  5866. u64 total_unpinned = 0;
  5867. u64 empty_cluster = 0;
  5868. bool readonly;
  5869. while (start <= end) {
  5870. readonly = false;
  5871. if (!cache ||
  5872. start >= cache->key.objectid + cache->key.offset) {
  5873. if (cache)
  5874. btrfs_put_block_group(cache);
  5875. total_unpinned = 0;
  5876. cache = btrfs_lookup_block_group(fs_info, start);
  5877. BUG_ON(!cache); /* Logic error */
  5878. cluster = fetch_cluster_info(root,
  5879. cache->space_info,
  5880. &empty_cluster);
  5881. empty_cluster <<= 1;
  5882. }
  5883. len = cache->key.objectid + cache->key.offset - start;
  5884. len = min(len, end + 1 - start);
  5885. if (start < cache->last_byte_to_unpin) {
  5886. len = min(len, cache->last_byte_to_unpin - start);
  5887. if (return_free_space)
  5888. btrfs_add_free_space(cache, start, len);
  5889. }
  5890. start += len;
  5891. total_unpinned += len;
  5892. space_info = cache->space_info;
  5893. /*
  5894. * If this space cluster has been marked as fragmented and we've
  5895. * unpinned enough in this block group to potentially allow a
  5896. * cluster to be created inside of it go ahead and clear the
  5897. * fragmented check.
  5898. */
  5899. if (cluster && cluster->fragmented &&
  5900. total_unpinned > empty_cluster) {
  5901. spin_lock(&cluster->lock);
  5902. cluster->fragmented = 0;
  5903. spin_unlock(&cluster->lock);
  5904. }
  5905. spin_lock(&space_info->lock);
  5906. spin_lock(&cache->lock);
  5907. cache->pinned -= len;
  5908. space_info->bytes_pinned -= len;
  5909. trace_btrfs_space_reservation(fs_info, "pinned",
  5910. space_info->flags, len, 0);
  5911. space_info->max_extent_size = 0;
  5912. percpu_counter_add(&space_info->total_bytes_pinned, -len);
  5913. if (cache->ro) {
  5914. space_info->bytes_readonly += len;
  5915. readonly = true;
  5916. }
  5917. spin_unlock(&cache->lock);
  5918. if (!readonly && return_free_space &&
  5919. global_rsv->space_info == space_info) {
  5920. u64 to_add = len;
  5921. WARN_ON(!return_free_space);
  5922. spin_lock(&global_rsv->lock);
  5923. if (!global_rsv->full) {
  5924. to_add = min(len, global_rsv->size -
  5925. global_rsv->reserved);
  5926. global_rsv->reserved += to_add;
  5927. space_info->bytes_may_use += to_add;
  5928. if (global_rsv->reserved >= global_rsv->size)
  5929. global_rsv->full = 1;
  5930. trace_btrfs_space_reservation(fs_info,
  5931. "space_info",
  5932. space_info->flags,
  5933. to_add, 1);
  5934. len -= to_add;
  5935. }
  5936. spin_unlock(&global_rsv->lock);
  5937. /* Add to any tickets we may have */
  5938. if (len)
  5939. space_info_add_new_bytes(fs_info, space_info,
  5940. len);
  5941. }
  5942. spin_unlock(&space_info->lock);
  5943. }
  5944. if (cache)
  5945. btrfs_put_block_group(cache);
  5946. return 0;
  5947. }
  5948. int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
  5949. struct btrfs_root *root)
  5950. {
  5951. struct btrfs_fs_info *fs_info = root->fs_info;
  5952. struct btrfs_block_group_cache *block_group, *tmp;
  5953. struct list_head *deleted_bgs;
  5954. struct extent_io_tree *unpin;
  5955. u64 start;
  5956. u64 end;
  5957. int ret;
  5958. if (fs_info->pinned_extents == &fs_info->freed_extents[0])
  5959. unpin = &fs_info->freed_extents[1];
  5960. else
  5961. unpin = &fs_info->freed_extents[0];
  5962. while (!trans->aborted) {
  5963. mutex_lock(&fs_info->unused_bg_unpin_mutex);
  5964. ret = find_first_extent_bit(unpin, 0, &start, &end,
  5965. EXTENT_DIRTY, NULL);
  5966. if (ret) {
  5967. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  5968. break;
  5969. }
  5970. if (btrfs_test_opt(root->fs_info, DISCARD))
  5971. ret = btrfs_discard_extent(root, start,
  5972. end + 1 - start, NULL);
  5973. clear_extent_dirty(unpin, start, end);
  5974. unpin_extent_range(root, start, end, true);
  5975. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  5976. cond_resched();
  5977. }
  5978. /*
  5979. * Transaction is finished. We don't need the lock anymore. We
  5980. * do need to clean up the block groups in case of a transaction
  5981. * abort.
  5982. */
  5983. deleted_bgs = &trans->transaction->deleted_bgs;
  5984. list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
  5985. u64 trimmed = 0;
  5986. ret = -EROFS;
  5987. if (!trans->aborted)
  5988. ret = btrfs_discard_extent(root,
  5989. block_group->key.objectid,
  5990. block_group->key.offset,
  5991. &trimmed);
  5992. list_del_init(&block_group->bg_list);
  5993. btrfs_put_block_group_trimming(block_group);
  5994. btrfs_put_block_group(block_group);
  5995. if (ret) {
  5996. const char *errstr = btrfs_decode_error(ret);
  5997. btrfs_warn(fs_info,
  5998. "Discard failed while removing blockgroup: errno=%d %s\n",
  5999. ret, errstr);
  6000. }
  6001. }
  6002. return 0;
  6003. }
  6004. static void add_pinned_bytes(struct btrfs_fs_info *fs_info, u64 num_bytes,
  6005. u64 owner, u64 root_objectid)
  6006. {
  6007. struct btrfs_space_info *space_info;
  6008. u64 flags;
  6009. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  6010. if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
  6011. flags = BTRFS_BLOCK_GROUP_SYSTEM;
  6012. else
  6013. flags = BTRFS_BLOCK_GROUP_METADATA;
  6014. } else {
  6015. flags = BTRFS_BLOCK_GROUP_DATA;
  6016. }
  6017. space_info = __find_space_info(fs_info, flags);
  6018. BUG_ON(!space_info); /* Logic bug */
  6019. percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
  6020. }
  6021. static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
  6022. struct btrfs_root *root,
  6023. struct btrfs_delayed_ref_node *node, u64 parent,
  6024. u64 root_objectid, u64 owner_objectid,
  6025. u64 owner_offset, int refs_to_drop,
  6026. struct btrfs_delayed_extent_op *extent_op)
  6027. {
  6028. struct btrfs_key key;
  6029. struct btrfs_path *path;
  6030. struct btrfs_fs_info *info = root->fs_info;
  6031. struct btrfs_root *extent_root = info->extent_root;
  6032. struct extent_buffer *leaf;
  6033. struct btrfs_extent_item *ei;
  6034. struct btrfs_extent_inline_ref *iref;
  6035. int ret;
  6036. int is_data;
  6037. int extent_slot = 0;
  6038. int found_extent = 0;
  6039. int num_to_del = 1;
  6040. u32 item_size;
  6041. u64 refs;
  6042. u64 bytenr = node->bytenr;
  6043. u64 num_bytes = node->num_bytes;
  6044. int last_ref = 0;
  6045. bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
  6046. SKINNY_METADATA);
  6047. path = btrfs_alloc_path();
  6048. if (!path)
  6049. return -ENOMEM;
  6050. path->reada = READA_FORWARD;
  6051. path->leave_spinning = 1;
  6052. is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
  6053. BUG_ON(!is_data && refs_to_drop != 1);
  6054. if (is_data)
  6055. skinny_metadata = 0;
  6056. ret = lookup_extent_backref(trans, extent_root, path, &iref,
  6057. bytenr, num_bytes, parent,
  6058. root_objectid, owner_objectid,
  6059. owner_offset);
  6060. if (ret == 0) {
  6061. extent_slot = path->slots[0];
  6062. while (extent_slot >= 0) {
  6063. btrfs_item_key_to_cpu(path->nodes[0], &key,
  6064. extent_slot);
  6065. if (key.objectid != bytenr)
  6066. break;
  6067. if (key.type == BTRFS_EXTENT_ITEM_KEY &&
  6068. key.offset == num_bytes) {
  6069. found_extent = 1;
  6070. break;
  6071. }
  6072. if (key.type == BTRFS_METADATA_ITEM_KEY &&
  6073. key.offset == owner_objectid) {
  6074. found_extent = 1;
  6075. break;
  6076. }
  6077. if (path->slots[0] - extent_slot > 5)
  6078. break;
  6079. extent_slot--;
  6080. }
  6081. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  6082. item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
  6083. if (found_extent && item_size < sizeof(*ei))
  6084. found_extent = 0;
  6085. #endif
  6086. if (!found_extent) {
  6087. BUG_ON(iref);
  6088. ret = remove_extent_backref(trans, extent_root, path,
  6089. NULL, refs_to_drop,
  6090. is_data, &last_ref);
  6091. if (ret) {
  6092. btrfs_abort_transaction(trans, ret);
  6093. goto out;
  6094. }
  6095. btrfs_release_path(path);
  6096. path->leave_spinning = 1;
  6097. key.objectid = bytenr;
  6098. key.type = BTRFS_EXTENT_ITEM_KEY;
  6099. key.offset = num_bytes;
  6100. if (!is_data && skinny_metadata) {
  6101. key.type = BTRFS_METADATA_ITEM_KEY;
  6102. key.offset = owner_objectid;
  6103. }
  6104. ret = btrfs_search_slot(trans, extent_root,
  6105. &key, path, -1, 1);
  6106. if (ret > 0 && skinny_metadata && path->slots[0]) {
  6107. /*
  6108. * Couldn't find our skinny metadata item,
  6109. * see if we have ye olde extent item.
  6110. */
  6111. path->slots[0]--;
  6112. btrfs_item_key_to_cpu(path->nodes[0], &key,
  6113. path->slots[0]);
  6114. if (key.objectid == bytenr &&
  6115. key.type == BTRFS_EXTENT_ITEM_KEY &&
  6116. key.offset == num_bytes)
  6117. ret = 0;
  6118. }
  6119. if (ret > 0 && skinny_metadata) {
  6120. skinny_metadata = false;
  6121. key.objectid = bytenr;
  6122. key.type = BTRFS_EXTENT_ITEM_KEY;
  6123. key.offset = num_bytes;
  6124. btrfs_release_path(path);
  6125. ret = btrfs_search_slot(trans, extent_root,
  6126. &key, path, -1, 1);
  6127. }
  6128. if (ret) {
  6129. btrfs_err(info,
  6130. "umm, got %d back from search, was looking for %llu",
  6131. ret, bytenr);
  6132. if (ret > 0)
  6133. btrfs_print_leaf(extent_root,
  6134. path->nodes[0]);
  6135. }
  6136. if (ret < 0) {
  6137. btrfs_abort_transaction(trans, ret);
  6138. goto out;
  6139. }
  6140. extent_slot = path->slots[0];
  6141. }
  6142. } else if (WARN_ON(ret == -ENOENT)) {
  6143. btrfs_print_leaf(extent_root, path->nodes[0]);
  6144. btrfs_err(info,
  6145. "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
  6146. bytenr, parent, root_objectid, owner_objectid,
  6147. owner_offset);
  6148. btrfs_abort_transaction(trans, ret);
  6149. goto out;
  6150. } else {
  6151. btrfs_abort_transaction(trans, ret);
  6152. goto out;
  6153. }
  6154. leaf = path->nodes[0];
  6155. item_size = btrfs_item_size_nr(leaf, extent_slot);
  6156. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  6157. if (item_size < sizeof(*ei)) {
  6158. BUG_ON(found_extent || extent_slot != path->slots[0]);
  6159. ret = convert_extent_item_v0(trans, extent_root, path,
  6160. owner_objectid, 0);
  6161. if (ret < 0) {
  6162. btrfs_abort_transaction(trans, ret);
  6163. goto out;
  6164. }
  6165. btrfs_release_path(path);
  6166. path->leave_spinning = 1;
  6167. key.objectid = bytenr;
  6168. key.type = BTRFS_EXTENT_ITEM_KEY;
  6169. key.offset = num_bytes;
  6170. ret = btrfs_search_slot(trans, extent_root, &key, path,
  6171. -1, 1);
  6172. if (ret) {
  6173. btrfs_err(info,
  6174. "umm, got %d back from search, was looking for %llu",
  6175. ret, bytenr);
  6176. btrfs_print_leaf(extent_root, path->nodes[0]);
  6177. }
  6178. if (ret < 0) {
  6179. btrfs_abort_transaction(trans, ret);
  6180. goto out;
  6181. }
  6182. extent_slot = path->slots[0];
  6183. leaf = path->nodes[0];
  6184. item_size = btrfs_item_size_nr(leaf, extent_slot);
  6185. }
  6186. #endif
  6187. BUG_ON(item_size < sizeof(*ei));
  6188. ei = btrfs_item_ptr(leaf, extent_slot,
  6189. struct btrfs_extent_item);
  6190. if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
  6191. key.type == BTRFS_EXTENT_ITEM_KEY) {
  6192. struct btrfs_tree_block_info *bi;
  6193. BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
  6194. bi = (struct btrfs_tree_block_info *)(ei + 1);
  6195. WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
  6196. }
  6197. refs = btrfs_extent_refs(leaf, ei);
  6198. if (refs < refs_to_drop) {
  6199. btrfs_err(info,
  6200. "trying to drop %d refs but we only have %Lu for bytenr %Lu",
  6201. refs_to_drop, refs, bytenr);
  6202. ret = -EINVAL;
  6203. btrfs_abort_transaction(trans, ret);
  6204. goto out;
  6205. }
  6206. refs -= refs_to_drop;
  6207. if (refs > 0) {
  6208. if (extent_op)
  6209. __run_delayed_extent_op(extent_op, leaf, ei);
  6210. /*
  6211. * In the case of inline back ref, reference count will
  6212. * be updated by remove_extent_backref
  6213. */
  6214. if (iref) {
  6215. BUG_ON(!found_extent);
  6216. } else {
  6217. btrfs_set_extent_refs(leaf, ei, refs);
  6218. btrfs_mark_buffer_dirty(leaf);
  6219. }
  6220. if (found_extent) {
  6221. ret = remove_extent_backref(trans, extent_root, path,
  6222. iref, refs_to_drop,
  6223. is_data, &last_ref);
  6224. if (ret) {
  6225. btrfs_abort_transaction(trans, ret);
  6226. goto out;
  6227. }
  6228. }
  6229. add_pinned_bytes(root->fs_info, -num_bytes, owner_objectid,
  6230. root_objectid);
  6231. } else {
  6232. if (found_extent) {
  6233. BUG_ON(is_data && refs_to_drop !=
  6234. extent_data_ref_count(path, iref));
  6235. if (iref) {
  6236. BUG_ON(path->slots[0] != extent_slot);
  6237. } else {
  6238. BUG_ON(path->slots[0] != extent_slot + 1);
  6239. path->slots[0] = extent_slot;
  6240. num_to_del = 2;
  6241. }
  6242. }
  6243. last_ref = 1;
  6244. ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
  6245. num_to_del);
  6246. if (ret) {
  6247. btrfs_abort_transaction(trans, ret);
  6248. goto out;
  6249. }
  6250. btrfs_release_path(path);
  6251. if (is_data) {
  6252. ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
  6253. if (ret) {
  6254. btrfs_abort_transaction(trans, ret);
  6255. goto out;
  6256. }
  6257. }
  6258. ret = add_to_free_space_tree(trans, root->fs_info, bytenr,
  6259. num_bytes);
  6260. if (ret) {
  6261. btrfs_abort_transaction(trans, ret);
  6262. goto out;
  6263. }
  6264. ret = update_block_group(trans, root, bytenr, num_bytes, 0);
  6265. if (ret) {
  6266. btrfs_abort_transaction(trans, ret);
  6267. goto out;
  6268. }
  6269. }
  6270. btrfs_release_path(path);
  6271. out:
  6272. btrfs_free_path(path);
  6273. return ret;
  6274. }
  6275. /*
  6276. * when we free an block, it is possible (and likely) that we free the last
  6277. * delayed ref for that extent as well. This searches the delayed ref tree for
  6278. * a given extent, and if there are no other delayed refs to be processed, it
  6279. * removes it from the tree.
  6280. */
  6281. static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
  6282. struct btrfs_root *root, u64 bytenr)
  6283. {
  6284. struct btrfs_delayed_ref_head *head;
  6285. struct btrfs_delayed_ref_root *delayed_refs;
  6286. int ret = 0;
  6287. delayed_refs = &trans->transaction->delayed_refs;
  6288. spin_lock(&delayed_refs->lock);
  6289. head = btrfs_find_delayed_ref_head(trans, bytenr);
  6290. if (!head)
  6291. goto out_delayed_unlock;
  6292. spin_lock(&head->lock);
  6293. if (!list_empty(&head->ref_list))
  6294. goto out;
  6295. if (head->extent_op) {
  6296. if (!head->must_insert_reserved)
  6297. goto out;
  6298. btrfs_free_delayed_extent_op(head->extent_op);
  6299. head->extent_op = NULL;
  6300. }
  6301. /*
  6302. * waiting for the lock here would deadlock. If someone else has it
  6303. * locked they are already in the process of dropping it anyway
  6304. */
  6305. if (!mutex_trylock(&head->mutex))
  6306. goto out;
  6307. /*
  6308. * at this point we have a head with no other entries. Go
  6309. * ahead and process it.
  6310. */
  6311. head->node.in_tree = 0;
  6312. rb_erase(&head->href_node, &delayed_refs->href_root);
  6313. atomic_dec(&delayed_refs->num_entries);
  6314. /*
  6315. * we don't take a ref on the node because we're removing it from the
  6316. * tree, so we just steal the ref the tree was holding.
  6317. */
  6318. delayed_refs->num_heads--;
  6319. if (head->processing == 0)
  6320. delayed_refs->num_heads_ready--;
  6321. head->processing = 0;
  6322. spin_unlock(&head->lock);
  6323. spin_unlock(&delayed_refs->lock);
  6324. BUG_ON(head->extent_op);
  6325. if (head->must_insert_reserved)
  6326. ret = 1;
  6327. mutex_unlock(&head->mutex);
  6328. btrfs_put_delayed_ref(&head->node);
  6329. return ret;
  6330. out:
  6331. spin_unlock(&head->lock);
  6332. out_delayed_unlock:
  6333. spin_unlock(&delayed_refs->lock);
  6334. return 0;
  6335. }
  6336. void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
  6337. struct btrfs_root *root,
  6338. struct extent_buffer *buf,
  6339. u64 parent, int last_ref)
  6340. {
  6341. int pin = 1;
  6342. int ret;
  6343. if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
  6344. ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
  6345. buf->start, buf->len,
  6346. parent, root->root_key.objectid,
  6347. btrfs_header_level(buf),
  6348. BTRFS_DROP_DELAYED_REF, NULL);
  6349. BUG_ON(ret); /* -ENOMEM */
  6350. }
  6351. if (!last_ref)
  6352. return;
  6353. if (btrfs_header_generation(buf) == trans->transid) {
  6354. struct btrfs_block_group_cache *cache;
  6355. if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
  6356. ret = check_ref_cleanup(trans, root, buf->start);
  6357. if (!ret)
  6358. goto out;
  6359. }
  6360. cache = btrfs_lookup_block_group(root->fs_info, buf->start);
  6361. if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
  6362. pin_down_extent(root, cache, buf->start, buf->len, 1);
  6363. btrfs_put_block_group(cache);
  6364. goto out;
  6365. }
  6366. WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
  6367. btrfs_add_free_space(cache, buf->start, buf->len);
  6368. btrfs_free_reserved_bytes(cache, buf->len, 0);
  6369. btrfs_put_block_group(cache);
  6370. trace_btrfs_reserved_extent_free(root, buf->start, buf->len);
  6371. pin = 0;
  6372. }
  6373. out:
  6374. if (pin)
  6375. add_pinned_bytes(root->fs_info, buf->len,
  6376. btrfs_header_level(buf),
  6377. root->root_key.objectid);
  6378. /*
  6379. * Deleting the buffer, clear the corrupt flag since it doesn't matter
  6380. * anymore.
  6381. */
  6382. clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
  6383. }
  6384. /* Can return -ENOMEM */
  6385. int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  6386. u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
  6387. u64 owner, u64 offset)
  6388. {
  6389. int ret;
  6390. struct btrfs_fs_info *fs_info = root->fs_info;
  6391. if (btrfs_is_testing(fs_info))
  6392. return 0;
  6393. add_pinned_bytes(root->fs_info, num_bytes, owner, root_objectid);
  6394. /*
  6395. * tree log blocks never actually go into the extent allocation
  6396. * tree, just update pinning info and exit early.
  6397. */
  6398. if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
  6399. WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
  6400. /* unlocks the pinned mutex */
  6401. btrfs_pin_extent(root, bytenr, num_bytes, 1);
  6402. ret = 0;
  6403. } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  6404. ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
  6405. num_bytes,
  6406. parent, root_objectid, (int)owner,
  6407. BTRFS_DROP_DELAYED_REF, NULL);
  6408. } else {
  6409. ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
  6410. num_bytes,
  6411. parent, root_objectid, owner,
  6412. offset, 0,
  6413. BTRFS_DROP_DELAYED_REF, NULL);
  6414. }
  6415. return ret;
  6416. }
  6417. /*
  6418. * when we wait for progress in the block group caching, its because
  6419. * our allocation attempt failed at least once. So, we must sleep
  6420. * and let some progress happen before we try again.
  6421. *
  6422. * This function will sleep at least once waiting for new free space to
  6423. * show up, and then it will check the block group free space numbers
  6424. * for our min num_bytes. Another option is to have it go ahead
  6425. * and look in the rbtree for a free extent of a given size, but this
  6426. * is a good start.
  6427. *
  6428. * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
  6429. * any of the information in this block group.
  6430. */
  6431. static noinline void
  6432. wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
  6433. u64 num_bytes)
  6434. {
  6435. struct btrfs_caching_control *caching_ctl;
  6436. caching_ctl = get_caching_control(cache);
  6437. if (!caching_ctl)
  6438. return;
  6439. wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
  6440. (cache->free_space_ctl->free_space >= num_bytes));
  6441. put_caching_control(caching_ctl);
  6442. }
  6443. static noinline int
  6444. wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
  6445. {
  6446. struct btrfs_caching_control *caching_ctl;
  6447. int ret = 0;
  6448. caching_ctl = get_caching_control(cache);
  6449. if (!caching_ctl)
  6450. return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
  6451. wait_event(caching_ctl->wait, block_group_cache_done(cache));
  6452. if (cache->cached == BTRFS_CACHE_ERROR)
  6453. ret = -EIO;
  6454. put_caching_control(caching_ctl);
  6455. return ret;
  6456. }
  6457. int __get_raid_index(u64 flags)
  6458. {
  6459. if (flags & BTRFS_BLOCK_GROUP_RAID10)
  6460. return BTRFS_RAID_RAID10;
  6461. else if (flags & BTRFS_BLOCK_GROUP_RAID1)
  6462. return BTRFS_RAID_RAID1;
  6463. else if (flags & BTRFS_BLOCK_GROUP_DUP)
  6464. return BTRFS_RAID_DUP;
  6465. else if (flags & BTRFS_BLOCK_GROUP_RAID0)
  6466. return BTRFS_RAID_RAID0;
  6467. else if (flags & BTRFS_BLOCK_GROUP_RAID5)
  6468. return BTRFS_RAID_RAID5;
  6469. else if (flags & BTRFS_BLOCK_GROUP_RAID6)
  6470. return BTRFS_RAID_RAID6;
  6471. return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
  6472. }
  6473. int get_block_group_index(struct btrfs_block_group_cache *cache)
  6474. {
  6475. return __get_raid_index(cache->flags);
  6476. }
  6477. static const char *btrfs_raid_type_names[BTRFS_NR_RAID_TYPES] = {
  6478. [BTRFS_RAID_RAID10] = "raid10",
  6479. [BTRFS_RAID_RAID1] = "raid1",
  6480. [BTRFS_RAID_DUP] = "dup",
  6481. [BTRFS_RAID_RAID0] = "raid0",
  6482. [BTRFS_RAID_SINGLE] = "single",
  6483. [BTRFS_RAID_RAID5] = "raid5",
  6484. [BTRFS_RAID_RAID6] = "raid6",
  6485. };
  6486. static const char *get_raid_name(enum btrfs_raid_types type)
  6487. {
  6488. if (type >= BTRFS_NR_RAID_TYPES)
  6489. return NULL;
  6490. return btrfs_raid_type_names[type];
  6491. }
  6492. enum btrfs_loop_type {
  6493. LOOP_CACHING_NOWAIT = 0,
  6494. LOOP_CACHING_WAIT = 1,
  6495. LOOP_ALLOC_CHUNK = 2,
  6496. LOOP_NO_EMPTY_SIZE = 3,
  6497. };
  6498. static inline void
  6499. btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
  6500. int delalloc)
  6501. {
  6502. if (delalloc)
  6503. down_read(&cache->data_rwsem);
  6504. }
  6505. static inline void
  6506. btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
  6507. int delalloc)
  6508. {
  6509. btrfs_get_block_group(cache);
  6510. if (delalloc)
  6511. down_read(&cache->data_rwsem);
  6512. }
  6513. static struct btrfs_block_group_cache *
  6514. btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
  6515. struct btrfs_free_cluster *cluster,
  6516. int delalloc)
  6517. {
  6518. struct btrfs_block_group_cache *used_bg = NULL;
  6519. spin_lock(&cluster->refill_lock);
  6520. while (1) {
  6521. used_bg = cluster->block_group;
  6522. if (!used_bg)
  6523. return NULL;
  6524. if (used_bg == block_group)
  6525. return used_bg;
  6526. btrfs_get_block_group(used_bg);
  6527. if (!delalloc)
  6528. return used_bg;
  6529. if (down_read_trylock(&used_bg->data_rwsem))
  6530. return used_bg;
  6531. spin_unlock(&cluster->refill_lock);
  6532. /* We should only have one-level nested. */
  6533. down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
  6534. spin_lock(&cluster->refill_lock);
  6535. if (used_bg == cluster->block_group)
  6536. return used_bg;
  6537. up_read(&used_bg->data_rwsem);
  6538. btrfs_put_block_group(used_bg);
  6539. }
  6540. }
  6541. static inline void
  6542. btrfs_release_block_group(struct btrfs_block_group_cache *cache,
  6543. int delalloc)
  6544. {
  6545. if (delalloc)
  6546. up_read(&cache->data_rwsem);
  6547. btrfs_put_block_group(cache);
  6548. }
  6549. /*
  6550. * walks the btree of allocated extents and find a hole of a given size.
  6551. * The key ins is changed to record the hole:
  6552. * ins->objectid == start position
  6553. * ins->flags = BTRFS_EXTENT_ITEM_KEY
  6554. * ins->offset == the size of the hole.
  6555. * Any available blocks before search_start are skipped.
  6556. *
  6557. * If there is no suitable free space, we will record the max size of
  6558. * the free space extent currently.
  6559. */
  6560. static noinline int find_free_extent(struct btrfs_root *orig_root,
  6561. u64 ram_bytes, u64 num_bytes, u64 empty_size,
  6562. u64 hint_byte, struct btrfs_key *ins,
  6563. u64 flags, int delalloc)
  6564. {
  6565. int ret = 0;
  6566. struct btrfs_root *root = orig_root->fs_info->extent_root;
  6567. struct btrfs_free_cluster *last_ptr = NULL;
  6568. struct btrfs_block_group_cache *block_group = NULL;
  6569. u64 search_start = 0;
  6570. u64 max_extent_size = 0;
  6571. u64 empty_cluster = 0;
  6572. struct btrfs_space_info *space_info;
  6573. int loop = 0;
  6574. int index = __get_raid_index(flags);
  6575. bool failed_cluster_refill = false;
  6576. bool failed_alloc = false;
  6577. bool use_cluster = true;
  6578. bool have_caching_bg = false;
  6579. bool orig_have_caching_bg = false;
  6580. bool full_search = false;
  6581. WARN_ON(num_bytes < root->sectorsize);
  6582. ins->type = BTRFS_EXTENT_ITEM_KEY;
  6583. ins->objectid = 0;
  6584. ins->offset = 0;
  6585. trace_find_free_extent(orig_root, num_bytes, empty_size, flags);
  6586. space_info = __find_space_info(root->fs_info, flags);
  6587. if (!space_info) {
  6588. btrfs_err(root->fs_info, "No space info for %llu", flags);
  6589. return -ENOSPC;
  6590. }
  6591. /*
  6592. * If our free space is heavily fragmented we may not be able to make
  6593. * big contiguous allocations, so instead of doing the expensive search
  6594. * for free space, simply return ENOSPC with our max_extent_size so we
  6595. * can go ahead and search for a more manageable chunk.
  6596. *
  6597. * If our max_extent_size is large enough for our allocation simply
  6598. * disable clustering since we will likely not be able to find enough
  6599. * space to create a cluster and induce latency trying.
  6600. */
  6601. if (unlikely(space_info->max_extent_size)) {
  6602. spin_lock(&space_info->lock);
  6603. if (space_info->max_extent_size &&
  6604. num_bytes > space_info->max_extent_size) {
  6605. ins->offset = space_info->max_extent_size;
  6606. spin_unlock(&space_info->lock);
  6607. return -ENOSPC;
  6608. } else if (space_info->max_extent_size) {
  6609. use_cluster = false;
  6610. }
  6611. spin_unlock(&space_info->lock);
  6612. }
  6613. last_ptr = fetch_cluster_info(orig_root, space_info, &empty_cluster);
  6614. if (last_ptr) {
  6615. spin_lock(&last_ptr->lock);
  6616. if (last_ptr->block_group)
  6617. hint_byte = last_ptr->window_start;
  6618. if (last_ptr->fragmented) {
  6619. /*
  6620. * We still set window_start so we can keep track of the
  6621. * last place we found an allocation to try and save
  6622. * some time.
  6623. */
  6624. hint_byte = last_ptr->window_start;
  6625. use_cluster = false;
  6626. }
  6627. spin_unlock(&last_ptr->lock);
  6628. }
  6629. search_start = max(search_start, first_logical_byte(root, 0));
  6630. search_start = max(search_start, hint_byte);
  6631. if (search_start == hint_byte) {
  6632. block_group = btrfs_lookup_block_group(root->fs_info,
  6633. search_start);
  6634. /*
  6635. * we don't want to use the block group if it doesn't match our
  6636. * allocation bits, or if its not cached.
  6637. *
  6638. * However if we are re-searching with an ideal block group
  6639. * picked out then we don't care that the block group is cached.
  6640. */
  6641. if (block_group && block_group_bits(block_group, flags) &&
  6642. block_group->cached != BTRFS_CACHE_NO) {
  6643. down_read(&space_info->groups_sem);
  6644. if (list_empty(&block_group->list) ||
  6645. block_group->ro) {
  6646. /*
  6647. * someone is removing this block group,
  6648. * we can't jump into the have_block_group
  6649. * target because our list pointers are not
  6650. * valid
  6651. */
  6652. btrfs_put_block_group(block_group);
  6653. up_read(&space_info->groups_sem);
  6654. } else {
  6655. index = get_block_group_index(block_group);
  6656. btrfs_lock_block_group(block_group, delalloc);
  6657. goto have_block_group;
  6658. }
  6659. } else if (block_group) {
  6660. btrfs_put_block_group(block_group);
  6661. }
  6662. }
  6663. search:
  6664. have_caching_bg = false;
  6665. if (index == 0 || index == __get_raid_index(flags))
  6666. full_search = true;
  6667. down_read(&space_info->groups_sem);
  6668. list_for_each_entry(block_group, &space_info->block_groups[index],
  6669. list) {
  6670. u64 offset;
  6671. int cached;
  6672. btrfs_grab_block_group(block_group, delalloc);
  6673. search_start = block_group->key.objectid;
  6674. /*
  6675. * this can happen if we end up cycling through all the
  6676. * raid types, but we want to make sure we only allocate
  6677. * for the proper type.
  6678. */
  6679. if (!block_group_bits(block_group, flags)) {
  6680. u64 extra = BTRFS_BLOCK_GROUP_DUP |
  6681. BTRFS_BLOCK_GROUP_RAID1 |
  6682. BTRFS_BLOCK_GROUP_RAID5 |
  6683. BTRFS_BLOCK_GROUP_RAID6 |
  6684. BTRFS_BLOCK_GROUP_RAID10;
  6685. /*
  6686. * if they asked for extra copies and this block group
  6687. * doesn't provide them, bail. This does allow us to
  6688. * fill raid0 from raid1.
  6689. */
  6690. if ((flags & extra) && !(block_group->flags & extra))
  6691. goto loop;
  6692. }
  6693. have_block_group:
  6694. cached = block_group_cache_done(block_group);
  6695. if (unlikely(!cached)) {
  6696. have_caching_bg = true;
  6697. ret = cache_block_group(block_group, 0);
  6698. BUG_ON(ret < 0);
  6699. ret = 0;
  6700. }
  6701. if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
  6702. goto loop;
  6703. if (unlikely(block_group->ro))
  6704. goto loop;
  6705. /*
  6706. * Ok we want to try and use the cluster allocator, so
  6707. * lets look there
  6708. */
  6709. if (last_ptr && use_cluster) {
  6710. struct btrfs_block_group_cache *used_block_group;
  6711. unsigned long aligned_cluster;
  6712. /*
  6713. * the refill lock keeps out other
  6714. * people trying to start a new cluster
  6715. */
  6716. used_block_group = btrfs_lock_cluster(block_group,
  6717. last_ptr,
  6718. delalloc);
  6719. if (!used_block_group)
  6720. goto refill_cluster;
  6721. if (used_block_group != block_group &&
  6722. (used_block_group->ro ||
  6723. !block_group_bits(used_block_group, flags)))
  6724. goto release_cluster;
  6725. offset = btrfs_alloc_from_cluster(used_block_group,
  6726. last_ptr,
  6727. num_bytes,
  6728. used_block_group->key.objectid,
  6729. &max_extent_size);
  6730. if (offset) {
  6731. /* we have a block, we're done */
  6732. spin_unlock(&last_ptr->refill_lock);
  6733. trace_btrfs_reserve_extent_cluster(root,
  6734. used_block_group,
  6735. search_start, num_bytes);
  6736. if (used_block_group != block_group) {
  6737. btrfs_release_block_group(block_group,
  6738. delalloc);
  6739. block_group = used_block_group;
  6740. }
  6741. goto checks;
  6742. }
  6743. WARN_ON(last_ptr->block_group != used_block_group);
  6744. release_cluster:
  6745. /* If we are on LOOP_NO_EMPTY_SIZE, we can't
  6746. * set up a new clusters, so lets just skip it
  6747. * and let the allocator find whatever block
  6748. * it can find. If we reach this point, we
  6749. * will have tried the cluster allocator
  6750. * plenty of times and not have found
  6751. * anything, so we are likely way too
  6752. * fragmented for the clustering stuff to find
  6753. * anything.
  6754. *
  6755. * However, if the cluster is taken from the
  6756. * current block group, release the cluster
  6757. * first, so that we stand a better chance of
  6758. * succeeding in the unclustered
  6759. * allocation. */
  6760. if (loop >= LOOP_NO_EMPTY_SIZE &&
  6761. used_block_group != block_group) {
  6762. spin_unlock(&last_ptr->refill_lock);
  6763. btrfs_release_block_group(used_block_group,
  6764. delalloc);
  6765. goto unclustered_alloc;
  6766. }
  6767. /*
  6768. * this cluster didn't work out, free it and
  6769. * start over
  6770. */
  6771. btrfs_return_cluster_to_free_space(NULL, last_ptr);
  6772. if (used_block_group != block_group)
  6773. btrfs_release_block_group(used_block_group,
  6774. delalloc);
  6775. refill_cluster:
  6776. if (loop >= LOOP_NO_EMPTY_SIZE) {
  6777. spin_unlock(&last_ptr->refill_lock);
  6778. goto unclustered_alloc;
  6779. }
  6780. aligned_cluster = max_t(unsigned long,
  6781. empty_cluster + empty_size,
  6782. block_group->full_stripe_len);
  6783. /* allocate a cluster in this block group */
  6784. ret = btrfs_find_space_cluster(root, block_group,
  6785. last_ptr, search_start,
  6786. num_bytes,
  6787. aligned_cluster);
  6788. if (ret == 0) {
  6789. /*
  6790. * now pull our allocation out of this
  6791. * cluster
  6792. */
  6793. offset = btrfs_alloc_from_cluster(block_group,
  6794. last_ptr,
  6795. num_bytes,
  6796. search_start,
  6797. &max_extent_size);
  6798. if (offset) {
  6799. /* we found one, proceed */
  6800. spin_unlock(&last_ptr->refill_lock);
  6801. trace_btrfs_reserve_extent_cluster(root,
  6802. block_group, search_start,
  6803. num_bytes);
  6804. goto checks;
  6805. }
  6806. } else if (!cached && loop > LOOP_CACHING_NOWAIT
  6807. && !failed_cluster_refill) {
  6808. spin_unlock(&last_ptr->refill_lock);
  6809. failed_cluster_refill = true;
  6810. wait_block_group_cache_progress(block_group,
  6811. num_bytes + empty_cluster + empty_size);
  6812. goto have_block_group;
  6813. }
  6814. /*
  6815. * at this point we either didn't find a cluster
  6816. * or we weren't able to allocate a block from our
  6817. * cluster. Free the cluster we've been trying
  6818. * to use, and go to the next block group
  6819. */
  6820. btrfs_return_cluster_to_free_space(NULL, last_ptr);
  6821. spin_unlock(&last_ptr->refill_lock);
  6822. goto loop;
  6823. }
  6824. unclustered_alloc:
  6825. /*
  6826. * We are doing an unclustered alloc, set the fragmented flag so
  6827. * we don't bother trying to setup a cluster again until we get
  6828. * more space.
  6829. */
  6830. if (unlikely(last_ptr)) {
  6831. spin_lock(&last_ptr->lock);
  6832. last_ptr->fragmented = 1;
  6833. spin_unlock(&last_ptr->lock);
  6834. }
  6835. spin_lock(&block_group->free_space_ctl->tree_lock);
  6836. if (cached &&
  6837. block_group->free_space_ctl->free_space <
  6838. num_bytes + empty_cluster + empty_size) {
  6839. if (block_group->free_space_ctl->free_space >
  6840. max_extent_size)
  6841. max_extent_size =
  6842. block_group->free_space_ctl->free_space;
  6843. spin_unlock(&block_group->free_space_ctl->tree_lock);
  6844. goto loop;
  6845. }
  6846. spin_unlock(&block_group->free_space_ctl->tree_lock);
  6847. offset = btrfs_find_space_for_alloc(block_group, search_start,
  6848. num_bytes, empty_size,
  6849. &max_extent_size);
  6850. /*
  6851. * If we didn't find a chunk, and we haven't failed on this
  6852. * block group before, and this block group is in the middle of
  6853. * caching and we are ok with waiting, then go ahead and wait
  6854. * for progress to be made, and set failed_alloc to true.
  6855. *
  6856. * If failed_alloc is true then we've already waited on this
  6857. * block group once and should move on to the next block group.
  6858. */
  6859. if (!offset && !failed_alloc && !cached &&
  6860. loop > LOOP_CACHING_NOWAIT) {
  6861. wait_block_group_cache_progress(block_group,
  6862. num_bytes + empty_size);
  6863. failed_alloc = true;
  6864. goto have_block_group;
  6865. } else if (!offset) {
  6866. goto loop;
  6867. }
  6868. checks:
  6869. search_start = ALIGN(offset, root->stripesize);
  6870. /* move on to the next group */
  6871. if (search_start + num_bytes >
  6872. block_group->key.objectid + block_group->key.offset) {
  6873. btrfs_add_free_space(block_group, offset, num_bytes);
  6874. goto loop;
  6875. }
  6876. if (offset < search_start)
  6877. btrfs_add_free_space(block_group, offset,
  6878. search_start - offset);
  6879. BUG_ON(offset > search_start);
  6880. ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
  6881. num_bytes, delalloc);
  6882. if (ret == -EAGAIN) {
  6883. btrfs_add_free_space(block_group, offset, num_bytes);
  6884. goto loop;
  6885. }
  6886. btrfs_inc_block_group_reservations(block_group);
  6887. /* we are all good, lets return */
  6888. ins->objectid = search_start;
  6889. ins->offset = num_bytes;
  6890. trace_btrfs_reserve_extent(orig_root, block_group,
  6891. search_start, num_bytes);
  6892. btrfs_release_block_group(block_group, delalloc);
  6893. break;
  6894. loop:
  6895. failed_cluster_refill = false;
  6896. failed_alloc = false;
  6897. BUG_ON(index != get_block_group_index(block_group));
  6898. btrfs_release_block_group(block_group, delalloc);
  6899. }
  6900. up_read(&space_info->groups_sem);
  6901. if ((loop == LOOP_CACHING_NOWAIT) && have_caching_bg
  6902. && !orig_have_caching_bg)
  6903. orig_have_caching_bg = true;
  6904. if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
  6905. goto search;
  6906. if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
  6907. goto search;
  6908. /*
  6909. * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
  6910. * caching kthreads as we move along
  6911. * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
  6912. * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
  6913. * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
  6914. * again
  6915. */
  6916. if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
  6917. index = 0;
  6918. if (loop == LOOP_CACHING_NOWAIT) {
  6919. /*
  6920. * We want to skip the LOOP_CACHING_WAIT step if we
  6921. * don't have any uncached bgs and we've already done a
  6922. * full search through.
  6923. */
  6924. if (orig_have_caching_bg || !full_search)
  6925. loop = LOOP_CACHING_WAIT;
  6926. else
  6927. loop = LOOP_ALLOC_CHUNK;
  6928. } else {
  6929. loop++;
  6930. }
  6931. if (loop == LOOP_ALLOC_CHUNK) {
  6932. struct btrfs_trans_handle *trans;
  6933. int exist = 0;
  6934. trans = current->journal_info;
  6935. if (trans)
  6936. exist = 1;
  6937. else
  6938. trans = btrfs_join_transaction(root);
  6939. if (IS_ERR(trans)) {
  6940. ret = PTR_ERR(trans);
  6941. goto out;
  6942. }
  6943. ret = do_chunk_alloc(trans, root, flags,
  6944. CHUNK_ALLOC_FORCE);
  6945. /*
  6946. * If we can't allocate a new chunk we've already looped
  6947. * through at least once, move on to the NO_EMPTY_SIZE
  6948. * case.
  6949. */
  6950. if (ret == -ENOSPC)
  6951. loop = LOOP_NO_EMPTY_SIZE;
  6952. /*
  6953. * Do not bail out on ENOSPC since we
  6954. * can do more things.
  6955. */
  6956. if (ret < 0 && ret != -ENOSPC)
  6957. btrfs_abort_transaction(trans, ret);
  6958. else
  6959. ret = 0;
  6960. if (!exist)
  6961. btrfs_end_transaction(trans, root);
  6962. if (ret)
  6963. goto out;
  6964. }
  6965. if (loop == LOOP_NO_EMPTY_SIZE) {
  6966. /*
  6967. * Don't loop again if we already have no empty_size and
  6968. * no empty_cluster.
  6969. */
  6970. if (empty_size == 0 &&
  6971. empty_cluster == 0) {
  6972. ret = -ENOSPC;
  6973. goto out;
  6974. }
  6975. empty_size = 0;
  6976. empty_cluster = 0;
  6977. }
  6978. goto search;
  6979. } else if (!ins->objectid) {
  6980. ret = -ENOSPC;
  6981. } else if (ins->objectid) {
  6982. if (!use_cluster && last_ptr) {
  6983. spin_lock(&last_ptr->lock);
  6984. last_ptr->window_start = ins->objectid;
  6985. spin_unlock(&last_ptr->lock);
  6986. }
  6987. ret = 0;
  6988. }
  6989. out:
  6990. if (ret == -ENOSPC) {
  6991. spin_lock(&space_info->lock);
  6992. space_info->max_extent_size = max_extent_size;
  6993. spin_unlock(&space_info->lock);
  6994. ins->offset = max_extent_size;
  6995. }
  6996. return ret;
  6997. }
  6998. static void dump_space_info(struct btrfs_fs_info *fs_info,
  6999. struct btrfs_space_info *info, u64 bytes,
  7000. int dump_block_groups)
  7001. {
  7002. struct btrfs_block_group_cache *cache;
  7003. int index = 0;
  7004. spin_lock(&info->lock);
  7005. btrfs_info(fs_info, "space_info %llu has %llu free, is %sfull",
  7006. info->flags,
  7007. info->total_bytes - info->bytes_used - info->bytes_pinned -
  7008. info->bytes_reserved - info->bytes_readonly -
  7009. info->bytes_may_use, (info->full) ? "" : "not ");
  7010. btrfs_info(fs_info,
  7011. "space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu",
  7012. info->total_bytes, info->bytes_used, info->bytes_pinned,
  7013. info->bytes_reserved, info->bytes_may_use,
  7014. info->bytes_readonly);
  7015. spin_unlock(&info->lock);
  7016. if (!dump_block_groups)
  7017. return;
  7018. down_read(&info->groups_sem);
  7019. again:
  7020. list_for_each_entry(cache, &info->block_groups[index], list) {
  7021. spin_lock(&cache->lock);
  7022. btrfs_info(fs_info,
  7023. "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s",
  7024. cache->key.objectid, cache->key.offset,
  7025. btrfs_block_group_used(&cache->item), cache->pinned,
  7026. cache->reserved, cache->ro ? "[readonly]" : "");
  7027. btrfs_dump_free_space(cache, bytes);
  7028. spin_unlock(&cache->lock);
  7029. }
  7030. if (++index < BTRFS_NR_RAID_TYPES)
  7031. goto again;
  7032. up_read(&info->groups_sem);
  7033. }
  7034. int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
  7035. u64 num_bytes, u64 min_alloc_size,
  7036. u64 empty_size, u64 hint_byte,
  7037. struct btrfs_key *ins, int is_data, int delalloc)
  7038. {
  7039. struct btrfs_fs_info *fs_info = root->fs_info;
  7040. bool final_tried = num_bytes == min_alloc_size;
  7041. u64 flags;
  7042. int ret;
  7043. flags = btrfs_get_alloc_profile(root, is_data);
  7044. again:
  7045. WARN_ON(num_bytes < root->sectorsize);
  7046. ret = find_free_extent(root, ram_bytes, num_bytes, empty_size,
  7047. hint_byte, ins, flags, delalloc);
  7048. if (!ret && !is_data) {
  7049. btrfs_dec_block_group_reservations(fs_info, ins->objectid);
  7050. } else if (ret == -ENOSPC) {
  7051. if (!final_tried && ins->offset) {
  7052. num_bytes = min(num_bytes >> 1, ins->offset);
  7053. num_bytes = round_down(num_bytes, root->sectorsize);
  7054. num_bytes = max(num_bytes, min_alloc_size);
  7055. ram_bytes = num_bytes;
  7056. if (num_bytes == min_alloc_size)
  7057. final_tried = true;
  7058. goto again;
  7059. } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
  7060. struct btrfs_space_info *sinfo;
  7061. sinfo = __find_space_info(fs_info, flags);
  7062. btrfs_err(root->fs_info,
  7063. "allocation failed flags %llu, wanted %llu",
  7064. flags, num_bytes);
  7065. if (sinfo)
  7066. dump_space_info(fs_info, sinfo, num_bytes, 1);
  7067. }
  7068. }
  7069. return ret;
  7070. }
  7071. static int __btrfs_free_reserved_extent(struct btrfs_root *root,
  7072. u64 start, u64 len,
  7073. int pin, int delalloc)
  7074. {
  7075. struct btrfs_block_group_cache *cache;
  7076. int ret = 0;
  7077. cache = btrfs_lookup_block_group(root->fs_info, start);
  7078. if (!cache) {
  7079. btrfs_err(root->fs_info, "Unable to find block group for %llu",
  7080. start);
  7081. return -ENOSPC;
  7082. }
  7083. if (pin)
  7084. pin_down_extent(root, cache, start, len, 1);
  7085. else {
  7086. if (btrfs_test_opt(root->fs_info, DISCARD))
  7087. ret = btrfs_discard_extent(root, start, len, NULL);
  7088. btrfs_add_free_space(cache, start, len);
  7089. btrfs_free_reserved_bytes(cache, len, delalloc);
  7090. trace_btrfs_reserved_extent_free(root, start, len);
  7091. }
  7092. btrfs_put_block_group(cache);
  7093. return ret;
  7094. }
  7095. int btrfs_free_reserved_extent(struct btrfs_root *root,
  7096. u64 start, u64 len, int delalloc)
  7097. {
  7098. return __btrfs_free_reserved_extent(root, start, len, 0, delalloc);
  7099. }
  7100. int btrfs_free_and_pin_reserved_extent(struct btrfs_root *root,
  7101. u64 start, u64 len)
  7102. {
  7103. return __btrfs_free_reserved_extent(root, start, len, 1, 0);
  7104. }
  7105. static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
  7106. struct btrfs_root *root,
  7107. u64 parent, u64 root_objectid,
  7108. u64 flags, u64 owner, u64 offset,
  7109. struct btrfs_key *ins, int ref_mod)
  7110. {
  7111. int ret;
  7112. struct btrfs_fs_info *fs_info = root->fs_info;
  7113. struct btrfs_extent_item *extent_item;
  7114. struct btrfs_extent_inline_ref *iref;
  7115. struct btrfs_path *path;
  7116. struct extent_buffer *leaf;
  7117. int type;
  7118. u32 size;
  7119. if (parent > 0)
  7120. type = BTRFS_SHARED_DATA_REF_KEY;
  7121. else
  7122. type = BTRFS_EXTENT_DATA_REF_KEY;
  7123. size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
  7124. path = btrfs_alloc_path();
  7125. if (!path)
  7126. return -ENOMEM;
  7127. path->leave_spinning = 1;
  7128. ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
  7129. ins, size);
  7130. if (ret) {
  7131. btrfs_free_path(path);
  7132. return ret;
  7133. }
  7134. leaf = path->nodes[0];
  7135. extent_item = btrfs_item_ptr(leaf, path->slots[0],
  7136. struct btrfs_extent_item);
  7137. btrfs_set_extent_refs(leaf, extent_item, ref_mod);
  7138. btrfs_set_extent_generation(leaf, extent_item, trans->transid);
  7139. btrfs_set_extent_flags(leaf, extent_item,
  7140. flags | BTRFS_EXTENT_FLAG_DATA);
  7141. iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
  7142. btrfs_set_extent_inline_ref_type(leaf, iref, type);
  7143. if (parent > 0) {
  7144. struct btrfs_shared_data_ref *ref;
  7145. ref = (struct btrfs_shared_data_ref *)(iref + 1);
  7146. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  7147. btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
  7148. } else {
  7149. struct btrfs_extent_data_ref *ref;
  7150. ref = (struct btrfs_extent_data_ref *)(&iref->offset);
  7151. btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
  7152. btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
  7153. btrfs_set_extent_data_ref_offset(leaf, ref, offset);
  7154. btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
  7155. }
  7156. btrfs_mark_buffer_dirty(path->nodes[0]);
  7157. btrfs_free_path(path);
  7158. ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
  7159. ins->offset);
  7160. if (ret)
  7161. return ret;
  7162. ret = update_block_group(trans, root, ins->objectid, ins->offset, 1);
  7163. if (ret) { /* -ENOENT, logic error */
  7164. btrfs_err(fs_info, "update block group failed for %llu %llu",
  7165. ins->objectid, ins->offset);
  7166. BUG();
  7167. }
  7168. trace_btrfs_reserved_extent_alloc(root, ins->objectid, ins->offset);
  7169. return ret;
  7170. }
  7171. static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
  7172. struct btrfs_root *root,
  7173. u64 parent, u64 root_objectid,
  7174. u64 flags, struct btrfs_disk_key *key,
  7175. int level, struct btrfs_key *ins)
  7176. {
  7177. int ret;
  7178. struct btrfs_fs_info *fs_info = root->fs_info;
  7179. struct btrfs_extent_item *extent_item;
  7180. struct btrfs_tree_block_info *block_info;
  7181. struct btrfs_extent_inline_ref *iref;
  7182. struct btrfs_path *path;
  7183. struct extent_buffer *leaf;
  7184. u32 size = sizeof(*extent_item) + sizeof(*iref);
  7185. u64 num_bytes = ins->offset;
  7186. bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
  7187. SKINNY_METADATA);
  7188. if (!skinny_metadata)
  7189. size += sizeof(*block_info);
  7190. path = btrfs_alloc_path();
  7191. if (!path) {
  7192. btrfs_free_and_pin_reserved_extent(root, ins->objectid,
  7193. root->nodesize);
  7194. return -ENOMEM;
  7195. }
  7196. path->leave_spinning = 1;
  7197. ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
  7198. ins, size);
  7199. if (ret) {
  7200. btrfs_free_path(path);
  7201. btrfs_free_and_pin_reserved_extent(root, ins->objectid,
  7202. root->nodesize);
  7203. return ret;
  7204. }
  7205. leaf = path->nodes[0];
  7206. extent_item = btrfs_item_ptr(leaf, path->slots[0],
  7207. struct btrfs_extent_item);
  7208. btrfs_set_extent_refs(leaf, extent_item, 1);
  7209. btrfs_set_extent_generation(leaf, extent_item, trans->transid);
  7210. btrfs_set_extent_flags(leaf, extent_item,
  7211. flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
  7212. if (skinny_metadata) {
  7213. iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
  7214. num_bytes = root->nodesize;
  7215. } else {
  7216. block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
  7217. btrfs_set_tree_block_key(leaf, block_info, key);
  7218. btrfs_set_tree_block_level(leaf, block_info, level);
  7219. iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
  7220. }
  7221. if (parent > 0) {
  7222. BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
  7223. btrfs_set_extent_inline_ref_type(leaf, iref,
  7224. BTRFS_SHARED_BLOCK_REF_KEY);
  7225. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  7226. } else {
  7227. btrfs_set_extent_inline_ref_type(leaf, iref,
  7228. BTRFS_TREE_BLOCK_REF_KEY);
  7229. btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
  7230. }
  7231. btrfs_mark_buffer_dirty(leaf);
  7232. btrfs_free_path(path);
  7233. ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
  7234. num_bytes);
  7235. if (ret)
  7236. return ret;
  7237. ret = update_block_group(trans, root, ins->objectid, root->nodesize,
  7238. 1);
  7239. if (ret) { /* -ENOENT, logic error */
  7240. btrfs_err(fs_info, "update block group failed for %llu %llu",
  7241. ins->objectid, ins->offset);
  7242. BUG();
  7243. }
  7244. trace_btrfs_reserved_extent_alloc(root, ins->objectid, root->nodesize);
  7245. return ret;
  7246. }
  7247. int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
  7248. struct btrfs_root *root,
  7249. u64 root_objectid, u64 owner,
  7250. u64 offset, u64 ram_bytes,
  7251. struct btrfs_key *ins)
  7252. {
  7253. int ret;
  7254. BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
  7255. ret = btrfs_add_delayed_data_ref(root->fs_info, trans, ins->objectid,
  7256. ins->offset, 0,
  7257. root_objectid, owner, offset,
  7258. ram_bytes, BTRFS_ADD_DELAYED_EXTENT,
  7259. NULL);
  7260. return ret;
  7261. }
  7262. /*
  7263. * this is used by the tree logging recovery code. It records that
  7264. * an extent has been allocated and makes sure to clear the free
  7265. * space cache bits as well
  7266. */
  7267. int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
  7268. struct btrfs_root *root,
  7269. u64 root_objectid, u64 owner, u64 offset,
  7270. struct btrfs_key *ins)
  7271. {
  7272. int ret;
  7273. struct btrfs_block_group_cache *block_group;
  7274. struct btrfs_space_info *space_info;
  7275. /*
  7276. * Mixed block groups will exclude before processing the log so we only
  7277. * need to do the exclude dance if this fs isn't mixed.
  7278. */
  7279. if (!btrfs_fs_incompat(root->fs_info, MIXED_GROUPS)) {
  7280. ret = __exclude_logged_extent(root, ins->objectid, ins->offset);
  7281. if (ret)
  7282. return ret;
  7283. }
  7284. block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
  7285. if (!block_group)
  7286. return -EINVAL;
  7287. space_info = block_group->space_info;
  7288. spin_lock(&space_info->lock);
  7289. spin_lock(&block_group->lock);
  7290. space_info->bytes_reserved += ins->offset;
  7291. block_group->reserved += ins->offset;
  7292. spin_unlock(&block_group->lock);
  7293. spin_unlock(&space_info->lock);
  7294. ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
  7295. 0, owner, offset, ins, 1);
  7296. btrfs_put_block_group(block_group);
  7297. return ret;
  7298. }
  7299. static struct extent_buffer *
  7300. btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  7301. u64 bytenr, int level)
  7302. {
  7303. struct extent_buffer *buf;
  7304. buf = btrfs_find_create_tree_block(root, bytenr);
  7305. if (IS_ERR(buf))
  7306. return buf;
  7307. btrfs_set_header_generation(buf, trans->transid);
  7308. btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
  7309. btrfs_tree_lock(buf);
  7310. clean_tree_block(trans, root->fs_info, buf);
  7311. clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
  7312. btrfs_set_lock_blocking(buf);
  7313. set_extent_buffer_uptodate(buf);
  7314. if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
  7315. buf->log_index = root->log_transid % 2;
  7316. /*
  7317. * we allow two log transactions at a time, use different
  7318. * EXENT bit to differentiate dirty pages.
  7319. */
  7320. if (buf->log_index == 0)
  7321. set_extent_dirty(&root->dirty_log_pages, buf->start,
  7322. buf->start + buf->len - 1, GFP_NOFS);
  7323. else
  7324. set_extent_new(&root->dirty_log_pages, buf->start,
  7325. buf->start + buf->len - 1);
  7326. } else {
  7327. buf->log_index = -1;
  7328. set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
  7329. buf->start + buf->len - 1, GFP_NOFS);
  7330. }
  7331. trans->dirty = true;
  7332. /* this returns a buffer locked for blocking */
  7333. return buf;
  7334. }
  7335. static struct btrfs_block_rsv *
  7336. use_block_rsv(struct btrfs_trans_handle *trans,
  7337. struct btrfs_root *root, u32 blocksize)
  7338. {
  7339. struct btrfs_block_rsv *block_rsv;
  7340. struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
  7341. int ret;
  7342. bool global_updated = false;
  7343. block_rsv = get_block_rsv(trans, root);
  7344. if (unlikely(block_rsv->size == 0))
  7345. goto try_reserve;
  7346. again:
  7347. ret = block_rsv_use_bytes(block_rsv, blocksize);
  7348. if (!ret)
  7349. return block_rsv;
  7350. if (block_rsv->failfast)
  7351. return ERR_PTR(ret);
  7352. if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
  7353. global_updated = true;
  7354. update_global_block_rsv(root->fs_info);
  7355. goto again;
  7356. }
  7357. if (btrfs_test_opt(root->fs_info, ENOSPC_DEBUG)) {
  7358. static DEFINE_RATELIMIT_STATE(_rs,
  7359. DEFAULT_RATELIMIT_INTERVAL * 10,
  7360. /*DEFAULT_RATELIMIT_BURST*/ 1);
  7361. if (__ratelimit(&_rs))
  7362. WARN(1, KERN_DEBUG
  7363. "BTRFS: block rsv returned %d\n", ret);
  7364. }
  7365. try_reserve:
  7366. ret = reserve_metadata_bytes(root, block_rsv, blocksize,
  7367. BTRFS_RESERVE_NO_FLUSH);
  7368. if (!ret)
  7369. return block_rsv;
  7370. /*
  7371. * If we couldn't reserve metadata bytes try and use some from
  7372. * the global reserve if its space type is the same as the global
  7373. * reservation.
  7374. */
  7375. if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
  7376. block_rsv->space_info == global_rsv->space_info) {
  7377. ret = block_rsv_use_bytes(global_rsv, blocksize);
  7378. if (!ret)
  7379. return global_rsv;
  7380. }
  7381. return ERR_PTR(ret);
  7382. }
  7383. static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
  7384. struct btrfs_block_rsv *block_rsv, u32 blocksize)
  7385. {
  7386. block_rsv_add_bytes(block_rsv, blocksize, 0);
  7387. block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
  7388. }
  7389. /*
  7390. * finds a free extent and does all the dirty work required for allocation
  7391. * returns the tree buffer or an ERR_PTR on error.
  7392. */
  7393. struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
  7394. struct btrfs_root *root,
  7395. u64 parent, u64 root_objectid,
  7396. struct btrfs_disk_key *key, int level,
  7397. u64 hint, u64 empty_size)
  7398. {
  7399. struct btrfs_key ins;
  7400. struct btrfs_block_rsv *block_rsv;
  7401. struct extent_buffer *buf;
  7402. struct btrfs_delayed_extent_op *extent_op;
  7403. u64 flags = 0;
  7404. int ret;
  7405. u32 blocksize = root->nodesize;
  7406. bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
  7407. SKINNY_METADATA);
  7408. #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
  7409. if (btrfs_is_testing(root->fs_info)) {
  7410. buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
  7411. level);
  7412. if (!IS_ERR(buf))
  7413. root->alloc_bytenr += blocksize;
  7414. return buf;
  7415. }
  7416. #endif
  7417. block_rsv = use_block_rsv(trans, root, blocksize);
  7418. if (IS_ERR(block_rsv))
  7419. return ERR_CAST(block_rsv);
  7420. ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
  7421. empty_size, hint, &ins, 0, 0);
  7422. if (ret)
  7423. goto out_unuse;
  7424. buf = btrfs_init_new_buffer(trans, root, ins.objectid, level);
  7425. if (IS_ERR(buf)) {
  7426. ret = PTR_ERR(buf);
  7427. goto out_free_reserved;
  7428. }
  7429. if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
  7430. if (parent == 0)
  7431. parent = ins.objectid;
  7432. flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
  7433. } else
  7434. BUG_ON(parent > 0);
  7435. if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
  7436. extent_op = btrfs_alloc_delayed_extent_op();
  7437. if (!extent_op) {
  7438. ret = -ENOMEM;
  7439. goto out_free_buf;
  7440. }
  7441. if (key)
  7442. memcpy(&extent_op->key, key, sizeof(extent_op->key));
  7443. else
  7444. memset(&extent_op->key, 0, sizeof(extent_op->key));
  7445. extent_op->flags_to_set = flags;
  7446. extent_op->update_key = skinny_metadata ? false : true;
  7447. extent_op->update_flags = true;
  7448. extent_op->is_data = false;
  7449. extent_op->level = level;
  7450. ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
  7451. ins.objectid, ins.offset,
  7452. parent, root_objectid, level,
  7453. BTRFS_ADD_DELAYED_EXTENT,
  7454. extent_op);
  7455. if (ret)
  7456. goto out_free_delayed;
  7457. }
  7458. return buf;
  7459. out_free_delayed:
  7460. btrfs_free_delayed_extent_op(extent_op);
  7461. out_free_buf:
  7462. free_extent_buffer(buf);
  7463. out_free_reserved:
  7464. btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 0);
  7465. out_unuse:
  7466. unuse_block_rsv(root->fs_info, block_rsv, blocksize);
  7467. return ERR_PTR(ret);
  7468. }
  7469. struct walk_control {
  7470. u64 refs[BTRFS_MAX_LEVEL];
  7471. u64 flags[BTRFS_MAX_LEVEL];
  7472. struct btrfs_key update_progress;
  7473. int stage;
  7474. int level;
  7475. int shared_level;
  7476. int update_ref;
  7477. int keep_locks;
  7478. int reada_slot;
  7479. int reada_count;
  7480. int for_reloc;
  7481. };
  7482. #define DROP_REFERENCE 1
  7483. #define UPDATE_BACKREF 2
  7484. static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
  7485. struct btrfs_root *root,
  7486. struct walk_control *wc,
  7487. struct btrfs_path *path)
  7488. {
  7489. u64 bytenr;
  7490. u64 generation;
  7491. u64 refs;
  7492. u64 flags;
  7493. u32 nritems;
  7494. struct btrfs_key key;
  7495. struct extent_buffer *eb;
  7496. int ret;
  7497. int slot;
  7498. int nread = 0;
  7499. if (path->slots[wc->level] < wc->reada_slot) {
  7500. wc->reada_count = wc->reada_count * 2 / 3;
  7501. wc->reada_count = max(wc->reada_count, 2);
  7502. } else {
  7503. wc->reada_count = wc->reada_count * 3 / 2;
  7504. wc->reada_count = min_t(int, wc->reada_count,
  7505. BTRFS_NODEPTRS_PER_BLOCK(root));
  7506. }
  7507. eb = path->nodes[wc->level];
  7508. nritems = btrfs_header_nritems(eb);
  7509. for (slot = path->slots[wc->level]; slot < nritems; slot++) {
  7510. if (nread >= wc->reada_count)
  7511. break;
  7512. cond_resched();
  7513. bytenr = btrfs_node_blockptr(eb, slot);
  7514. generation = btrfs_node_ptr_generation(eb, slot);
  7515. if (slot == path->slots[wc->level])
  7516. goto reada;
  7517. if (wc->stage == UPDATE_BACKREF &&
  7518. generation <= root->root_key.offset)
  7519. continue;
  7520. /* We don't lock the tree block, it's OK to be racy here */
  7521. ret = btrfs_lookup_extent_info(trans, root, bytenr,
  7522. wc->level - 1, 1, &refs,
  7523. &flags);
  7524. /* We don't care about errors in readahead. */
  7525. if (ret < 0)
  7526. continue;
  7527. BUG_ON(refs == 0);
  7528. if (wc->stage == DROP_REFERENCE) {
  7529. if (refs == 1)
  7530. goto reada;
  7531. if (wc->level == 1 &&
  7532. (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7533. continue;
  7534. if (!wc->update_ref ||
  7535. generation <= root->root_key.offset)
  7536. continue;
  7537. btrfs_node_key_to_cpu(eb, &key, slot);
  7538. ret = btrfs_comp_cpu_keys(&key,
  7539. &wc->update_progress);
  7540. if (ret < 0)
  7541. continue;
  7542. } else {
  7543. if (wc->level == 1 &&
  7544. (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7545. continue;
  7546. }
  7547. reada:
  7548. readahead_tree_block(root, bytenr);
  7549. nread++;
  7550. }
  7551. wc->reada_slot = slot;
  7552. }
  7553. static int account_leaf_items(struct btrfs_trans_handle *trans,
  7554. struct btrfs_root *root,
  7555. struct extent_buffer *eb)
  7556. {
  7557. int nr = btrfs_header_nritems(eb);
  7558. int i, extent_type, ret;
  7559. struct btrfs_key key;
  7560. struct btrfs_file_extent_item *fi;
  7561. u64 bytenr, num_bytes;
  7562. /* We can be called directly from walk_up_proc() */
  7563. if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &root->fs_info->flags))
  7564. return 0;
  7565. for (i = 0; i < nr; i++) {
  7566. btrfs_item_key_to_cpu(eb, &key, i);
  7567. if (key.type != BTRFS_EXTENT_DATA_KEY)
  7568. continue;
  7569. fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
  7570. /* filter out non qgroup-accountable extents */
  7571. extent_type = btrfs_file_extent_type(eb, fi);
  7572. if (extent_type == BTRFS_FILE_EXTENT_INLINE)
  7573. continue;
  7574. bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
  7575. if (!bytenr)
  7576. continue;
  7577. num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
  7578. ret = btrfs_qgroup_insert_dirty_extent(trans, root->fs_info,
  7579. bytenr, num_bytes, GFP_NOFS);
  7580. if (ret)
  7581. return ret;
  7582. }
  7583. return 0;
  7584. }
  7585. /*
  7586. * Walk up the tree from the bottom, freeing leaves and any interior
  7587. * nodes which have had all slots visited. If a node (leaf or
  7588. * interior) is freed, the node above it will have it's slot
  7589. * incremented. The root node will never be freed.
  7590. *
  7591. * At the end of this function, we should have a path which has all
  7592. * slots incremented to the next position for a search. If we need to
  7593. * read a new node it will be NULL and the node above it will have the
  7594. * correct slot selected for a later read.
  7595. *
  7596. * If we increment the root nodes slot counter past the number of
  7597. * elements, 1 is returned to signal completion of the search.
  7598. */
  7599. static int adjust_slots_upwards(struct btrfs_root *root,
  7600. struct btrfs_path *path, int root_level)
  7601. {
  7602. int level = 0;
  7603. int nr, slot;
  7604. struct extent_buffer *eb;
  7605. if (root_level == 0)
  7606. return 1;
  7607. while (level <= root_level) {
  7608. eb = path->nodes[level];
  7609. nr = btrfs_header_nritems(eb);
  7610. path->slots[level]++;
  7611. slot = path->slots[level];
  7612. if (slot >= nr || level == 0) {
  7613. /*
  7614. * Don't free the root - we will detect this
  7615. * condition after our loop and return a
  7616. * positive value for caller to stop walking the tree.
  7617. */
  7618. if (level != root_level) {
  7619. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7620. path->locks[level] = 0;
  7621. free_extent_buffer(eb);
  7622. path->nodes[level] = NULL;
  7623. path->slots[level] = 0;
  7624. }
  7625. } else {
  7626. /*
  7627. * We have a valid slot to walk back down
  7628. * from. Stop here so caller can process these
  7629. * new nodes.
  7630. */
  7631. break;
  7632. }
  7633. level++;
  7634. }
  7635. eb = path->nodes[root_level];
  7636. if (path->slots[root_level] >= btrfs_header_nritems(eb))
  7637. return 1;
  7638. return 0;
  7639. }
  7640. /*
  7641. * root_eb is the subtree root and is locked before this function is called.
  7642. */
  7643. static int account_shared_subtree(struct btrfs_trans_handle *trans,
  7644. struct btrfs_root *root,
  7645. struct extent_buffer *root_eb,
  7646. u64 root_gen,
  7647. int root_level)
  7648. {
  7649. int ret = 0;
  7650. int level;
  7651. struct extent_buffer *eb = root_eb;
  7652. struct btrfs_path *path = NULL;
  7653. BUG_ON(root_level < 0 || root_level > BTRFS_MAX_LEVEL);
  7654. BUG_ON(root_eb == NULL);
  7655. if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &root->fs_info->flags))
  7656. return 0;
  7657. if (!extent_buffer_uptodate(root_eb)) {
  7658. ret = btrfs_read_buffer(root_eb, root_gen);
  7659. if (ret)
  7660. goto out;
  7661. }
  7662. if (root_level == 0) {
  7663. ret = account_leaf_items(trans, root, root_eb);
  7664. goto out;
  7665. }
  7666. path = btrfs_alloc_path();
  7667. if (!path)
  7668. return -ENOMEM;
  7669. /*
  7670. * Walk down the tree. Missing extent blocks are filled in as
  7671. * we go. Metadata is accounted every time we read a new
  7672. * extent block.
  7673. *
  7674. * When we reach a leaf, we account for file extent items in it,
  7675. * walk back up the tree (adjusting slot pointers as we go)
  7676. * and restart the search process.
  7677. */
  7678. extent_buffer_get(root_eb); /* For path */
  7679. path->nodes[root_level] = root_eb;
  7680. path->slots[root_level] = 0;
  7681. path->locks[root_level] = 0; /* so release_path doesn't try to unlock */
  7682. walk_down:
  7683. level = root_level;
  7684. while (level >= 0) {
  7685. if (path->nodes[level] == NULL) {
  7686. int parent_slot;
  7687. u64 child_gen;
  7688. u64 child_bytenr;
  7689. /* We need to get child blockptr/gen from
  7690. * parent before we can read it. */
  7691. eb = path->nodes[level + 1];
  7692. parent_slot = path->slots[level + 1];
  7693. child_bytenr = btrfs_node_blockptr(eb, parent_slot);
  7694. child_gen = btrfs_node_ptr_generation(eb, parent_slot);
  7695. eb = read_tree_block(root, child_bytenr, child_gen);
  7696. if (IS_ERR(eb)) {
  7697. ret = PTR_ERR(eb);
  7698. goto out;
  7699. } else if (!extent_buffer_uptodate(eb)) {
  7700. free_extent_buffer(eb);
  7701. ret = -EIO;
  7702. goto out;
  7703. }
  7704. path->nodes[level] = eb;
  7705. path->slots[level] = 0;
  7706. btrfs_tree_read_lock(eb);
  7707. btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
  7708. path->locks[level] = BTRFS_READ_LOCK_BLOCKING;
  7709. ret = btrfs_qgroup_insert_dirty_extent(trans,
  7710. root->fs_info, child_bytenr,
  7711. root->nodesize, GFP_NOFS);
  7712. if (ret)
  7713. goto out;
  7714. }
  7715. if (level == 0) {
  7716. ret = account_leaf_items(trans, root, path->nodes[level]);
  7717. if (ret)
  7718. goto out;
  7719. /* Nonzero return here means we completed our search */
  7720. ret = adjust_slots_upwards(root, path, root_level);
  7721. if (ret)
  7722. break;
  7723. /* Restart search with new slots */
  7724. goto walk_down;
  7725. }
  7726. level--;
  7727. }
  7728. ret = 0;
  7729. out:
  7730. btrfs_free_path(path);
  7731. return ret;
  7732. }
  7733. /*
  7734. * helper to process tree block while walking down the tree.
  7735. *
  7736. * when wc->stage == UPDATE_BACKREF, this function updates
  7737. * back refs for pointers in the block.
  7738. *
  7739. * NOTE: return value 1 means we should stop walking down.
  7740. */
  7741. static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
  7742. struct btrfs_root *root,
  7743. struct btrfs_path *path,
  7744. struct walk_control *wc, int lookup_info)
  7745. {
  7746. int level = wc->level;
  7747. struct extent_buffer *eb = path->nodes[level];
  7748. u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  7749. int ret;
  7750. if (wc->stage == UPDATE_BACKREF &&
  7751. btrfs_header_owner(eb) != root->root_key.objectid)
  7752. return 1;
  7753. /*
  7754. * when reference count of tree block is 1, it won't increase
  7755. * again. once full backref flag is set, we never clear it.
  7756. */
  7757. if (lookup_info &&
  7758. ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
  7759. (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
  7760. BUG_ON(!path->locks[level]);
  7761. ret = btrfs_lookup_extent_info(trans, root,
  7762. eb->start, level, 1,
  7763. &wc->refs[level],
  7764. &wc->flags[level]);
  7765. BUG_ON(ret == -ENOMEM);
  7766. if (ret)
  7767. return ret;
  7768. BUG_ON(wc->refs[level] == 0);
  7769. }
  7770. if (wc->stage == DROP_REFERENCE) {
  7771. if (wc->refs[level] > 1)
  7772. return 1;
  7773. if (path->locks[level] && !wc->keep_locks) {
  7774. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7775. path->locks[level] = 0;
  7776. }
  7777. return 0;
  7778. }
  7779. /* wc->stage == UPDATE_BACKREF */
  7780. if (!(wc->flags[level] & flag)) {
  7781. BUG_ON(!path->locks[level]);
  7782. ret = btrfs_inc_ref(trans, root, eb, 1);
  7783. BUG_ON(ret); /* -ENOMEM */
  7784. ret = btrfs_dec_ref(trans, root, eb, 0);
  7785. BUG_ON(ret); /* -ENOMEM */
  7786. ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
  7787. eb->len, flag,
  7788. btrfs_header_level(eb), 0);
  7789. BUG_ON(ret); /* -ENOMEM */
  7790. wc->flags[level] |= flag;
  7791. }
  7792. /*
  7793. * the block is shared by multiple trees, so it's not good to
  7794. * keep the tree lock
  7795. */
  7796. if (path->locks[level] && level > 0) {
  7797. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7798. path->locks[level] = 0;
  7799. }
  7800. return 0;
  7801. }
  7802. /*
  7803. * helper to process tree block pointer.
  7804. *
  7805. * when wc->stage == DROP_REFERENCE, this function checks
  7806. * reference count of the block pointed to. if the block
  7807. * is shared and we need update back refs for the subtree
  7808. * rooted at the block, this function changes wc->stage to
  7809. * UPDATE_BACKREF. if the block is shared and there is no
  7810. * need to update back, this function drops the reference
  7811. * to the block.
  7812. *
  7813. * NOTE: return value 1 means we should stop walking down.
  7814. */
  7815. static noinline int do_walk_down(struct btrfs_trans_handle *trans,
  7816. struct btrfs_root *root,
  7817. struct btrfs_path *path,
  7818. struct walk_control *wc, int *lookup_info)
  7819. {
  7820. u64 bytenr;
  7821. u64 generation;
  7822. u64 parent;
  7823. u32 blocksize;
  7824. struct btrfs_key key;
  7825. struct extent_buffer *next;
  7826. int level = wc->level;
  7827. int reada = 0;
  7828. int ret = 0;
  7829. bool need_account = false;
  7830. generation = btrfs_node_ptr_generation(path->nodes[level],
  7831. path->slots[level]);
  7832. /*
  7833. * if the lower level block was created before the snapshot
  7834. * was created, we know there is no need to update back refs
  7835. * for the subtree
  7836. */
  7837. if (wc->stage == UPDATE_BACKREF &&
  7838. generation <= root->root_key.offset) {
  7839. *lookup_info = 1;
  7840. return 1;
  7841. }
  7842. bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
  7843. blocksize = root->nodesize;
  7844. next = btrfs_find_tree_block(root->fs_info, bytenr);
  7845. if (!next) {
  7846. next = btrfs_find_create_tree_block(root, bytenr);
  7847. if (IS_ERR(next))
  7848. return PTR_ERR(next);
  7849. btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
  7850. level - 1);
  7851. reada = 1;
  7852. }
  7853. btrfs_tree_lock(next);
  7854. btrfs_set_lock_blocking(next);
  7855. ret = btrfs_lookup_extent_info(trans, root, bytenr, level - 1, 1,
  7856. &wc->refs[level - 1],
  7857. &wc->flags[level - 1]);
  7858. if (ret < 0)
  7859. goto out_unlock;
  7860. if (unlikely(wc->refs[level - 1] == 0)) {
  7861. btrfs_err(root->fs_info, "Missing references.");
  7862. ret = -EIO;
  7863. goto out_unlock;
  7864. }
  7865. *lookup_info = 0;
  7866. if (wc->stage == DROP_REFERENCE) {
  7867. if (wc->refs[level - 1] > 1) {
  7868. need_account = true;
  7869. if (level == 1 &&
  7870. (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7871. goto skip;
  7872. if (!wc->update_ref ||
  7873. generation <= root->root_key.offset)
  7874. goto skip;
  7875. btrfs_node_key_to_cpu(path->nodes[level], &key,
  7876. path->slots[level]);
  7877. ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
  7878. if (ret < 0)
  7879. goto skip;
  7880. wc->stage = UPDATE_BACKREF;
  7881. wc->shared_level = level - 1;
  7882. }
  7883. } else {
  7884. if (level == 1 &&
  7885. (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7886. goto skip;
  7887. }
  7888. if (!btrfs_buffer_uptodate(next, generation, 0)) {
  7889. btrfs_tree_unlock(next);
  7890. free_extent_buffer(next);
  7891. next = NULL;
  7892. *lookup_info = 1;
  7893. }
  7894. if (!next) {
  7895. if (reada && level == 1)
  7896. reada_walk_down(trans, root, wc, path);
  7897. next = read_tree_block(root, bytenr, generation);
  7898. if (IS_ERR(next)) {
  7899. return PTR_ERR(next);
  7900. } else if (!extent_buffer_uptodate(next)) {
  7901. free_extent_buffer(next);
  7902. return -EIO;
  7903. }
  7904. btrfs_tree_lock(next);
  7905. btrfs_set_lock_blocking(next);
  7906. }
  7907. level--;
  7908. ASSERT(level == btrfs_header_level(next));
  7909. if (level != btrfs_header_level(next)) {
  7910. btrfs_err(root->fs_info, "mismatched level");
  7911. ret = -EIO;
  7912. goto out_unlock;
  7913. }
  7914. path->nodes[level] = next;
  7915. path->slots[level] = 0;
  7916. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7917. wc->level = level;
  7918. if (wc->level == 1)
  7919. wc->reada_slot = 0;
  7920. return 0;
  7921. skip:
  7922. wc->refs[level - 1] = 0;
  7923. wc->flags[level - 1] = 0;
  7924. if (wc->stage == DROP_REFERENCE) {
  7925. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
  7926. parent = path->nodes[level]->start;
  7927. } else {
  7928. ASSERT(root->root_key.objectid ==
  7929. btrfs_header_owner(path->nodes[level]));
  7930. if (root->root_key.objectid !=
  7931. btrfs_header_owner(path->nodes[level])) {
  7932. btrfs_err(root->fs_info,
  7933. "mismatched block owner");
  7934. ret = -EIO;
  7935. goto out_unlock;
  7936. }
  7937. parent = 0;
  7938. }
  7939. if (need_account) {
  7940. ret = account_shared_subtree(trans, root, next,
  7941. generation, level - 1);
  7942. if (ret) {
  7943. btrfs_err_rl(root->fs_info,
  7944. "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
  7945. ret);
  7946. }
  7947. }
  7948. ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
  7949. root->root_key.objectid, level - 1, 0);
  7950. if (ret)
  7951. goto out_unlock;
  7952. }
  7953. *lookup_info = 1;
  7954. ret = 1;
  7955. out_unlock:
  7956. btrfs_tree_unlock(next);
  7957. free_extent_buffer(next);
  7958. return ret;
  7959. }
  7960. /*
  7961. * helper to process tree block while walking up the tree.
  7962. *
  7963. * when wc->stage == DROP_REFERENCE, this function drops
  7964. * reference count on the block.
  7965. *
  7966. * when wc->stage == UPDATE_BACKREF, this function changes
  7967. * wc->stage back to DROP_REFERENCE if we changed wc->stage
  7968. * to UPDATE_BACKREF previously while processing the block.
  7969. *
  7970. * NOTE: return value 1 means we should stop walking up.
  7971. */
  7972. static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
  7973. struct btrfs_root *root,
  7974. struct btrfs_path *path,
  7975. struct walk_control *wc)
  7976. {
  7977. int ret;
  7978. int level = wc->level;
  7979. struct extent_buffer *eb = path->nodes[level];
  7980. u64 parent = 0;
  7981. if (wc->stage == UPDATE_BACKREF) {
  7982. BUG_ON(wc->shared_level < level);
  7983. if (level < wc->shared_level)
  7984. goto out;
  7985. ret = find_next_key(path, level + 1, &wc->update_progress);
  7986. if (ret > 0)
  7987. wc->update_ref = 0;
  7988. wc->stage = DROP_REFERENCE;
  7989. wc->shared_level = -1;
  7990. path->slots[level] = 0;
  7991. /*
  7992. * check reference count again if the block isn't locked.
  7993. * we should start walking down the tree again if reference
  7994. * count is one.
  7995. */
  7996. if (!path->locks[level]) {
  7997. BUG_ON(level == 0);
  7998. btrfs_tree_lock(eb);
  7999. btrfs_set_lock_blocking(eb);
  8000. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  8001. ret = btrfs_lookup_extent_info(trans, root,
  8002. eb->start, level, 1,
  8003. &wc->refs[level],
  8004. &wc->flags[level]);
  8005. if (ret < 0) {
  8006. btrfs_tree_unlock_rw(eb, path->locks[level]);
  8007. path->locks[level] = 0;
  8008. return ret;
  8009. }
  8010. BUG_ON(wc->refs[level] == 0);
  8011. if (wc->refs[level] == 1) {
  8012. btrfs_tree_unlock_rw(eb, path->locks[level]);
  8013. path->locks[level] = 0;
  8014. return 1;
  8015. }
  8016. }
  8017. }
  8018. /* wc->stage == DROP_REFERENCE */
  8019. BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
  8020. if (wc->refs[level] == 1) {
  8021. if (level == 0) {
  8022. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  8023. ret = btrfs_dec_ref(trans, root, eb, 1);
  8024. else
  8025. ret = btrfs_dec_ref(trans, root, eb, 0);
  8026. BUG_ON(ret); /* -ENOMEM */
  8027. ret = account_leaf_items(trans, root, eb);
  8028. if (ret) {
  8029. btrfs_err_rl(root->fs_info,
  8030. "error %d accounting leaf items. Quota is out of sync, rescan required.",
  8031. ret);
  8032. }
  8033. }
  8034. /* make block locked assertion in clean_tree_block happy */
  8035. if (!path->locks[level] &&
  8036. btrfs_header_generation(eb) == trans->transid) {
  8037. btrfs_tree_lock(eb);
  8038. btrfs_set_lock_blocking(eb);
  8039. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  8040. }
  8041. clean_tree_block(trans, root->fs_info, eb);
  8042. }
  8043. if (eb == root->node) {
  8044. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  8045. parent = eb->start;
  8046. else
  8047. BUG_ON(root->root_key.objectid !=
  8048. btrfs_header_owner(eb));
  8049. } else {
  8050. if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  8051. parent = path->nodes[level + 1]->start;
  8052. else
  8053. BUG_ON(root->root_key.objectid !=
  8054. btrfs_header_owner(path->nodes[level + 1]));
  8055. }
  8056. btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
  8057. out:
  8058. wc->refs[level] = 0;
  8059. wc->flags[level] = 0;
  8060. return 0;
  8061. }
  8062. static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
  8063. struct btrfs_root *root,
  8064. struct btrfs_path *path,
  8065. struct walk_control *wc)
  8066. {
  8067. int level = wc->level;
  8068. int lookup_info = 1;
  8069. int ret;
  8070. while (level >= 0) {
  8071. ret = walk_down_proc(trans, root, path, wc, lookup_info);
  8072. if (ret > 0)
  8073. break;
  8074. if (level == 0)
  8075. break;
  8076. if (path->slots[level] >=
  8077. btrfs_header_nritems(path->nodes[level]))
  8078. break;
  8079. ret = do_walk_down(trans, root, path, wc, &lookup_info);
  8080. if (ret > 0) {
  8081. path->slots[level]++;
  8082. continue;
  8083. } else if (ret < 0)
  8084. return ret;
  8085. level = wc->level;
  8086. }
  8087. return 0;
  8088. }
  8089. static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
  8090. struct btrfs_root *root,
  8091. struct btrfs_path *path,
  8092. struct walk_control *wc, int max_level)
  8093. {
  8094. int level = wc->level;
  8095. int ret;
  8096. path->slots[level] = btrfs_header_nritems(path->nodes[level]);
  8097. while (level < max_level && path->nodes[level]) {
  8098. wc->level = level;
  8099. if (path->slots[level] + 1 <
  8100. btrfs_header_nritems(path->nodes[level])) {
  8101. path->slots[level]++;
  8102. return 0;
  8103. } else {
  8104. ret = walk_up_proc(trans, root, path, wc);
  8105. if (ret > 0)
  8106. return 0;
  8107. if (path->locks[level]) {
  8108. btrfs_tree_unlock_rw(path->nodes[level],
  8109. path->locks[level]);
  8110. path->locks[level] = 0;
  8111. }
  8112. free_extent_buffer(path->nodes[level]);
  8113. path->nodes[level] = NULL;
  8114. level++;
  8115. }
  8116. }
  8117. return 1;
  8118. }
  8119. /*
  8120. * drop a subvolume tree.
  8121. *
  8122. * this function traverses the tree freeing any blocks that only
  8123. * referenced by the tree.
  8124. *
  8125. * when a shared tree block is found. this function decreases its
  8126. * reference count by one. if update_ref is true, this function
  8127. * also make sure backrefs for the shared block and all lower level
  8128. * blocks are properly updated.
  8129. *
  8130. * If called with for_reloc == 0, may exit early with -EAGAIN
  8131. */
  8132. int btrfs_drop_snapshot(struct btrfs_root *root,
  8133. struct btrfs_block_rsv *block_rsv, int update_ref,
  8134. int for_reloc)
  8135. {
  8136. struct btrfs_fs_info *fs_info = root->fs_info;
  8137. struct btrfs_path *path;
  8138. struct btrfs_trans_handle *trans;
  8139. struct btrfs_root *tree_root = fs_info->tree_root;
  8140. struct btrfs_root_item *root_item = &root->root_item;
  8141. struct walk_control *wc;
  8142. struct btrfs_key key;
  8143. int err = 0;
  8144. int ret;
  8145. int level;
  8146. bool root_dropped = false;
  8147. btrfs_debug(fs_info, "Drop subvolume %llu", root->objectid);
  8148. path = btrfs_alloc_path();
  8149. if (!path) {
  8150. err = -ENOMEM;
  8151. goto out;
  8152. }
  8153. wc = kzalloc(sizeof(*wc), GFP_NOFS);
  8154. if (!wc) {
  8155. btrfs_free_path(path);
  8156. err = -ENOMEM;
  8157. goto out;
  8158. }
  8159. trans = btrfs_start_transaction(tree_root, 0);
  8160. if (IS_ERR(trans)) {
  8161. err = PTR_ERR(trans);
  8162. goto out_free;
  8163. }
  8164. if (block_rsv)
  8165. trans->block_rsv = block_rsv;
  8166. if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
  8167. level = btrfs_header_level(root->node);
  8168. path->nodes[level] = btrfs_lock_root_node(root);
  8169. btrfs_set_lock_blocking(path->nodes[level]);
  8170. path->slots[level] = 0;
  8171. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  8172. memset(&wc->update_progress, 0,
  8173. sizeof(wc->update_progress));
  8174. } else {
  8175. btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
  8176. memcpy(&wc->update_progress, &key,
  8177. sizeof(wc->update_progress));
  8178. level = root_item->drop_level;
  8179. BUG_ON(level == 0);
  8180. path->lowest_level = level;
  8181. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  8182. path->lowest_level = 0;
  8183. if (ret < 0) {
  8184. err = ret;
  8185. goto out_end_trans;
  8186. }
  8187. WARN_ON(ret > 0);
  8188. /*
  8189. * unlock our path, this is safe because only this
  8190. * function is allowed to delete this snapshot
  8191. */
  8192. btrfs_unlock_up_safe(path, 0);
  8193. level = btrfs_header_level(root->node);
  8194. while (1) {
  8195. btrfs_tree_lock(path->nodes[level]);
  8196. btrfs_set_lock_blocking(path->nodes[level]);
  8197. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  8198. ret = btrfs_lookup_extent_info(trans, root,
  8199. path->nodes[level]->start,
  8200. level, 1, &wc->refs[level],
  8201. &wc->flags[level]);
  8202. if (ret < 0) {
  8203. err = ret;
  8204. goto out_end_trans;
  8205. }
  8206. BUG_ON(wc->refs[level] == 0);
  8207. if (level == root_item->drop_level)
  8208. break;
  8209. btrfs_tree_unlock(path->nodes[level]);
  8210. path->locks[level] = 0;
  8211. WARN_ON(wc->refs[level] != 1);
  8212. level--;
  8213. }
  8214. }
  8215. wc->level = level;
  8216. wc->shared_level = -1;
  8217. wc->stage = DROP_REFERENCE;
  8218. wc->update_ref = update_ref;
  8219. wc->keep_locks = 0;
  8220. wc->for_reloc = for_reloc;
  8221. wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
  8222. while (1) {
  8223. ret = walk_down_tree(trans, root, path, wc);
  8224. if (ret < 0) {
  8225. err = ret;
  8226. break;
  8227. }
  8228. ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
  8229. if (ret < 0) {
  8230. err = ret;
  8231. break;
  8232. }
  8233. if (ret > 0) {
  8234. BUG_ON(wc->stage != DROP_REFERENCE);
  8235. break;
  8236. }
  8237. if (wc->stage == DROP_REFERENCE) {
  8238. level = wc->level;
  8239. btrfs_node_key(path->nodes[level],
  8240. &root_item->drop_progress,
  8241. path->slots[level]);
  8242. root_item->drop_level = level;
  8243. }
  8244. BUG_ON(wc->level == 0);
  8245. if (btrfs_should_end_transaction(trans, tree_root) ||
  8246. (!for_reloc && btrfs_need_cleaner_sleep(root))) {
  8247. ret = btrfs_update_root(trans, tree_root,
  8248. &root->root_key,
  8249. root_item);
  8250. if (ret) {
  8251. btrfs_abort_transaction(trans, ret);
  8252. err = ret;
  8253. goto out_end_trans;
  8254. }
  8255. btrfs_end_transaction_throttle(trans, tree_root);
  8256. if (!for_reloc && btrfs_need_cleaner_sleep(root)) {
  8257. btrfs_debug(fs_info,
  8258. "drop snapshot early exit");
  8259. err = -EAGAIN;
  8260. goto out_free;
  8261. }
  8262. trans = btrfs_start_transaction(tree_root, 0);
  8263. if (IS_ERR(trans)) {
  8264. err = PTR_ERR(trans);
  8265. goto out_free;
  8266. }
  8267. if (block_rsv)
  8268. trans->block_rsv = block_rsv;
  8269. }
  8270. }
  8271. btrfs_release_path(path);
  8272. if (err)
  8273. goto out_end_trans;
  8274. ret = btrfs_del_root(trans, tree_root, &root->root_key);
  8275. if (ret) {
  8276. btrfs_abort_transaction(trans, ret);
  8277. err = ret;
  8278. goto out_end_trans;
  8279. }
  8280. if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
  8281. ret = btrfs_find_root(tree_root, &root->root_key, path,
  8282. NULL, NULL);
  8283. if (ret < 0) {
  8284. btrfs_abort_transaction(trans, ret);
  8285. err = ret;
  8286. goto out_end_trans;
  8287. } else if (ret > 0) {
  8288. /* if we fail to delete the orphan item this time
  8289. * around, it'll get picked up the next time.
  8290. *
  8291. * The most common failure here is just -ENOENT.
  8292. */
  8293. btrfs_del_orphan_item(trans, tree_root,
  8294. root->root_key.objectid);
  8295. }
  8296. }
  8297. if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
  8298. btrfs_add_dropped_root(trans, root);
  8299. } else {
  8300. free_extent_buffer(root->node);
  8301. free_extent_buffer(root->commit_root);
  8302. btrfs_put_fs_root(root);
  8303. }
  8304. root_dropped = true;
  8305. out_end_trans:
  8306. btrfs_end_transaction_throttle(trans, tree_root);
  8307. out_free:
  8308. kfree(wc);
  8309. btrfs_free_path(path);
  8310. out:
  8311. /*
  8312. * So if we need to stop dropping the snapshot for whatever reason we
  8313. * need to make sure to add it back to the dead root list so that we
  8314. * keep trying to do the work later. This also cleans up roots if we
  8315. * don't have it in the radix (like when we recover after a power fail
  8316. * or unmount) so we don't leak memory.
  8317. */
  8318. if (!for_reloc && root_dropped == false)
  8319. btrfs_add_dead_root(root);
  8320. if (err && err != -EAGAIN)
  8321. btrfs_handle_fs_error(fs_info, err, NULL);
  8322. return err;
  8323. }
  8324. /*
  8325. * drop subtree rooted at tree block 'node'.
  8326. *
  8327. * NOTE: this function will unlock and release tree block 'node'
  8328. * only used by relocation code
  8329. */
  8330. int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
  8331. struct btrfs_root *root,
  8332. struct extent_buffer *node,
  8333. struct extent_buffer *parent)
  8334. {
  8335. struct btrfs_path *path;
  8336. struct walk_control *wc;
  8337. int level;
  8338. int parent_level;
  8339. int ret = 0;
  8340. int wret;
  8341. BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
  8342. path = btrfs_alloc_path();
  8343. if (!path)
  8344. return -ENOMEM;
  8345. wc = kzalloc(sizeof(*wc), GFP_NOFS);
  8346. if (!wc) {
  8347. btrfs_free_path(path);
  8348. return -ENOMEM;
  8349. }
  8350. btrfs_assert_tree_locked(parent);
  8351. parent_level = btrfs_header_level(parent);
  8352. extent_buffer_get(parent);
  8353. path->nodes[parent_level] = parent;
  8354. path->slots[parent_level] = btrfs_header_nritems(parent);
  8355. btrfs_assert_tree_locked(node);
  8356. level = btrfs_header_level(node);
  8357. path->nodes[level] = node;
  8358. path->slots[level] = 0;
  8359. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  8360. wc->refs[parent_level] = 1;
  8361. wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  8362. wc->level = level;
  8363. wc->shared_level = -1;
  8364. wc->stage = DROP_REFERENCE;
  8365. wc->update_ref = 0;
  8366. wc->keep_locks = 1;
  8367. wc->for_reloc = 1;
  8368. wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
  8369. while (1) {
  8370. wret = walk_down_tree(trans, root, path, wc);
  8371. if (wret < 0) {
  8372. ret = wret;
  8373. break;
  8374. }
  8375. wret = walk_up_tree(trans, root, path, wc, parent_level);
  8376. if (wret < 0)
  8377. ret = wret;
  8378. if (wret != 0)
  8379. break;
  8380. }
  8381. kfree(wc);
  8382. btrfs_free_path(path);
  8383. return ret;
  8384. }
  8385. static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
  8386. {
  8387. u64 num_devices;
  8388. u64 stripped;
  8389. /*
  8390. * if restripe for this chunk_type is on pick target profile and
  8391. * return, otherwise do the usual balance
  8392. */
  8393. stripped = get_restripe_target(root->fs_info, flags);
  8394. if (stripped)
  8395. return extended_to_chunk(stripped);
  8396. num_devices = root->fs_info->fs_devices->rw_devices;
  8397. stripped = BTRFS_BLOCK_GROUP_RAID0 |
  8398. BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
  8399. BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
  8400. if (num_devices == 1) {
  8401. stripped |= BTRFS_BLOCK_GROUP_DUP;
  8402. stripped = flags & ~stripped;
  8403. /* turn raid0 into single device chunks */
  8404. if (flags & BTRFS_BLOCK_GROUP_RAID0)
  8405. return stripped;
  8406. /* turn mirroring into duplication */
  8407. if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
  8408. BTRFS_BLOCK_GROUP_RAID10))
  8409. return stripped | BTRFS_BLOCK_GROUP_DUP;
  8410. } else {
  8411. /* they already had raid on here, just return */
  8412. if (flags & stripped)
  8413. return flags;
  8414. stripped |= BTRFS_BLOCK_GROUP_DUP;
  8415. stripped = flags & ~stripped;
  8416. /* switch duplicated blocks with raid1 */
  8417. if (flags & BTRFS_BLOCK_GROUP_DUP)
  8418. return stripped | BTRFS_BLOCK_GROUP_RAID1;
  8419. /* this is drive concat, leave it alone */
  8420. }
  8421. return flags;
  8422. }
  8423. static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
  8424. {
  8425. struct btrfs_space_info *sinfo = cache->space_info;
  8426. u64 num_bytes;
  8427. u64 min_allocable_bytes;
  8428. int ret = -ENOSPC;
  8429. /*
  8430. * We need some metadata space and system metadata space for
  8431. * allocating chunks in some corner cases until we force to set
  8432. * it to be readonly.
  8433. */
  8434. if ((sinfo->flags &
  8435. (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
  8436. !force)
  8437. min_allocable_bytes = SZ_1M;
  8438. else
  8439. min_allocable_bytes = 0;
  8440. spin_lock(&sinfo->lock);
  8441. spin_lock(&cache->lock);
  8442. if (cache->ro) {
  8443. cache->ro++;
  8444. ret = 0;
  8445. goto out;
  8446. }
  8447. num_bytes = cache->key.offset - cache->reserved - cache->pinned -
  8448. cache->bytes_super - btrfs_block_group_used(&cache->item);
  8449. if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
  8450. sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
  8451. min_allocable_bytes <= sinfo->total_bytes) {
  8452. sinfo->bytes_readonly += num_bytes;
  8453. cache->ro++;
  8454. list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
  8455. ret = 0;
  8456. }
  8457. out:
  8458. spin_unlock(&cache->lock);
  8459. spin_unlock(&sinfo->lock);
  8460. return ret;
  8461. }
  8462. int btrfs_inc_block_group_ro(struct btrfs_root *root,
  8463. struct btrfs_block_group_cache *cache)
  8464. {
  8465. struct btrfs_trans_handle *trans;
  8466. u64 alloc_flags;
  8467. int ret;
  8468. again:
  8469. trans = btrfs_join_transaction(root);
  8470. if (IS_ERR(trans))
  8471. return PTR_ERR(trans);
  8472. /*
  8473. * we're not allowed to set block groups readonly after the dirty
  8474. * block groups cache has started writing. If it already started,
  8475. * back off and let this transaction commit
  8476. */
  8477. mutex_lock(&root->fs_info->ro_block_group_mutex);
  8478. if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
  8479. u64 transid = trans->transid;
  8480. mutex_unlock(&root->fs_info->ro_block_group_mutex);
  8481. btrfs_end_transaction(trans, root);
  8482. ret = btrfs_wait_for_commit(root, transid);
  8483. if (ret)
  8484. return ret;
  8485. goto again;
  8486. }
  8487. /*
  8488. * if we are changing raid levels, try to allocate a corresponding
  8489. * block group with the new raid level.
  8490. */
  8491. alloc_flags = update_block_group_flags(root, cache->flags);
  8492. if (alloc_flags != cache->flags) {
  8493. ret = do_chunk_alloc(trans, root, alloc_flags,
  8494. CHUNK_ALLOC_FORCE);
  8495. /*
  8496. * ENOSPC is allowed here, we may have enough space
  8497. * already allocated at the new raid level to
  8498. * carry on
  8499. */
  8500. if (ret == -ENOSPC)
  8501. ret = 0;
  8502. if (ret < 0)
  8503. goto out;
  8504. }
  8505. ret = inc_block_group_ro(cache, 0);
  8506. if (!ret)
  8507. goto out;
  8508. alloc_flags = get_alloc_profile(root, cache->space_info->flags);
  8509. ret = do_chunk_alloc(trans, root, alloc_flags,
  8510. CHUNK_ALLOC_FORCE);
  8511. if (ret < 0)
  8512. goto out;
  8513. ret = inc_block_group_ro(cache, 0);
  8514. out:
  8515. if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
  8516. alloc_flags = update_block_group_flags(root, cache->flags);
  8517. lock_chunks(root->fs_info->chunk_root);
  8518. check_system_chunk(trans, root, alloc_flags);
  8519. unlock_chunks(root->fs_info->chunk_root);
  8520. }
  8521. mutex_unlock(&root->fs_info->ro_block_group_mutex);
  8522. btrfs_end_transaction(trans, root);
  8523. return ret;
  8524. }
  8525. int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
  8526. struct btrfs_root *root, u64 type)
  8527. {
  8528. u64 alloc_flags = get_alloc_profile(root, type);
  8529. return do_chunk_alloc(trans, root, alloc_flags,
  8530. CHUNK_ALLOC_FORCE);
  8531. }
  8532. /*
  8533. * helper to account the unused space of all the readonly block group in the
  8534. * space_info. takes mirrors into account.
  8535. */
  8536. u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
  8537. {
  8538. struct btrfs_block_group_cache *block_group;
  8539. u64 free_bytes = 0;
  8540. int factor;
  8541. /* It's df, we don't care if it's racy */
  8542. if (list_empty(&sinfo->ro_bgs))
  8543. return 0;
  8544. spin_lock(&sinfo->lock);
  8545. list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
  8546. spin_lock(&block_group->lock);
  8547. if (!block_group->ro) {
  8548. spin_unlock(&block_group->lock);
  8549. continue;
  8550. }
  8551. if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
  8552. BTRFS_BLOCK_GROUP_RAID10 |
  8553. BTRFS_BLOCK_GROUP_DUP))
  8554. factor = 2;
  8555. else
  8556. factor = 1;
  8557. free_bytes += (block_group->key.offset -
  8558. btrfs_block_group_used(&block_group->item)) *
  8559. factor;
  8560. spin_unlock(&block_group->lock);
  8561. }
  8562. spin_unlock(&sinfo->lock);
  8563. return free_bytes;
  8564. }
  8565. void btrfs_dec_block_group_ro(struct btrfs_root *root,
  8566. struct btrfs_block_group_cache *cache)
  8567. {
  8568. struct btrfs_space_info *sinfo = cache->space_info;
  8569. u64 num_bytes;
  8570. BUG_ON(!cache->ro);
  8571. spin_lock(&sinfo->lock);
  8572. spin_lock(&cache->lock);
  8573. if (!--cache->ro) {
  8574. num_bytes = cache->key.offset - cache->reserved -
  8575. cache->pinned - cache->bytes_super -
  8576. btrfs_block_group_used(&cache->item);
  8577. sinfo->bytes_readonly -= num_bytes;
  8578. list_del_init(&cache->ro_list);
  8579. }
  8580. spin_unlock(&cache->lock);
  8581. spin_unlock(&sinfo->lock);
  8582. }
  8583. /*
  8584. * checks to see if its even possible to relocate this block group.
  8585. *
  8586. * @return - -1 if it's not a good idea to relocate this block group, 0 if its
  8587. * ok to go ahead and try.
  8588. */
  8589. int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
  8590. {
  8591. struct btrfs_block_group_cache *block_group;
  8592. struct btrfs_space_info *space_info;
  8593. struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
  8594. struct btrfs_device *device;
  8595. struct btrfs_trans_handle *trans;
  8596. u64 min_free;
  8597. u64 dev_min = 1;
  8598. u64 dev_nr = 0;
  8599. u64 target;
  8600. int debug;
  8601. int index;
  8602. int full = 0;
  8603. int ret = 0;
  8604. debug = btrfs_test_opt(root->fs_info, ENOSPC_DEBUG);
  8605. block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
  8606. /* odd, couldn't find the block group, leave it alone */
  8607. if (!block_group) {
  8608. if (debug)
  8609. btrfs_warn(root->fs_info,
  8610. "can't find block group for bytenr %llu",
  8611. bytenr);
  8612. return -1;
  8613. }
  8614. min_free = btrfs_block_group_used(&block_group->item);
  8615. /* no bytes used, we're good */
  8616. if (!min_free)
  8617. goto out;
  8618. space_info = block_group->space_info;
  8619. spin_lock(&space_info->lock);
  8620. full = space_info->full;
  8621. /*
  8622. * if this is the last block group we have in this space, we can't
  8623. * relocate it unless we're able to allocate a new chunk below.
  8624. *
  8625. * Otherwise, we need to make sure we have room in the space to handle
  8626. * all of the extents from this block group. If we can, we're good
  8627. */
  8628. if ((space_info->total_bytes != block_group->key.offset) &&
  8629. (space_info->bytes_used + space_info->bytes_reserved +
  8630. space_info->bytes_pinned + space_info->bytes_readonly +
  8631. min_free < space_info->total_bytes)) {
  8632. spin_unlock(&space_info->lock);
  8633. goto out;
  8634. }
  8635. spin_unlock(&space_info->lock);
  8636. /*
  8637. * ok we don't have enough space, but maybe we have free space on our
  8638. * devices to allocate new chunks for relocation, so loop through our
  8639. * alloc devices and guess if we have enough space. if this block
  8640. * group is going to be restriped, run checks against the target
  8641. * profile instead of the current one.
  8642. */
  8643. ret = -1;
  8644. /*
  8645. * index:
  8646. * 0: raid10
  8647. * 1: raid1
  8648. * 2: dup
  8649. * 3: raid0
  8650. * 4: single
  8651. */
  8652. target = get_restripe_target(root->fs_info, block_group->flags);
  8653. if (target) {
  8654. index = __get_raid_index(extended_to_chunk(target));
  8655. } else {
  8656. /*
  8657. * this is just a balance, so if we were marked as full
  8658. * we know there is no space for a new chunk
  8659. */
  8660. if (full) {
  8661. if (debug)
  8662. btrfs_warn(root->fs_info,
  8663. "no space to alloc new chunk for block group %llu",
  8664. block_group->key.objectid);
  8665. goto out;
  8666. }
  8667. index = get_block_group_index(block_group);
  8668. }
  8669. if (index == BTRFS_RAID_RAID10) {
  8670. dev_min = 4;
  8671. /* Divide by 2 */
  8672. min_free >>= 1;
  8673. } else if (index == BTRFS_RAID_RAID1) {
  8674. dev_min = 2;
  8675. } else if (index == BTRFS_RAID_DUP) {
  8676. /* Multiply by 2 */
  8677. min_free <<= 1;
  8678. } else if (index == BTRFS_RAID_RAID0) {
  8679. dev_min = fs_devices->rw_devices;
  8680. min_free = div64_u64(min_free, dev_min);
  8681. }
  8682. /* We need to do this so that we can look at pending chunks */
  8683. trans = btrfs_join_transaction(root);
  8684. if (IS_ERR(trans)) {
  8685. ret = PTR_ERR(trans);
  8686. goto out;
  8687. }
  8688. mutex_lock(&root->fs_info->chunk_mutex);
  8689. list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
  8690. u64 dev_offset;
  8691. /*
  8692. * check to make sure we can actually find a chunk with enough
  8693. * space to fit our block group in.
  8694. */
  8695. if (device->total_bytes > device->bytes_used + min_free &&
  8696. !device->is_tgtdev_for_dev_replace) {
  8697. ret = find_free_dev_extent(trans, device, min_free,
  8698. &dev_offset, NULL);
  8699. if (!ret)
  8700. dev_nr++;
  8701. if (dev_nr >= dev_min)
  8702. break;
  8703. ret = -1;
  8704. }
  8705. }
  8706. if (debug && ret == -1)
  8707. btrfs_warn(root->fs_info,
  8708. "no space to allocate a new chunk for block group %llu",
  8709. block_group->key.objectid);
  8710. mutex_unlock(&root->fs_info->chunk_mutex);
  8711. btrfs_end_transaction(trans, root);
  8712. out:
  8713. btrfs_put_block_group(block_group);
  8714. return ret;
  8715. }
  8716. static int find_first_block_group(struct btrfs_root *root,
  8717. struct btrfs_path *path, struct btrfs_key *key)
  8718. {
  8719. int ret = 0;
  8720. struct btrfs_key found_key;
  8721. struct extent_buffer *leaf;
  8722. int slot;
  8723. ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
  8724. if (ret < 0)
  8725. goto out;
  8726. while (1) {
  8727. slot = path->slots[0];
  8728. leaf = path->nodes[0];
  8729. if (slot >= btrfs_header_nritems(leaf)) {
  8730. ret = btrfs_next_leaf(root, path);
  8731. if (ret == 0)
  8732. continue;
  8733. if (ret < 0)
  8734. goto out;
  8735. break;
  8736. }
  8737. btrfs_item_key_to_cpu(leaf, &found_key, slot);
  8738. if (found_key.objectid >= key->objectid &&
  8739. found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
  8740. struct extent_map_tree *em_tree;
  8741. struct extent_map *em;
  8742. em_tree = &root->fs_info->mapping_tree.map_tree;
  8743. read_lock(&em_tree->lock);
  8744. em = lookup_extent_mapping(em_tree, found_key.objectid,
  8745. found_key.offset);
  8746. read_unlock(&em_tree->lock);
  8747. if (!em) {
  8748. btrfs_err(root->fs_info,
  8749. "logical %llu len %llu found bg but no related chunk",
  8750. found_key.objectid, found_key.offset);
  8751. ret = -ENOENT;
  8752. } else {
  8753. ret = 0;
  8754. }
  8755. free_extent_map(em);
  8756. goto out;
  8757. }
  8758. path->slots[0]++;
  8759. }
  8760. out:
  8761. return ret;
  8762. }
  8763. void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
  8764. {
  8765. struct btrfs_block_group_cache *block_group;
  8766. u64 last = 0;
  8767. while (1) {
  8768. struct inode *inode;
  8769. block_group = btrfs_lookup_first_block_group(info, last);
  8770. while (block_group) {
  8771. spin_lock(&block_group->lock);
  8772. if (block_group->iref)
  8773. break;
  8774. spin_unlock(&block_group->lock);
  8775. block_group = next_block_group(info->tree_root,
  8776. block_group);
  8777. }
  8778. if (!block_group) {
  8779. if (last == 0)
  8780. break;
  8781. last = 0;
  8782. continue;
  8783. }
  8784. inode = block_group->inode;
  8785. block_group->iref = 0;
  8786. block_group->inode = NULL;
  8787. spin_unlock(&block_group->lock);
  8788. ASSERT(block_group->io_ctl.inode == NULL);
  8789. iput(inode);
  8790. last = block_group->key.objectid + block_group->key.offset;
  8791. btrfs_put_block_group(block_group);
  8792. }
  8793. }
  8794. int btrfs_free_block_groups(struct btrfs_fs_info *info)
  8795. {
  8796. struct btrfs_block_group_cache *block_group;
  8797. struct btrfs_space_info *space_info;
  8798. struct btrfs_caching_control *caching_ctl;
  8799. struct rb_node *n;
  8800. down_write(&info->commit_root_sem);
  8801. while (!list_empty(&info->caching_block_groups)) {
  8802. caching_ctl = list_entry(info->caching_block_groups.next,
  8803. struct btrfs_caching_control, list);
  8804. list_del(&caching_ctl->list);
  8805. put_caching_control(caching_ctl);
  8806. }
  8807. up_write(&info->commit_root_sem);
  8808. spin_lock(&info->unused_bgs_lock);
  8809. while (!list_empty(&info->unused_bgs)) {
  8810. block_group = list_first_entry(&info->unused_bgs,
  8811. struct btrfs_block_group_cache,
  8812. bg_list);
  8813. list_del_init(&block_group->bg_list);
  8814. btrfs_put_block_group(block_group);
  8815. }
  8816. spin_unlock(&info->unused_bgs_lock);
  8817. spin_lock(&info->block_group_cache_lock);
  8818. while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
  8819. block_group = rb_entry(n, struct btrfs_block_group_cache,
  8820. cache_node);
  8821. rb_erase(&block_group->cache_node,
  8822. &info->block_group_cache_tree);
  8823. RB_CLEAR_NODE(&block_group->cache_node);
  8824. spin_unlock(&info->block_group_cache_lock);
  8825. down_write(&block_group->space_info->groups_sem);
  8826. list_del(&block_group->list);
  8827. up_write(&block_group->space_info->groups_sem);
  8828. if (block_group->cached == BTRFS_CACHE_STARTED)
  8829. wait_block_group_cache_done(block_group);
  8830. /*
  8831. * We haven't cached this block group, which means we could
  8832. * possibly have excluded extents on this block group.
  8833. */
  8834. if (block_group->cached == BTRFS_CACHE_NO ||
  8835. block_group->cached == BTRFS_CACHE_ERROR)
  8836. free_excluded_extents(info->extent_root, block_group);
  8837. btrfs_remove_free_space_cache(block_group);
  8838. ASSERT(list_empty(&block_group->dirty_list));
  8839. ASSERT(list_empty(&block_group->io_list));
  8840. ASSERT(list_empty(&block_group->bg_list));
  8841. ASSERT(atomic_read(&block_group->count) == 1);
  8842. btrfs_put_block_group(block_group);
  8843. spin_lock(&info->block_group_cache_lock);
  8844. }
  8845. spin_unlock(&info->block_group_cache_lock);
  8846. /* now that all the block groups are freed, go through and
  8847. * free all the space_info structs. This is only called during
  8848. * the final stages of unmount, and so we know nobody is
  8849. * using them. We call synchronize_rcu() once before we start,
  8850. * just to be on the safe side.
  8851. */
  8852. synchronize_rcu();
  8853. release_global_block_rsv(info);
  8854. while (!list_empty(&info->space_info)) {
  8855. int i;
  8856. space_info = list_entry(info->space_info.next,
  8857. struct btrfs_space_info,
  8858. list);
  8859. /*
  8860. * Do not hide this behind enospc_debug, this is actually
  8861. * important and indicates a real bug if this happens.
  8862. */
  8863. if (WARN_ON(space_info->bytes_pinned > 0 ||
  8864. space_info->bytes_reserved > 0 ||
  8865. space_info->bytes_may_use > 0))
  8866. dump_space_info(info, space_info, 0, 0);
  8867. list_del(&space_info->list);
  8868. for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
  8869. struct kobject *kobj;
  8870. kobj = space_info->block_group_kobjs[i];
  8871. space_info->block_group_kobjs[i] = NULL;
  8872. if (kobj) {
  8873. kobject_del(kobj);
  8874. kobject_put(kobj);
  8875. }
  8876. }
  8877. kobject_del(&space_info->kobj);
  8878. kobject_put(&space_info->kobj);
  8879. }
  8880. return 0;
  8881. }
  8882. static void __link_block_group(struct btrfs_space_info *space_info,
  8883. struct btrfs_block_group_cache *cache)
  8884. {
  8885. int index = get_block_group_index(cache);
  8886. bool first = false;
  8887. down_write(&space_info->groups_sem);
  8888. if (list_empty(&space_info->block_groups[index]))
  8889. first = true;
  8890. list_add_tail(&cache->list, &space_info->block_groups[index]);
  8891. up_write(&space_info->groups_sem);
  8892. if (first) {
  8893. struct raid_kobject *rkobj;
  8894. int ret;
  8895. rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
  8896. if (!rkobj)
  8897. goto out_err;
  8898. rkobj->raid_type = index;
  8899. kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
  8900. ret = kobject_add(&rkobj->kobj, &space_info->kobj,
  8901. "%s", get_raid_name(index));
  8902. if (ret) {
  8903. kobject_put(&rkobj->kobj);
  8904. goto out_err;
  8905. }
  8906. space_info->block_group_kobjs[index] = &rkobj->kobj;
  8907. }
  8908. return;
  8909. out_err:
  8910. btrfs_warn(cache->fs_info,
  8911. "failed to add kobject for block cache, ignoring");
  8912. }
  8913. static struct btrfs_block_group_cache *
  8914. btrfs_create_block_group_cache(struct btrfs_root *root, u64 start, u64 size)
  8915. {
  8916. struct btrfs_block_group_cache *cache;
  8917. cache = kzalloc(sizeof(*cache), GFP_NOFS);
  8918. if (!cache)
  8919. return NULL;
  8920. cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
  8921. GFP_NOFS);
  8922. if (!cache->free_space_ctl) {
  8923. kfree(cache);
  8924. return NULL;
  8925. }
  8926. cache->key.objectid = start;
  8927. cache->key.offset = size;
  8928. cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
  8929. cache->sectorsize = root->sectorsize;
  8930. cache->fs_info = root->fs_info;
  8931. cache->full_stripe_len = btrfs_full_stripe_len(root,
  8932. &root->fs_info->mapping_tree,
  8933. start);
  8934. set_free_space_tree_thresholds(cache);
  8935. atomic_set(&cache->count, 1);
  8936. spin_lock_init(&cache->lock);
  8937. init_rwsem(&cache->data_rwsem);
  8938. INIT_LIST_HEAD(&cache->list);
  8939. INIT_LIST_HEAD(&cache->cluster_list);
  8940. INIT_LIST_HEAD(&cache->bg_list);
  8941. INIT_LIST_HEAD(&cache->ro_list);
  8942. INIT_LIST_HEAD(&cache->dirty_list);
  8943. INIT_LIST_HEAD(&cache->io_list);
  8944. btrfs_init_free_space_ctl(cache);
  8945. atomic_set(&cache->trimming, 0);
  8946. mutex_init(&cache->free_space_lock);
  8947. return cache;
  8948. }
  8949. int btrfs_read_block_groups(struct btrfs_root *root)
  8950. {
  8951. struct btrfs_path *path;
  8952. int ret;
  8953. struct btrfs_block_group_cache *cache;
  8954. struct btrfs_fs_info *info = root->fs_info;
  8955. struct btrfs_space_info *space_info;
  8956. struct btrfs_key key;
  8957. struct btrfs_key found_key;
  8958. struct extent_buffer *leaf;
  8959. int need_clear = 0;
  8960. u64 cache_gen;
  8961. u64 feature;
  8962. int mixed;
  8963. feature = btrfs_super_incompat_flags(info->super_copy);
  8964. mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
  8965. root = info->extent_root;
  8966. key.objectid = 0;
  8967. key.offset = 0;
  8968. key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
  8969. path = btrfs_alloc_path();
  8970. if (!path)
  8971. return -ENOMEM;
  8972. path->reada = READA_FORWARD;
  8973. cache_gen = btrfs_super_cache_generation(root->fs_info->super_copy);
  8974. if (btrfs_test_opt(root->fs_info, SPACE_CACHE) &&
  8975. btrfs_super_generation(root->fs_info->super_copy) != cache_gen)
  8976. need_clear = 1;
  8977. if (btrfs_test_opt(root->fs_info, CLEAR_CACHE))
  8978. need_clear = 1;
  8979. while (1) {
  8980. ret = find_first_block_group(root, path, &key);
  8981. if (ret > 0)
  8982. break;
  8983. if (ret != 0)
  8984. goto error;
  8985. leaf = path->nodes[0];
  8986. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  8987. cache = btrfs_create_block_group_cache(root, found_key.objectid,
  8988. found_key.offset);
  8989. if (!cache) {
  8990. ret = -ENOMEM;
  8991. goto error;
  8992. }
  8993. if (need_clear) {
  8994. /*
  8995. * When we mount with old space cache, we need to
  8996. * set BTRFS_DC_CLEAR and set dirty flag.
  8997. *
  8998. * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
  8999. * truncate the old free space cache inode and
  9000. * setup a new one.
  9001. * b) Setting 'dirty flag' makes sure that we flush
  9002. * the new space cache info onto disk.
  9003. */
  9004. if (btrfs_test_opt(root->fs_info, SPACE_CACHE))
  9005. cache->disk_cache_state = BTRFS_DC_CLEAR;
  9006. }
  9007. read_extent_buffer(leaf, &cache->item,
  9008. btrfs_item_ptr_offset(leaf, path->slots[0]),
  9009. sizeof(cache->item));
  9010. cache->flags = btrfs_block_group_flags(&cache->item);
  9011. if (!mixed &&
  9012. ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
  9013. (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
  9014. btrfs_err(info,
  9015. "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
  9016. cache->key.objectid);
  9017. ret = -EINVAL;
  9018. goto error;
  9019. }
  9020. key.objectid = found_key.objectid + found_key.offset;
  9021. btrfs_release_path(path);
  9022. /*
  9023. * We need to exclude the super stripes now so that the space
  9024. * info has super bytes accounted for, otherwise we'll think
  9025. * we have more space than we actually do.
  9026. */
  9027. ret = exclude_super_stripes(root, cache);
  9028. if (ret) {
  9029. /*
  9030. * We may have excluded something, so call this just in
  9031. * case.
  9032. */
  9033. free_excluded_extents(root, cache);
  9034. btrfs_put_block_group(cache);
  9035. goto error;
  9036. }
  9037. /*
  9038. * check for two cases, either we are full, and therefore
  9039. * don't need to bother with the caching work since we won't
  9040. * find any space, or we are empty, and we can just add all
  9041. * the space in and be done with it. This saves us _alot_ of
  9042. * time, particularly in the full case.
  9043. */
  9044. if (found_key.offset == btrfs_block_group_used(&cache->item)) {
  9045. cache->last_byte_to_unpin = (u64)-1;
  9046. cache->cached = BTRFS_CACHE_FINISHED;
  9047. free_excluded_extents(root, cache);
  9048. } else if (btrfs_block_group_used(&cache->item) == 0) {
  9049. cache->last_byte_to_unpin = (u64)-1;
  9050. cache->cached = BTRFS_CACHE_FINISHED;
  9051. add_new_free_space(cache, root->fs_info,
  9052. found_key.objectid,
  9053. found_key.objectid +
  9054. found_key.offset);
  9055. free_excluded_extents(root, cache);
  9056. }
  9057. ret = btrfs_add_block_group_cache(root->fs_info, cache);
  9058. if (ret) {
  9059. btrfs_remove_free_space_cache(cache);
  9060. btrfs_put_block_group(cache);
  9061. goto error;
  9062. }
  9063. trace_btrfs_add_block_group(root->fs_info, cache, 0);
  9064. ret = update_space_info(info, cache->flags, found_key.offset,
  9065. btrfs_block_group_used(&cache->item),
  9066. cache->bytes_super, &space_info);
  9067. if (ret) {
  9068. btrfs_remove_free_space_cache(cache);
  9069. spin_lock(&info->block_group_cache_lock);
  9070. rb_erase(&cache->cache_node,
  9071. &info->block_group_cache_tree);
  9072. RB_CLEAR_NODE(&cache->cache_node);
  9073. spin_unlock(&info->block_group_cache_lock);
  9074. btrfs_put_block_group(cache);
  9075. goto error;
  9076. }
  9077. cache->space_info = space_info;
  9078. __link_block_group(space_info, cache);
  9079. set_avail_alloc_bits(root->fs_info, cache->flags);
  9080. if (btrfs_chunk_readonly(root, cache->key.objectid)) {
  9081. inc_block_group_ro(cache, 1);
  9082. } else if (btrfs_block_group_used(&cache->item) == 0) {
  9083. spin_lock(&info->unused_bgs_lock);
  9084. /* Should always be true but just in case. */
  9085. if (list_empty(&cache->bg_list)) {
  9086. btrfs_get_block_group(cache);
  9087. list_add_tail(&cache->bg_list,
  9088. &info->unused_bgs);
  9089. }
  9090. spin_unlock(&info->unused_bgs_lock);
  9091. }
  9092. }
  9093. list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
  9094. if (!(get_alloc_profile(root, space_info->flags) &
  9095. (BTRFS_BLOCK_GROUP_RAID10 |
  9096. BTRFS_BLOCK_GROUP_RAID1 |
  9097. BTRFS_BLOCK_GROUP_RAID5 |
  9098. BTRFS_BLOCK_GROUP_RAID6 |
  9099. BTRFS_BLOCK_GROUP_DUP)))
  9100. continue;
  9101. /*
  9102. * avoid allocating from un-mirrored block group if there are
  9103. * mirrored block groups.
  9104. */
  9105. list_for_each_entry(cache,
  9106. &space_info->block_groups[BTRFS_RAID_RAID0],
  9107. list)
  9108. inc_block_group_ro(cache, 1);
  9109. list_for_each_entry(cache,
  9110. &space_info->block_groups[BTRFS_RAID_SINGLE],
  9111. list)
  9112. inc_block_group_ro(cache, 1);
  9113. }
  9114. init_global_block_rsv(info);
  9115. ret = 0;
  9116. error:
  9117. btrfs_free_path(path);
  9118. return ret;
  9119. }
  9120. void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
  9121. struct btrfs_root *root)
  9122. {
  9123. struct btrfs_block_group_cache *block_group, *tmp;
  9124. struct btrfs_root *extent_root = root->fs_info->extent_root;
  9125. struct btrfs_block_group_item item;
  9126. struct btrfs_key key;
  9127. int ret = 0;
  9128. bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
  9129. trans->can_flush_pending_bgs = false;
  9130. list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
  9131. if (ret)
  9132. goto next;
  9133. spin_lock(&block_group->lock);
  9134. memcpy(&item, &block_group->item, sizeof(item));
  9135. memcpy(&key, &block_group->key, sizeof(key));
  9136. spin_unlock(&block_group->lock);
  9137. ret = btrfs_insert_item(trans, extent_root, &key, &item,
  9138. sizeof(item));
  9139. if (ret)
  9140. btrfs_abort_transaction(trans, ret);
  9141. ret = btrfs_finish_chunk_alloc(trans, extent_root,
  9142. key.objectid, key.offset);
  9143. if (ret)
  9144. btrfs_abort_transaction(trans, ret);
  9145. add_block_group_free_space(trans, root->fs_info, block_group);
  9146. /* already aborted the transaction if it failed. */
  9147. next:
  9148. list_del_init(&block_group->bg_list);
  9149. }
  9150. trans->can_flush_pending_bgs = can_flush_pending_bgs;
  9151. }
  9152. int btrfs_make_block_group(struct btrfs_trans_handle *trans,
  9153. struct btrfs_root *root, u64 bytes_used,
  9154. u64 type, u64 chunk_objectid, u64 chunk_offset,
  9155. u64 size)
  9156. {
  9157. int ret;
  9158. struct btrfs_root *extent_root;
  9159. struct btrfs_block_group_cache *cache;
  9160. extent_root = root->fs_info->extent_root;
  9161. btrfs_set_log_full_commit(root->fs_info, trans);
  9162. cache = btrfs_create_block_group_cache(root, chunk_offset, size);
  9163. if (!cache)
  9164. return -ENOMEM;
  9165. btrfs_set_block_group_used(&cache->item, bytes_used);
  9166. btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
  9167. btrfs_set_block_group_flags(&cache->item, type);
  9168. cache->flags = type;
  9169. cache->last_byte_to_unpin = (u64)-1;
  9170. cache->cached = BTRFS_CACHE_FINISHED;
  9171. cache->needs_free_space = 1;
  9172. ret = exclude_super_stripes(root, cache);
  9173. if (ret) {
  9174. /*
  9175. * We may have excluded something, so call this just in
  9176. * case.
  9177. */
  9178. free_excluded_extents(root, cache);
  9179. btrfs_put_block_group(cache);
  9180. return ret;
  9181. }
  9182. add_new_free_space(cache, root->fs_info, chunk_offset,
  9183. chunk_offset + size);
  9184. free_excluded_extents(root, cache);
  9185. #ifdef CONFIG_BTRFS_DEBUG
  9186. if (btrfs_should_fragment_free_space(root, cache)) {
  9187. u64 new_bytes_used = size - bytes_used;
  9188. bytes_used += new_bytes_used >> 1;
  9189. fragment_free_space(root, cache);
  9190. }
  9191. #endif
  9192. /*
  9193. * Call to ensure the corresponding space_info object is created and
  9194. * assigned to our block group, but don't update its counters just yet.
  9195. * We want our bg to be added to the rbtree with its ->space_info set.
  9196. */
  9197. ret = update_space_info(root->fs_info, cache->flags, 0, 0, 0,
  9198. &cache->space_info);
  9199. if (ret) {
  9200. btrfs_remove_free_space_cache(cache);
  9201. btrfs_put_block_group(cache);
  9202. return ret;
  9203. }
  9204. ret = btrfs_add_block_group_cache(root->fs_info, cache);
  9205. if (ret) {
  9206. btrfs_remove_free_space_cache(cache);
  9207. btrfs_put_block_group(cache);
  9208. return ret;
  9209. }
  9210. /*
  9211. * Now that our block group has its ->space_info set and is inserted in
  9212. * the rbtree, update the space info's counters.
  9213. */
  9214. trace_btrfs_add_block_group(root->fs_info, cache, 1);
  9215. ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
  9216. cache->bytes_super, &cache->space_info);
  9217. if (ret) {
  9218. btrfs_remove_free_space_cache(cache);
  9219. spin_lock(&root->fs_info->block_group_cache_lock);
  9220. rb_erase(&cache->cache_node,
  9221. &root->fs_info->block_group_cache_tree);
  9222. RB_CLEAR_NODE(&cache->cache_node);
  9223. spin_unlock(&root->fs_info->block_group_cache_lock);
  9224. btrfs_put_block_group(cache);
  9225. return ret;
  9226. }
  9227. update_global_block_rsv(root->fs_info);
  9228. __link_block_group(cache->space_info, cache);
  9229. list_add_tail(&cache->bg_list, &trans->new_bgs);
  9230. set_avail_alloc_bits(extent_root->fs_info, type);
  9231. return 0;
  9232. }
  9233. static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
  9234. {
  9235. u64 extra_flags = chunk_to_extended(flags) &
  9236. BTRFS_EXTENDED_PROFILE_MASK;
  9237. write_seqlock(&fs_info->profiles_lock);
  9238. if (flags & BTRFS_BLOCK_GROUP_DATA)
  9239. fs_info->avail_data_alloc_bits &= ~extra_flags;
  9240. if (flags & BTRFS_BLOCK_GROUP_METADATA)
  9241. fs_info->avail_metadata_alloc_bits &= ~extra_flags;
  9242. if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
  9243. fs_info->avail_system_alloc_bits &= ~extra_flags;
  9244. write_sequnlock(&fs_info->profiles_lock);
  9245. }
  9246. int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
  9247. struct btrfs_root *root, u64 group_start,
  9248. struct extent_map *em)
  9249. {
  9250. struct btrfs_path *path;
  9251. struct btrfs_block_group_cache *block_group;
  9252. struct btrfs_free_cluster *cluster;
  9253. struct btrfs_root *tree_root = root->fs_info->tree_root;
  9254. struct btrfs_key key;
  9255. struct inode *inode;
  9256. struct kobject *kobj = NULL;
  9257. int ret;
  9258. int index;
  9259. int factor;
  9260. struct btrfs_caching_control *caching_ctl = NULL;
  9261. bool remove_em;
  9262. root = root->fs_info->extent_root;
  9263. block_group = btrfs_lookup_block_group(root->fs_info, group_start);
  9264. BUG_ON(!block_group);
  9265. BUG_ON(!block_group->ro);
  9266. /*
  9267. * Free the reserved super bytes from this block group before
  9268. * remove it.
  9269. */
  9270. free_excluded_extents(root, block_group);
  9271. memcpy(&key, &block_group->key, sizeof(key));
  9272. index = get_block_group_index(block_group);
  9273. if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
  9274. BTRFS_BLOCK_GROUP_RAID1 |
  9275. BTRFS_BLOCK_GROUP_RAID10))
  9276. factor = 2;
  9277. else
  9278. factor = 1;
  9279. /* make sure this block group isn't part of an allocation cluster */
  9280. cluster = &root->fs_info->data_alloc_cluster;
  9281. spin_lock(&cluster->refill_lock);
  9282. btrfs_return_cluster_to_free_space(block_group, cluster);
  9283. spin_unlock(&cluster->refill_lock);
  9284. /*
  9285. * make sure this block group isn't part of a metadata
  9286. * allocation cluster
  9287. */
  9288. cluster = &root->fs_info->meta_alloc_cluster;
  9289. spin_lock(&cluster->refill_lock);
  9290. btrfs_return_cluster_to_free_space(block_group, cluster);
  9291. spin_unlock(&cluster->refill_lock);
  9292. path = btrfs_alloc_path();
  9293. if (!path) {
  9294. ret = -ENOMEM;
  9295. goto out;
  9296. }
  9297. /*
  9298. * get the inode first so any iput calls done for the io_list
  9299. * aren't the final iput (no unlinks allowed now)
  9300. */
  9301. inode = lookup_free_space_inode(tree_root, block_group, path);
  9302. mutex_lock(&trans->transaction->cache_write_mutex);
  9303. /*
  9304. * make sure our free spache cache IO is done before remove the
  9305. * free space inode
  9306. */
  9307. spin_lock(&trans->transaction->dirty_bgs_lock);
  9308. if (!list_empty(&block_group->io_list)) {
  9309. list_del_init(&block_group->io_list);
  9310. WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
  9311. spin_unlock(&trans->transaction->dirty_bgs_lock);
  9312. btrfs_wait_cache_io(root, trans, block_group,
  9313. &block_group->io_ctl, path,
  9314. block_group->key.objectid);
  9315. btrfs_put_block_group(block_group);
  9316. spin_lock(&trans->transaction->dirty_bgs_lock);
  9317. }
  9318. if (!list_empty(&block_group->dirty_list)) {
  9319. list_del_init(&block_group->dirty_list);
  9320. btrfs_put_block_group(block_group);
  9321. }
  9322. spin_unlock(&trans->transaction->dirty_bgs_lock);
  9323. mutex_unlock(&trans->transaction->cache_write_mutex);
  9324. if (!IS_ERR(inode)) {
  9325. ret = btrfs_orphan_add(trans, inode);
  9326. if (ret) {
  9327. btrfs_add_delayed_iput(inode);
  9328. goto out;
  9329. }
  9330. clear_nlink(inode);
  9331. /* One for the block groups ref */
  9332. spin_lock(&block_group->lock);
  9333. if (block_group->iref) {
  9334. block_group->iref = 0;
  9335. block_group->inode = NULL;
  9336. spin_unlock(&block_group->lock);
  9337. iput(inode);
  9338. } else {
  9339. spin_unlock(&block_group->lock);
  9340. }
  9341. /* One for our lookup ref */
  9342. btrfs_add_delayed_iput(inode);
  9343. }
  9344. key.objectid = BTRFS_FREE_SPACE_OBJECTID;
  9345. key.offset = block_group->key.objectid;
  9346. key.type = 0;
  9347. ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
  9348. if (ret < 0)
  9349. goto out;
  9350. if (ret > 0)
  9351. btrfs_release_path(path);
  9352. if (ret == 0) {
  9353. ret = btrfs_del_item(trans, tree_root, path);
  9354. if (ret)
  9355. goto out;
  9356. btrfs_release_path(path);
  9357. }
  9358. spin_lock(&root->fs_info->block_group_cache_lock);
  9359. rb_erase(&block_group->cache_node,
  9360. &root->fs_info->block_group_cache_tree);
  9361. RB_CLEAR_NODE(&block_group->cache_node);
  9362. if (root->fs_info->first_logical_byte == block_group->key.objectid)
  9363. root->fs_info->first_logical_byte = (u64)-1;
  9364. spin_unlock(&root->fs_info->block_group_cache_lock);
  9365. down_write(&block_group->space_info->groups_sem);
  9366. /*
  9367. * we must use list_del_init so people can check to see if they
  9368. * are still on the list after taking the semaphore
  9369. */
  9370. list_del_init(&block_group->list);
  9371. if (list_empty(&block_group->space_info->block_groups[index])) {
  9372. kobj = block_group->space_info->block_group_kobjs[index];
  9373. block_group->space_info->block_group_kobjs[index] = NULL;
  9374. clear_avail_alloc_bits(root->fs_info, block_group->flags);
  9375. }
  9376. up_write(&block_group->space_info->groups_sem);
  9377. if (kobj) {
  9378. kobject_del(kobj);
  9379. kobject_put(kobj);
  9380. }
  9381. if (block_group->has_caching_ctl)
  9382. caching_ctl = get_caching_control(block_group);
  9383. if (block_group->cached == BTRFS_CACHE_STARTED)
  9384. wait_block_group_cache_done(block_group);
  9385. if (block_group->has_caching_ctl) {
  9386. down_write(&root->fs_info->commit_root_sem);
  9387. if (!caching_ctl) {
  9388. struct btrfs_caching_control *ctl;
  9389. list_for_each_entry(ctl,
  9390. &root->fs_info->caching_block_groups, list)
  9391. if (ctl->block_group == block_group) {
  9392. caching_ctl = ctl;
  9393. atomic_inc(&caching_ctl->count);
  9394. break;
  9395. }
  9396. }
  9397. if (caching_ctl)
  9398. list_del_init(&caching_ctl->list);
  9399. up_write(&root->fs_info->commit_root_sem);
  9400. if (caching_ctl) {
  9401. /* Once for the caching bgs list and once for us. */
  9402. put_caching_control(caching_ctl);
  9403. put_caching_control(caching_ctl);
  9404. }
  9405. }
  9406. spin_lock(&trans->transaction->dirty_bgs_lock);
  9407. if (!list_empty(&block_group->dirty_list)) {
  9408. WARN_ON(1);
  9409. }
  9410. if (!list_empty(&block_group->io_list)) {
  9411. WARN_ON(1);
  9412. }
  9413. spin_unlock(&trans->transaction->dirty_bgs_lock);
  9414. btrfs_remove_free_space_cache(block_group);
  9415. spin_lock(&block_group->space_info->lock);
  9416. list_del_init(&block_group->ro_list);
  9417. if (btrfs_test_opt(root->fs_info, ENOSPC_DEBUG)) {
  9418. WARN_ON(block_group->space_info->total_bytes
  9419. < block_group->key.offset);
  9420. WARN_ON(block_group->space_info->bytes_readonly
  9421. < block_group->key.offset);
  9422. WARN_ON(block_group->space_info->disk_total
  9423. < block_group->key.offset * factor);
  9424. }
  9425. block_group->space_info->total_bytes -= block_group->key.offset;
  9426. block_group->space_info->bytes_readonly -= block_group->key.offset;
  9427. block_group->space_info->disk_total -= block_group->key.offset * factor;
  9428. spin_unlock(&block_group->space_info->lock);
  9429. memcpy(&key, &block_group->key, sizeof(key));
  9430. lock_chunks(root);
  9431. if (!list_empty(&em->list)) {
  9432. /* We're in the transaction->pending_chunks list. */
  9433. free_extent_map(em);
  9434. }
  9435. spin_lock(&block_group->lock);
  9436. block_group->removed = 1;
  9437. /*
  9438. * At this point trimming can't start on this block group, because we
  9439. * removed the block group from the tree fs_info->block_group_cache_tree
  9440. * so no one can't find it anymore and even if someone already got this
  9441. * block group before we removed it from the rbtree, they have already
  9442. * incremented block_group->trimming - if they didn't, they won't find
  9443. * any free space entries because we already removed them all when we
  9444. * called btrfs_remove_free_space_cache().
  9445. *
  9446. * And we must not remove the extent map from the fs_info->mapping_tree
  9447. * to prevent the same logical address range and physical device space
  9448. * ranges from being reused for a new block group. This is because our
  9449. * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
  9450. * completely transactionless, so while it is trimming a range the
  9451. * currently running transaction might finish and a new one start,
  9452. * allowing for new block groups to be created that can reuse the same
  9453. * physical device locations unless we take this special care.
  9454. *
  9455. * There may also be an implicit trim operation if the file system
  9456. * is mounted with -odiscard. The same protections must remain
  9457. * in place until the extents have been discarded completely when
  9458. * the transaction commit has completed.
  9459. */
  9460. remove_em = (atomic_read(&block_group->trimming) == 0);
  9461. /*
  9462. * Make sure a trimmer task always sees the em in the pinned_chunks list
  9463. * if it sees block_group->removed == 1 (needs to lock block_group->lock
  9464. * before checking block_group->removed).
  9465. */
  9466. if (!remove_em) {
  9467. /*
  9468. * Our em might be in trans->transaction->pending_chunks which
  9469. * is protected by fs_info->chunk_mutex ([lock|unlock]_chunks),
  9470. * and so is the fs_info->pinned_chunks list.
  9471. *
  9472. * So at this point we must be holding the chunk_mutex to avoid
  9473. * any races with chunk allocation (more specifically at
  9474. * volumes.c:contains_pending_extent()), to ensure it always
  9475. * sees the em, either in the pending_chunks list or in the
  9476. * pinned_chunks list.
  9477. */
  9478. list_move_tail(&em->list, &root->fs_info->pinned_chunks);
  9479. }
  9480. spin_unlock(&block_group->lock);
  9481. if (remove_em) {
  9482. struct extent_map_tree *em_tree;
  9483. em_tree = &root->fs_info->mapping_tree.map_tree;
  9484. write_lock(&em_tree->lock);
  9485. /*
  9486. * The em might be in the pending_chunks list, so make sure the
  9487. * chunk mutex is locked, since remove_extent_mapping() will
  9488. * delete us from that list.
  9489. */
  9490. remove_extent_mapping(em_tree, em);
  9491. write_unlock(&em_tree->lock);
  9492. /* once for the tree */
  9493. free_extent_map(em);
  9494. }
  9495. unlock_chunks(root);
  9496. ret = remove_block_group_free_space(trans, root->fs_info, block_group);
  9497. if (ret)
  9498. goto out;
  9499. btrfs_put_block_group(block_group);
  9500. btrfs_put_block_group(block_group);
  9501. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  9502. if (ret > 0)
  9503. ret = -EIO;
  9504. if (ret < 0)
  9505. goto out;
  9506. ret = btrfs_del_item(trans, root, path);
  9507. out:
  9508. btrfs_free_path(path);
  9509. return ret;
  9510. }
  9511. struct btrfs_trans_handle *
  9512. btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
  9513. const u64 chunk_offset)
  9514. {
  9515. struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
  9516. struct extent_map *em;
  9517. struct map_lookup *map;
  9518. unsigned int num_items;
  9519. read_lock(&em_tree->lock);
  9520. em = lookup_extent_mapping(em_tree, chunk_offset, 1);
  9521. read_unlock(&em_tree->lock);
  9522. ASSERT(em && em->start == chunk_offset);
  9523. /*
  9524. * We need to reserve 3 + N units from the metadata space info in order
  9525. * to remove a block group (done at btrfs_remove_chunk() and at
  9526. * btrfs_remove_block_group()), which are used for:
  9527. *
  9528. * 1 unit for adding the free space inode's orphan (located in the tree
  9529. * of tree roots).
  9530. * 1 unit for deleting the block group item (located in the extent
  9531. * tree).
  9532. * 1 unit for deleting the free space item (located in tree of tree
  9533. * roots).
  9534. * N units for deleting N device extent items corresponding to each
  9535. * stripe (located in the device tree).
  9536. *
  9537. * In order to remove a block group we also need to reserve units in the
  9538. * system space info in order to update the chunk tree (update one or
  9539. * more device items and remove one chunk item), but this is done at
  9540. * btrfs_remove_chunk() through a call to check_system_chunk().
  9541. */
  9542. map = em->map_lookup;
  9543. num_items = 3 + map->num_stripes;
  9544. free_extent_map(em);
  9545. return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
  9546. num_items, 1);
  9547. }
  9548. /*
  9549. * Process the unused_bgs list and remove any that don't have any allocated
  9550. * space inside of them.
  9551. */
  9552. void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
  9553. {
  9554. struct btrfs_block_group_cache *block_group;
  9555. struct btrfs_space_info *space_info;
  9556. struct btrfs_root *root = fs_info->extent_root;
  9557. struct btrfs_trans_handle *trans;
  9558. int ret = 0;
  9559. if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
  9560. return;
  9561. spin_lock(&fs_info->unused_bgs_lock);
  9562. while (!list_empty(&fs_info->unused_bgs)) {
  9563. u64 start, end;
  9564. int trimming;
  9565. block_group = list_first_entry(&fs_info->unused_bgs,
  9566. struct btrfs_block_group_cache,
  9567. bg_list);
  9568. list_del_init(&block_group->bg_list);
  9569. space_info = block_group->space_info;
  9570. if (ret || btrfs_mixed_space_info(space_info)) {
  9571. btrfs_put_block_group(block_group);
  9572. continue;
  9573. }
  9574. spin_unlock(&fs_info->unused_bgs_lock);
  9575. mutex_lock(&fs_info->delete_unused_bgs_mutex);
  9576. /* Don't want to race with allocators so take the groups_sem */
  9577. down_write(&space_info->groups_sem);
  9578. spin_lock(&block_group->lock);
  9579. if (block_group->reserved ||
  9580. btrfs_block_group_used(&block_group->item) ||
  9581. block_group->ro ||
  9582. list_is_singular(&block_group->list)) {
  9583. /*
  9584. * We want to bail if we made new allocations or have
  9585. * outstanding allocations in this block group. We do
  9586. * the ro check in case balance is currently acting on
  9587. * this block group.
  9588. */
  9589. spin_unlock(&block_group->lock);
  9590. up_write(&space_info->groups_sem);
  9591. goto next;
  9592. }
  9593. spin_unlock(&block_group->lock);
  9594. /* We don't want to force the issue, only flip if it's ok. */
  9595. ret = inc_block_group_ro(block_group, 0);
  9596. up_write(&space_info->groups_sem);
  9597. if (ret < 0) {
  9598. ret = 0;
  9599. goto next;
  9600. }
  9601. /*
  9602. * Want to do this before we do anything else so we can recover
  9603. * properly if we fail to join the transaction.
  9604. */
  9605. trans = btrfs_start_trans_remove_block_group(fs_info,
  9606. block_group->key.objectid);
  9607. if (IS_ERR(trans)) {
  9608. btrfs_dec_block_group_ro(root, block_group);
  9609. ret = PTR_ERR(trans);
  9610. goto next;
  9611. }
  9612. /*
  9613. * We could have pending pinned extents for this block group,
  9614. * just delete them, we don't care about them anymore.
  9615. */
  9616. start = block_group->key.objectid;
  9617. end = start + block_group->key.offset - 1;
  9618. /*
  9619. * Hold the unused_bg_unpin_mutex lock to avoid racing with
  9620. * btrfs_finish_extent_commit(). If we are at transaction N,
  9621. * another task might be running finish_extent_commit() for the
  9622. * previous transaction N - 1, and have seen a range belonging
  9623. * to the block group in freed_extents[] before we were able to
  9624. * clear the whole block group range from freed_extents[]. This
  9625. * means that task can lookup for the block group after we
  9626. * unpinned it from freed_extents[] and removed it, leading to
  9627. * a BUG_ON() at btrfs_unpin_extent_range().
  9628. */
  9629. mutex_lock(&fs_info->unused_bg_unpin_mutex);
  9630. ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
  9631. EXTENT_DIRTY);
  9632. if (ret) {
  9633. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  9634. btrfs_dec_block_group_ro(root, block_group);
  9635. goto end_trans;
  9636. }
  9637. ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
  9638. EXTENT_DIRTY);
  9639. if (ret) {
  9640. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  9641. btrfs_dec_block_group_ro(root, block_group);
  9642. goto end_trans;
  9643. }
  9644. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  9645. /* Reset pinned so btrfs_put_block_group doesn't complain */
  9646. spin_lock(&space_info->lock);
  9647. spin_lock(&block_group->lock);
  9648. space_info->bytes_pinned -= block_group->pinned;
  9649. space_info->bytes_readonly += block_group->pinned;
  9650. percpu_counter_add(&space_info->total_bytes_pinned,
  9651. -block_group->pinned);
  9652. block_group->pinned = 0;
  9653. spin_unlock(&block_group->lock);
  9654. spin_unlock(&space_info->lock);
  9655. /* DISCARD can flip during remount */
  9656. trimming = btrfs_test_opt(root->fs_info, DISCARD);
  9657. /* Implicit trim during transaction commit. */
  9658. if (trimming)
  9659. btrfs_get_block_group_trimming(block_group);
  9660. /*
  9661. * Btrfs_remove_chunk will abort the transaction if things go
  9662. * horribly wrong.
  9663. */
  9664. ret = btrfs_remove_chunk(trans, root,
  9665. block_group->key.objectid);
  9666. if (ret) {
  9667. if (trimming)
  9668. btrfs_put_block_group_trimming(block_group);
  9669. goto end_trans;
  9670. }
  9671. /*
  9672. * If we're not mounted with -odiscard, we can just forget
  9673. * about this block group. Otherwise we'll need to wait
  9674. * until transaction commit to do the actual discard.
  9675. */
  9676. if (trimming) {
  9677. spin_lock(&fs_info->unused_bgs_lock);
  9678. /*
  9679. * A concurrent scrub might have added us to the list
  9680. * fs_info->unused_bgs, so use a list_move operation
  9681. * to add the block group to the deleted_bgs list.
  9682. */
  9683. list_move(&block_group->bg_list,
  9684. &trans->transaction->deleted_bgs);
  9685. spin_unlock(&fs_info->unused_bgs_lock);
  9686. btrfs_get_block_group(block_group);
  9687. }
  9688. end_trans:
  9689. btrfs_end_transaction(trans, root);
  9690. next:
  9691. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  9692. btrfs_put_block_group(block_group);
  9693. spin_lock(&fs_info->unused_bgs_lock);
  9694. }
  9695. spin_unlock(&fs_info->unused_bgs_lock);
  9696. }
  9697. int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
  9698. {
  9699. struct btrfs_space_info *space_info;
  9700. struct btrfs_super_block *disk_super;
  9701. u64 features;
  9702. u64 flags;
  9703. int mixed = 0;
  9704. int ret;
  9705. disk_super = fs_info->super_copy;
  9706. if (!btrfs_super_root(disk_super))
  9707. return -EINVAL;
  9708. features = btrfs_super_incompat_flags(disk_super);
  9709. if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
  9710. mixed = 1;
  9711. flags = BTRFS_BLOCK_GROUP_SYSTEM;
  9712. ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
  9713. if (ret)
  9714. goto out;
  9715. if (mixed) {
  9716. flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
  9717. ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
  9718. } else {
  9719. flags = BTRFS_BLOCK_GROUP_METADATA;
  9720. ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
  9721. if (ret)
  9722. goto out;
  9723. flags = BTRFS_BLOCK_GROUP_DATA;
  9724. ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
  9725. }
  9726. out:
  9727. return ret;
  9728. }
  9729. int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
  9730. {
  9731. return unpin_extent_range(root, start, end, false);
  9732. }
  9733. /*
  9734. * It used to be that old block groups would be left around forever.
  9735. * Iterating over them would be enough to trim unused space. Since we
  9736. * now automatically remove them, we also need to iterate over unallocated
  9737. * space.
  9738. *
  9739. * We don't want a transaction for this since the discard may take a
  9740. * substantial amount of time. We don't require that a transaction be
  9741. * running, but we do need to take a running transaction into account
  9742. * to ensure that we're not discarding chunks that were released in
  9743. * the current transaction.
  9744. *
  9745. * Holding the chunks lock will prevent other threads from allocating
  9746. * or releasing chunks, but it won't prevent a running transaction
  9747. * from committing and releasing the memory that the pending chunks
  9748. * list head uses. For that, we need to take a reference to the
  9749. * transaction.
  9750. */
  9751. static int btrfs_trim_free_extents(struct btrfs_device *device,
  9752. u64 minlen, u64 *trimmed)
  9753. {
  9754. u64 start = 0, len = 0;
  9755. int ret;
  9756. *trimmed = 0;
  9757. /* Not writeable = nothing to do. */
  9758. if (!device->writeable)
  9759. return 0;
  9760. /* No free space = nothing to do. */
  9761. if (device->total_bytes <= device->bytes_used)
  9762. return 0;
  9763. ret = 0;
  9764. while (1) {
  9765. struct btrfs_fs_info *fs_info = device->dev_root->fs_info;
  9766. struct btrfs_transaction *trans;
  9767. u64 bytes;
  9768. ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
  9769. if (ret)
  9770. return ret;
  9771. down_read(&fs_info->commit_root_sem);
  9772. spin_lock(&fs_info->trans_lock);
  9773. trans = fs_info->running_transaction;
  9774. if (trans)
  9775. atomic_inc(&trans->use_count);
  9776. spin_unlock(&fs_info->trans_lock);
  9777. ret = find_free_dev_extent_start(trans, device, minlen, start,
  9778. &start, &len);
  9779. if (trans)
  9780. btrfs_put_transaction(trans);
  9781. if (ret) {
  9782. up_read(&fs_info->commit_root_sem);
  9783. mutex_unlock(&fs_info->chunk_mutex);
  9784. if (ret == -ENOSPC)
  9785. ret = 0;
  9786. break;
  9787. }
  9788. ret = btrfs_issue_discard(device->bdev, start, len, &bytes);
  9789. up_read(&fs_info->commit_root_sem);
  9790. mutex_unlock(&fs_info->chunk_mutex);
  9791. if (ret)
  9792. break;
  9793. start += len;
  9794. *trimmed += bytes;
  9795. if (fatal_signal_pending(current)) {
  9796. ret = -ERESTARTSYS;
  9797. break;
  9798. }
  9799. cond_resched();
  9800. }
  9801. return ret;
  9802. }
  9803. int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
  9804. {
  9805. struct btrfs_fs_info *fs_info = root->fs_info;
  9806. struct btrfs_block_group_cache *cache = NULL;
  9807. struct btrfs_device *device;
  9808. struct list_head *devices;
  9809. u64 group_trimmed;
  9810. u64 start;
  9811. u64 end;
  9812. u64 trimmed = 0;
  9813. u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
  9814. int ret = 0;
  9815. /*
  9816. * try to trim all FS space, our block group may start from non-zero.
  9817. */
  9818. if (range->len == total_bytes)
  9819. cache = btrfs_lookup_first_block_group(fs_info, range->start);
  9820. else
  9821. cache = btrfs_lookup_block_group(fs_info, range->start);
  9822. while (cache) {
  9823. if (cache->key.objectid >= (range->start + range->len)) {
  9824. btrfs_put_block_group(cache);
  9825. break;
  9826. }
  9827. start = max(range->start, cache->key.objectid);
  9828. end = min(range->start + range->len,
  9829. cache->key.objectid + cache->key.offset);
  9830. if (end - start >= range->minlen) {
  9831. if (!block_group_cache_done(cache)) {
  9832. ret = cache_block_group(cache, 0);
  9833. if (ret) {
  9834. btrfs_put_block_group(cache);
  9835. break;
  9836. }
  9837. ret = wait_block_group_cache_done(cache);
  9838. if (ret) {
  9839. btrfs_put_block_group(cache);
  9840. break;
  9841. }
  9842. }
  9843. ret = btrfs_trim_block_group(cache,
  9844. &group_trimmed,
  9845. start,
  9846. end,
  9847. range->minlen);
  9848. trimmed += group_trimmed;
  9849. if (ret) {
  9850. btrfs_put_block_group(cache);
  9851. break;
  9852. }
  9853. }
  9854. cache = next_block_group(fs_info->tree_root, cache);
  9855. }
  9856. mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
  9857. devices = &root->fs_info->fs_devices->alloc_list;
  9858. list_for_each_entry(device, devices, dev_alloc_list) {
  9859. ret = btrfs_trim_free_extents(device, range->minlen,
  9860. &group_trimmed);
  9861. if (ret)
  9862. break;
  9863. trimmed += group_trimmed;
  9864. }
  9865. mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
  9866. range->len = trimmed;
  9867. return ret;
  9868. }
  9869. /*
  9870. * btrfs_{start,end}_write_no_snapshoting() are similar to
  9871. * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
  9872. * data into the page cache through nocow before the subvolume is snapshoted,
  9873. * but flush the data into disk after the snapshot creation, or to prevent
  9874. * operations while snapshoting is ongoing and that cause the snapshot to be
  9875. * inconsistent (writes followed by expanding truncates for example).
  9876. */
  9877. void btrfs_end_write_no_snapshoting(struct btrfs_root *root)
  9878. {
  9879. percpu_counter_dec(&root->subv_writers->counter);
  9880. /*
  9881. * Make sure counter is updated before we wake up waiters.
  9882. */
  9883. smp_mb();
  9884. if (waitqueue_active(&root->subv_writers->wait))
  9885. wake_up(&root->subv_writers->wait);
  9886. }
  9887. int btrfs_start_write_no_snapshoting(struct btrfs_root *root)
  9888. {
  9889. if (atomic_read(&root->will_be_snapshoted))
  9890. return 0;
  9891. percpu_counter_inc(&root->subv_writers->counter);
  9892. /*
  9893. * Make sure counter is updated before we check for snapshot creation.
  9894. */
  9895. smp_mb();
  9896. if (atomic_read(&root->will_be_snapshoted)) {
  9897. btrfs_end_write_no_snapshoting(root);
  9898. return 0;
  9899. }
  9900. return 1;
  9901. }
  9902. static int wait_snapshoting_atomic_t(atomic_t *a)
  9903. {
  9904. schedule();
  9905. return 0;
  9906. }
  9907. void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
  9908. {
  9909. while (true) {
  9910. int ret;
  9911. ret = btrfs_start_write_no_snapshoting(root);
  9912. if (ret)
  9913. break;
  9914. wait_on_atomic_t(&root->will_be_snapshoted,
  9915. wait_snapshoting_atomic_t,
  9916. TASK_UNINTERRUPTIBLE);
  9917. }
  9918. }