extent-tree.c 299 KB

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