extent-tree.c 278 KB

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