extent-tree.c 304 KB

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