extent-tree.c 292 KB

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