extent-tree.c 304 KB

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