extent-tree.c 278 KB

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