extent-tree.c 182 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2007 Oracle. All rights reserved.
  4. */
  5. #include <linux/sched.h>
  6. #include <linux/sched/signal.h>
  7. #include <linux/pagemap.h>
  8. #include <linux/writeback.h>
  9. #include <linux/blkdev.h>
  10. #include <linux/sort.h>
  11. #include <linux/rcupdate.h>
  12. #include <linux/kthread.h>
  13. #include <linux/slab.h>
  14. #include <linux/ratelimit.h>
  15. #include <linux/percpu_counter.h>
  16. #include <linux/lockdep.h>
  17. #include <linux/crc32c.h>
  18. #include "ctree.h"
  19. #include "extent-tree.h"
  20. #include "transaction.h"
  21. #include "disk-io.h"
  22. #include "print-tree.h"
  23. #include "volumes.h"
  24. #include "raid56.h"
  25. #include "locking.h"
  26. #include "free-space-cache.h"
  27. #include "free-space-tree.h"
  28. #include "qgroup.h"
  29. #include "ref-verify.h"
  30. #include "space-info.h"
  31. #include "block-rsv.h"
  32. #include "discard.h"
  33. #include "zoned.h"
  34. #include "dev-replace.h"
  35. #include "fs.h"
  36. #include "accessors.h"
  37. #include "root-tree.h"
  38. #include "file-item.h"
  39. #include "orphan.h"
  40. #include "tree-checker.h"
  41. #include "raid-stripe-tree.h"
  42. #undef SCRAMBLE_DELAYED_REFS
  43. static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
  44. struct btrfs_delayed_ref_head *href,
  45. struct btrfs_delayed_ref_node *node,
  46. struct btrfs_delayed_extent_op *extra_op);
  47. static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
  48. struct extent_buffer *leaf,
  49. struct btrfs_extent_item *ei);
  50. static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
  51. u64 parent, u64 root_objectid,
  52. u64 flags, u64 owner, u64 offset,
  53. struct btrfs_key *ins, int ref_mod, u64 oref_root);
  54. static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
  55. struct btrfs_delayed_ref_node *node,
  56. struct btrfs_delayed_extent_op *extent_op);
  57. static int find_next_key(struct btrfs_path *path, int level,
  58. struct btrfs_key *key);
  59. static int block_group_bits(struct btrfs_block_group *cache, u64 bits)
  60. {
  61. return (cache->flags & bits) == bits;
  62. }
  63. /* simple helper to search for an existing data extent at a given offset */
  64. int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
  65. {
  66. struct btrfs_root *root = btrfs_extent_root(fs_info, start);
  67. int ret;
  68. struct btrfs_key key;
  69. struct btrfs_path *path;
  70. path = btrfs_alloc_path();
  71. if (!path)
  72. return -ENOMEM;
  73. key.objectid = start;
  74. key.offset = len;
  75. key.type = BTRFS_EXTENT_ITEM_KEY;
  76. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  77. btrfs_free_path(path);
  78. return ret;
  79. }
  80. /*
  81. * helper function to lookup reference count and flags of a tree block.
  82. *
  83. * the head node for delayed ref is used to store the sum of all the
  84. * reference count modifications queued up in the rbtree. the head
  85. * node may also store the extent flags to set. This way you can check
  86. * to see what the reference count and extent flags would be if all of
  87. * the delayed refs are not processed.
  88. */
  89. int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
  90. struct btrfs_fs_info *fs_info, u64 bytenr,
  91. u64 offset, int metadata, u64 *refs, u64 *flags,
  92. u64 *owning_root)
  93. {
  94. struct btrfs_root *extent_root;
  95. struct btrfs_delayed_ref_head *head;
  96. struct btrfs_delayed_ref_root *delayed_refs;
  97. struct btrfs_path *path;
  98. struct btrfs_key key;
  99. u64 num_refs;
  100. u64 extent_flags;
  101. u64 owner = 0;
  102. int ret;
  103. /*
  104. * If we don't have skinny metadata, don't bother doing anything
  105. * different
  106. */
  107. if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
  108. offset = fs_info->nodesize;
  109. metadata = 0;
  110. }
  111. path = btrfs_alloc_path();
  112. if (!path)
  113. return -ENOMEM;
  114. search_again:
  115. key.objectid = bytenr;
  116. key.offset = offset;
  117. if (metadata)
  118. key.type = BTRFS_METADATA_ITEM_KEY;
  119. else
  120. key.type = BTRFS_EXTENT_ITEM_KEY;
  121. extent_root = btrfs_extent_root(fs_info, bytenr);
  122. ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
  123. if (ret < 0)
  124. goto out_free;
  125. if (ret > 0 && key.type == BTRFS_METADATA_ITEM_KEY) {
  126. if (path->slots[0]) {
  127. path->slots[0]--;
  128. btrfs_item_key_to_cpu(path->nodes[0], &key,
  129. path->slots[0]);
  130. if (key.objectid == bytenr &&
  131. key.type == BTRFS_EXTENT_ITEM_KEY &&
  132. key.offset == fs_info->nodesize)
  133. ret = 0;
  134. }
  135. }
  136. if (ret == 0) {
  137. struct extent_buffer *leaf = path->nodes[0];
  138. struct btrfs_extent_item *ei;
  139. const u32 item_size = btrfs_item_size(leaf, path->slots[0]);
  140. if (unlikely(item_size < sizeof(*ei))) {
  141. ret = -EUCLEAN;
  142. btrfs_err(fs_info,
  143. "unexpected extent item size, has %u expect >= %zu",
  144. item_size, sizeof(*ei));
  145. btrfs_abort_transaction(trans, ret);
  146. goto out_free;
  147. }
  148. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  149. num_refs = btrfs_extent_refs(leaf, ei);
  150. if (unlikely(num_refs == 0)) {
  151. ret = -EUCLEAN;
  152. btrfs_err(fs_info,
  153. "unexpected zero reference count for extent item (%llu %u %llu)",
  154. key.objectid, key.type, key.offset);
  155. btrfs_abort_transaction(trans, ret);
  156. goto out_free;
  157. }
  158. extent_flags = btrfs_extent_flags(leaf, ei);
  159. owner = btrfs_get_extent_owner_root(fs_info, leaf, path->slots[0]);
  160. } else {
  161. num_refs = 0;
  162. extent_flags = 0;
  163. ret = 0;
  164. }
  165. delayed_refs = &trans->transaction->delayed_refs;
  166. spin_lock(&delayed_refs->lock);
  167. head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
  168. if (head) {
  169. if (!mutex_trylock(&head->mutex)) {
  170. refcount_inc(&head->refs);
  171. spin_unlock(&delayed_refs->lock);
  172. btrfs_release_path(path);
  173. /*
  174. * Mutex was contended, block until it's released and try
  175. * again
  176. */
  177. mutex_lock(&head->mutex);
  178. mutex_unlock(&head->mutex);
  179. btrfs_put_delayed_ref_head(head);
  180. goto search_again;
  181. }
  182. spin_lock(&head->lock);
  183. if (head->extent_op && head->extent_op->update_flags)
  184. extent_flags |= head->extent_op->flags_to_set;
  185. num_refs += head->ref_mod;
  186. spin_unlock(&head->lock);
  187. mutex_unlock(&head->mutex);
  188. }
  189. spin_unlock(&delayed_refs->lock);
  190. WARN_ON(num_refs == 0);
  191. if (refs)
  192. *refs = num_refs;
  193. if (flags)
  194. *flags = extent_flags;
  195. if (owning_root)
  196. *owning_root = owner;
  197. out_free:
  198. btrfs_free_path(path);
  199. return ret;
  200. }
  201. /*
  202. * Back reference rules. Back refs have three main goals:
  203. *
  204. * 1) differentiate between all holders of references to an extent so that
  205. * when a reference is dropped we can make sure it was a valid reference
  206. * before freeing the extent.
  207. *
  208. * 2) Provide enough information to quickly find the holders of an extent
  209. * if we notice a given block is corrupted or bad.
  210. *
  211. * 3) Make it easy to migrate blocks for FS shrinking or storage pool
  212. * maintenance. This is actually the same as #2, but with a slightly
  213. * different use case.
  214. *
  215. * There are two kinds of back refs. The implicit back refs is optimized
  216. * for pointers in non-shared tree blocks. For a given pointer in a block,
  217. * back refs of this kind provide information about the block's owner tree
  218. * and the pointer's key. These information allow us to find the block by
  219. * b-tree searching. The full back refs is for pointers in tree blocks not
  220. * referenced by their owner trees. The location of tree block is recorded
  221. * in the back refs. Actually the full back refs is generic, and can be
  222. * used in all cases the implicit back refs is used. The major shortcoming
  223. * of the full back refs is its overhead. Every time a tree block gets
  224. * COWed, we have to update back refs entry for all pointers in it.
  225. *
  226. * For a newly allocated tree block, we use implicit back refs for
  227. * pointers in it. This means most tree related operations only involve
  228. * implicit back refs. For a tree block created in old transaction, the
  229. * only way to drop a reference to it is COW it. So we can detect the
  230. * event that tree block loses its owner tree's reference and do the
  231. * back refs conversion.
  232. *
  233. * When a tree block is COWed through a tree, there are four cases:
  234. *
  235. * The reference count of the block is one and the tree is the block's
  236. * owner tree. Nothing to do in this case.
  237. *
  238. * The reference count of the block is one and the tree is not the
  239. * block's owner tree. In this case, full back refs is used for pointers
  240. * in the block. Remove these full back refs, add implicit back refs for
  241. * every pointers in the new block.
  242. *
  243. * The reference count of the block is greater than one and the tree is
  244. * the block's owner tree. In this case, implicit back refs is used for
  245. * pointers in the block. Add full back refs for every pointers in the
  246. * block, increase lower level extents' reference counts. The original
  247. * implicit back refs are entailed to the new block.
  248. *
  249. * The reference count of the block is greater than one and the tree is
  250. * not the block's owner tree. Add implicit back refs for every pointer in
  251. * the new block, increase lower level extents' reference count.
  252. *
  253. * Back Reference Key composing:
  254. *
  255. * The key objectid corresponds to the first byte in the extent,
  256. * The key type is used to differentiate between types of back refs.
  257. * There are different meanings of the key offset for different types
  258. * of back refs.
  259. *
  260. * File extents can be referenced by:
  261. *
  262. * - multiple snapshots, subvolumes, or different generations in one subvol
  263. * - different files inside a single subvolume
  264. * - different offsets inside a file (bookend extents in file.c)
  265. *
  266. * The extent ref structure for the implicit back refs has fields for:
  267. *
  268. * - Objectid of the subvolume root
  269. * - objectid of the file holding the reference
  270. * - original offset in the file
  271. * - how many bookend extents
  272. *
  273. * The key offset for the implicit back refs is hash of the first
  274. * three fields.
  275. *
  276. * The extent ref structure for the full back refs has field for:
  277. *
  278. * - number of pointers in the tree leaf
  279. *
  280. * The key offset for the implicit back refs is the first byte of
  281. * the tree leaf
  282. *
  283. * When a file extent is allocated, The implicit back refs is used.
  284. * the fields are filled in:
  285. *
  286. * (root_key.objectid, inode objectid, offset in file, 1)
  287. *
  288. * When a file extent is removed file truncation, we find the
  289. * corresponding implicit back refs and check the following fields:
  290. *
  291. * (btrfs_header_owner(leaf), inode objectid, offset in file)
  292. *
  293. * Btree extents can be referenced by:
  294. *
  295. * - Different subvolumes
  296. *
  297. * Both the implicit back refs and the full back refs for tree blocks
  298. * only consist of key. The key offset for the implicit back refs is
  299. * objectid of block's owner tree. The key offset for the full back refs
  300. * is the first byte of parent block.
  301. *
  302. * When implicit back refs is used, information about the lowest key and
  303. * level of the tree block are required. These information are stored in
  304. * tree block info structure.
  305. */
  306. /*
  307. * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
  308. * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
  309. * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
  310. */
  311. int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
  312. struct btrfs_extent_inline_ref *iref,
  313. enum btrfs_inline_ref_type is_data)
  314. {
  315. struct btrfs_fs_info *fs_info = eb->fs_info;
  316. int type = btrfs_extent_inline_ref_type(eb, iref);
  317. u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
  318. if (type == BTRFS_EXTENT_OWNER_REF_KEY) {
  319. ASSERT(btrfs_fs_incompat(fs_info, SIMPLE_QUOTA));
  320. return type;
  321. }
  322. if (type == BTRFS_TREE_BLOCK_REF_KEY ||
  323. type == BTRFS_SHARED_BLOCK_REF_KEY ||
  324. type == BTRFS_SHARED_DATA_REF_KEY ||
  325. type == BTRFS_EXTENT_DATA_REF_KEY) {
  326. if (is_data == BTRFS_REF_TYPE_BLOCK) {
  327. if (type == BTRFS_TREE_BLOCK_REF_KEY)
  328. return type;
  329. if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
  330. ASSERT(fs_info);
  331. /*
  332. * Every shared one has parent tree block,
  333. * which must be aligned to sector size.
  334. */
  335. if (offset && IS_ALIGNED(offset, fs_info->sectorsize))
  336. return type;
  337. }
  338. } else if (is_data == BTRFS_REF_TYPE_DATA) {
  339. if (type == BTRFS_EXTENT_DATA_REF_KEY)
  340. return type;
  341. if (type == BTRFS_SHARED_DATA_REF_KEY) {
  342. ASSERT(fs_info);
  343. /*
  344. * Every shared one has parent tree block,
  345. * which must be aligned to sector size.
  346. */
  347. if (offset &&
  348. IS_ALIGNED(offset, fs_info->sectorsize))
  349. return type;
  350. }
  351. } else {
  352. ASSERT(is_data == BTRFS_REF_TYPE_ANY);
  353. return type;
  354. }
  355. }
  356. WARN_ON(1);
  357. btrfs_print_leaf(eb);
  358. btrfs_err(fs_info,
  359. "eb %llu iref 0x%lx invalid extent inline ref type %d",
  360. eb->start, (unsigned long)iref, type);
  361. return BTRFS_REF_TYPE_INVALID;
  362. }
  363. u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
  364. {
  365. u32 high_crc = ~(u32)0;
  366. u32 low_crc = ~(u32)0;
  367. __le64 lenum;
  368. lenum = cpu_to_le64(root_objectid);
  369. high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
  370. lenum = cpu_to_le64(owner);
  371. low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
  372. lenum = cpu_to_le64(offset);
  373. low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
  374. return ((u64)high_crc << 31) ^ (u64)low_crc;
  375. }
  376. static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
  377. struct btrfs_extent_data_ref *ref)
  378. {
  379. return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
  380. btrfs_extent_data_ref_objectid(leaf, ref),
  381. btrfs_extent_data_ref_offset(leaf, ref));
  382. }
  383. static int match_extent_data_ref(struct extent_buffer *leaf,
  384. struct btrfs_extent_data_ref *ref,
  385. u64 root_objectid, u64 owner, u64 offset)
  386. {
  387. if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
  388. btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
  389. btrfs_extent_data_ref_offset(leaf, ref) != offset)
  390. return 0;
  391. return 1;
  392. }
  393. static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
  394. struct btrfs_path *path,
  395. u64 bytenr, u64 parent,
  396. u64 root_objectid,
  397. u64 owner, u64 offset)
  398. {
  399. struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
  400. struct btrfs_key key;
  401. struct btrfs_extent_data_ref *ref;
  402. struct extent_buffer *leaf;
  403. u32 nritems;
  404. int recow;
  405. int ret;
  406. key.objectid = bytenr;
  407. if (parent) {
  408. key.type = BTRFS_SHARED_DATA_REF_KEY;
  409. key.offset = parent;
  410. } else {
  411. key.type = BTRFS_EXTENT_DATA_REF_KEY;
  412. key.offset = hash_extent_data_ref(root_objectid,
  413. owner, offset);
  414. }
  415. again:
  416. recow = 0;
  417. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  418. if (ret < 0)
  419. return ret;
  420. if (parent) {
  421. if (ret)
  422. return -ENOENT;
  423. return 0;
  424. }
  425. ret = -ENOENT;
  426. leaf = path->nodes[0];
  427. nritems = btrfs_header_nritems(leaf);
  428. while (1) {
  429. if (path->slots[0] >= nritems) {
  430. ret = btrfs_next_leaf(root, path);
  431. if (ret) {
  432. if (ret > 0)
  433. return -ENOENT;
  434. return ret;
  435. }
  436. leaf = path->nodes[0];
  437. nritems = btrfs_header_nritems(leaf);
  438. recow = 1;
  439. }
  440. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  441. if (key.objectid != bytenr ||
  442. key.type != BTRFS_EXTENT_DATA_REF_KEY)
  443. goto fail;
  444. ref = btrfs_item_ptr(leaf, path->slots[0],
  445. struct btrfs_extent_data_ref);
  446. if (match_extent_data_ref(leaf, ref, root_objectid,
  447. owner, offset)) {
  448. if (recow) {
  449. btrfs_release_path(path);
  450. goto again;
  451. }
  452. ret = 0;
  453. break;
  454. }
  455. path->slots[0]++;
  456. }
  457. fail:
  458. return ret;
  459. }
  460. static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
  461. struct btrfs_path *path,
  462. struct btrfs_delayed_ref_node *node,
  463. u64 bytenr)
  464. {
  465. struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
  466. struct btrfs_key key;
  467. struct extent_buffer *leaf;
  468. u64 owner = btrfs_delayed_ref_owner(node);
  469. u64 offset = btrfs_delayed_ref_offset(node);
  470. u32 size;
  471. u32 num_refs;
  472. int ret;
  473. key.objectid = bytenr;
  474. if (node->parent) {
  475. key.type = BTRFS_SHARED_DATA_REF_KEY;
  476. key.offset = node->parent;
  477. size = sizeof(struct btrfs_shared_data_ref);
  478. } else {
  479. key.type = BTRFS_EXTENT_DATA_REF_KEY;
  480. key.offset = hash_extent_data_ref(node->ref_root, owner, offset);
  481. size = sizeof(struct btrfs_extent_data_ref);
  482. }
  483. ret = btrfs_insert_empty_item(trans, root, path, &key, size);
  484. if (ret && ret != -EEXIST)
  485. goto fail;
  486. leaf = path->nodes[0];
  487. if (node->parent) {
  488. struct btrfs_shared_data_ref *ref;
  489. ref = btrfs_item_ptr(leaf, path->slots[0],
  490. struct btrfs_shared_data_ref);
  491. if (ret == 0) {
  492. btrfs_set_shared_data_ref_count(leaf, ref, node->ref_mod);
  493. } else {
  494. num_refs = btrfs_shared_data_ref_count(leaf, ref);
  495. num_refs += node->ref_mod;
  496. btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
  497. }
  498. } else {
  499. struct btrfs_extent_data_ref *ref;
  500. while (ret == -EEXIST) {
  501. ref = btrfs_item_ptr(leaf, path->slots[0],
  502. struct btrfs_extent_data_ref);
  503. if (match_extent_data_ref(leaf, ref, node->ref_root,
  504. owner, offset))
  505. break;
  506. btrfs_release_path(path);
  507. key.offset++;
  508. ret = btrfs_insert_empty_item(trans, root, path, &key,
  509. size);
  510. if (ret && ret != -EEXIST)
  511. goto fail;
  512. leaf = path->nodes[0];
  513. }
  514. ref = btrfs_item_ptr(leaf, path->slots[0],
  515. struct btrfs_extent_data_ref);
  516. if (ret == 0) {
  517. btrfs_set_extent_data_ref_root(leaf, ref, node->ref_root);
  518. btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
  519. btrfs_set_extent_data_ref_offset(leaf, ref, offset);
  520. btrfs_set_extent_data_ref_count(leaf, ref, node->ref_mod);
  521. } else {
  522. num_refs = btrfs_extent_data_ref_count(leaf, ref);
  523. num_refs += node->ref_mod;
  524. btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
  525. }
  526. }
  527. btrfs_mark_buffer_dirty(trans, leaf);
  528. ret = 0;
  529. fail:
  530. btrfs_release_path(path);
  531. return ret;
  532. }
  533. static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
  534. struct btrfs_root *root,
  535. struct btrfs_path *path,
  536. int refs_to_drop)
  537. {
  538. struct btrfs_key key;
  539. struct btrfs_extent_data_ref *ref1 = NULL;
  540. struct btrfs_shared_data_ref *ref2 = NULL;
  541. struct extent_buffer *leaf;
  542. u32 num_refs = 0;
  543. int ret = 0;
  544. leaf = path->nodes[0];
  545. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  546. if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
  547. ref1 = btrfs_item_ptr(leaf, path->slots[0],
  548. struct btrfs_extent_data_ref);
  549. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  550. } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
  551. ref2 = btrfs_item_ptr(leaf, path->slots[0],
  552. struct btrfs_shared_data_ref);
  553. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  554. } else {
  555. btrfs_err(trans->fs_info,
  556. "unrecognized backref key (%llu %u %llu)",
  557. key.objectid, key.type, key.offset);
  558. btrfs_abort_transaction(trans, -EUCLEAN);
  559. return -EUCLEAN;
  560. }
  561. BUG_ON(num_refs < refs_to_drop);
  562. num_refs -= refs_to_drop;
  563. if (num_refs == 0) {
  564. ret = btrfs_del_item(trans, root, path);
  565. } else {
  566. if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
  567. btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
  568. else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
  569. btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
  570. btrfs_mark_buffer_dirty(trans, leaf);
  571. }
  572. return ret;
  573. }
  574. static noinline u32 extent_data_ref_count(struct btrfs_path *path,
  575. struct btrfs_extent_inline_ref *iref)
  576. {
  577. struct btrfs_key key;
  578. struct extent_buffer *leaf;
  579. struct btrfs_extent_data_ref *ref1;
  580. struct btrfs_shared_data_ref *ref2;
  581. u32 num_refs = 0;
  582. int type;
  583. leaf = path->nodes[0];
  584. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  585. if (iref) {
  586. /*
  587. * If type is invalid, we should have bailed out earlier than
  588. * this call.
  589. */
  590. type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
  591. ASSERT(type != BTRFS_REF_TYPE_INVALID);
  592. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  593. ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
  594. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  595. } else {
  596. ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
  597. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  598. }
  599. } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
  600. ref1 = btrfs_item_ptr(leaf, path->slots[0],
  601. struct btrfs_extent_data_ref);
  602. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  603. } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
  604. ref2 = btrfs_item_ptr(leaf, path->slots[0],
  605. struct btrfs_shared_data_ref);
  606. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  607. } else {
  608. WARN_ON(1);
  609. }
  610. return num_refs;
  611. }
  612. static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
  613. struct btrfs_path *path,
  614. u64 bytenr, u64 parent,
  615. u64 root_objectid)
  616. {
  617. struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
  618. struct btrfs_key key;
  619. int ret;
  620. key.objectid = bytenr;
  621. if (parent) {
  622. key.type = BTRFS_SHARED_BLOCK_REF_KEY;
  623. key.offset = parent;
  624. } else {
  625. key.type = BTRFS_TREE_BLOCK_REF_KEY;
  626. key.offset = root_objectid;
  627. }
  628. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  629. if (ret > 0)
  630. ret = -ENOENT;
  631. return ret;
  632. }
  633. static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
  634. struct btrfs_path *path,
  635. struct btrfs_delayed_ref_node *node,
  636. u64 bytenr)
  637. {
  638. struct btrfs_root *root = btrfs_extent_root(trans->fs_info, bytenr);
  639. struct btrfs_key key;
  640. int ret;
  641. key.objectid = bytenr;
  642. if (node->parent) {
  643. key.type = BTRFS_SHARED_BLOCK_REF_KEY;
  644. key.offset = node->parent;
  645. } else {
  646. key.type = BTRFS_TREE_BLOCK_REF_KEY;
  647. key.offset = node->ref_root;
  648. }
  649. ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
  650. btrfs_release_path(path);
  651. return ret;
  652. }
  653. static inline int extent_ref_type(u64 parent, u64 owner)
  654. {
  655. int type;
  656. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  657. if (parent > 0)
  658. type = BTRFS_SHARED_BLOCK_REF_KEY;
  659. else
  660. type = BTRFS_TREE_BLOCK_REF_KEY;
  661. } else {
  662. if (parent > 0)
  663. type = BTRFS_SHARED_DATA_REF_KEY;
  664. else
  665. type = BTRFS_EXTENT_DATA_REF_KEY;
  666. }
  667. return type;
  668. }
  669. static int find_next_key(struct btrfs_path *path, int level,
  670. struct btrfs_key *key)
  671. {
  672. for (; level < BTRFS_MAX_LEVEL; level++) {
  673. if (!path->nodes[level])
  674. break;
  675. if (path->slots[level] + 1 >=
  676. btrfs_header_nritems(path->nodes[level]))
  677. continue;
  678. if (level == 0)
  679. btrfs_item_key_to_cpu(path->nodes[level], key,
  680. path->slots[level] + 1);
  681. else
  682. btrfs_node_key_to_cpu(path->nodes[level], key,
  683. path->slots[level] + 1);
  684. return 0;
  685. }
  686. return 1;
  687. }
  688. /*
  689. * look for inline back ref. if back ref is found, *ref_ret is set
  690. * to the address of inline back ref, and 0 is returned.
  691. *
  692. * if back ref isn't found, *ref_ret is set to the address where it
  693. * should be inserted, and -ENOENT is returned.
  694. *
  695. * if insert is true and there are too many inline back refs, the path
  696. * points to the extent item, and -EAGAIN is returned.
  697. *
  698. * NOTE: inline back refs are ordered in the same way that back ref
  699. * items in the tree are ordered.
  700. */
  701. static noinline_for_stack
  702. int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
  703. struct btrfs_path *path,
  704. struct btrfs_extent_inline_ref **ref_ret,
  705. u64 bytenr, u64 num_bytes,
  706. u64 parent, u64 root_objectid,
  707. u64 owner, u64 offset, int insert)
  708. {
  709. struct btrfs_fs_info *fs_info = trans->fs_info;
  710. struct btrfs_root *root = btrfs_extent_root(fs_info, bytenr);
  711. struct btrfs_key key;
  712. struct extent_buffer *leaf;
  713. struct btrfs_extent_item *ei;
  714. struct btrfs_extent_inline_ref *iref;
  715. u64 flags;
  716. u64 item_size;
  717. unsigned long ptr;
  718. unsigned long end;
  719. int extra_size;
  720. int type;
  721. int want;
  722. int ret;
  723. bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
  724. int needed;
  725. key.objectid = bytenr;
  726. key.type = BTRFS_EXTENT_ITEM_KEY;
  727. key.offset = num_bytes;
  728. want = extent_ref_type(parent, owner);
  729. if (insert) {
  730. extra_size = btrfs_extent_inline_ref_size(want);
  731. path->search_for_extension = 1;
  732. path->keep_locks = 1;
  733. } else
  734. extra_size = -1;
  735. /*
  736. * Owner is our level, so we can just add one to get the level for the
  737. * block we are interested in.
  738. */
  739. if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
  740. key.type = BTRFS_METADATA_ITEM_KEY;
  741. key.offset = owner;
  742. }
  743. again:
  744. ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
  745. if (ret < 0)
  746. goto out;
  747. /*
  748. * We may be a newly converted file system which still has the old fat
  749. * extent entries for metadata, so try and see if we have one of those.
  750. */
  751. if (ret > 0 && skinny_metadata) {
  752. skinny_metadata = false;
  753. if (path->slots[0]) {
  754. path->slots[0]--;
  755. btrfs_item_key_to_cpu(path->nodes[0], &key,
  756. path->slots[0]);
  757. if (key.objectid == bytenr &&
  758. key.type == BTRFS_EXTENT_ITEM_KEY &&
  759. key.offset == num_bytes)
  760. ret = 0;
  761. }
  762. if (ret) {
  763. key.objectid = bytenr;
  764. key.type = BTRFS_EXTENT_ITEM_KEY;
  765. key.offset = num_bytes;
  766. btrfs_release_path(path);
  767. goto again;
  768. }
  769. }
  770. if (ret && !insert) {
  771. ret = -ENOENT;
  772. goto out;
  773. } else if (WARN_ON(ret)) {
  774. btrfs_print_leaf(path->nodes[0]);
  775. btrfs_err(fs_info,
  776. "extent item not found for insert, bytenr %llu num_bytes %llu parent %llu root_objectid %llu owner %llu offset %llu",
  777. bytenr, num_bytes, parent, root_objectid, owner,
  778. offset);
  779. ret = -EUCLEAN;
  780. goto out;
  781. }
  782. leaf = path->nodes[0];
  783. item_size = btrfs_item_size(leaf, path->slots[0]);
  784. if (unlikely(item_size < sizeof(*ei))) {
  785. ret = -EUCLEAN;
  786. btrfs_err(fs_info,
  787. "unexpected extent item size, has %llu expect >= %zu",
  788. item_size, sizeof(*ei));
  789. btrfs_abort_transaction(trans, ret);
  790. goto out;
  791. }
  792. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  793. flags = btrfs_extent_flags(leaf, ei);
  794. ptr = (unsigned long)(ei + 1);
  795. end = (unsigned long)ei + item_size;
  796. if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
  797. ptr += sizeof(struct btrfs_tree_block_info);
  798. BUG_ON(ptr > end);
  799. }
  800. if (owner >= BTRFS_FIRST_FREE_OBJECTID)
  801. needed = BTRFS_REF_TYPE_DATA;
  802. else
  803. needed = BTRFS_REF_TYPE_BLOCK;
  804. ret = -ENOENT;
  805. while (ptr < end) {
  806. iref = (struct btrfs_extent_inline_ref *)ptr;
  807. type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
  808. if (type == BTRFS_EXTENT_OWNER_REF_KEY) {
  809. ASSERT(btrfs_fs_incompat(fs_info, SIMPLE_QUOTA));
  810. ptr += btrfs_extent_inline_ref_size(type);
  811. continue;
  812. }
  813. if (type == BTRFS_REF_TYPE_INVALID) {
  814. ret = -EUCLEAN;
  815. goto out;
  816. }
  817. if (want < type)
  818. break;
  819. if (want > type) {
  820. ptr += btrfs_extent_inline_ref_size(type);
  821. continue;
  822. }
  823. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  824. struct btrfs_extent_data_ref *dref;
  825. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  826. if (match_extent_data_ref(leaf, dref, root_objectid,
  827. owner, offset)) {
  828. ret = 0;
  829. break;
  830. }
  831. if (hash_extent_data_ref_item(leaf, dref) <
  832. hash_extent_data_ref(root_objectid, owner, offset))
  833. break;
  834. } else {
  835. u64 ref_offset;
  836. ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
  837. if (parent > 0) {
  838. if (parent == ref_offset) {
  839. ret = 0;
  840. break;
  841. }
  842. if (ref_offset < parent)
  843. break;
  844. } else {
  845. if (root_objectid == ref_offset) {
  846. ret = 0;
  847. break;
  848. }
  849. if (ref_offset < root_objectid)
  850. break;
  851. }
  852. }
  853. ptr += btrfs_extent_inline_ref_size(type);
  854. }
  855. if (unlikely(ptr > end)) {
  856. ret = -EUCLEAN;
  857. btrfs_print_leaf(path->nodes[0]);
  858. btrfs_crit(fs_info,
  859. "overrun extent record at slot %d while looking for inline extent for root %llu owner %llu offset %llu parent %llu",
  860. path->slots[0], root_objectid, owner, offset, parent);
  861. goto out;
  862. }
  863. if (ret == -ENOENT && insert) {
  864. if (item_size + extra_size >=
  865. BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
  866. ret = -EAGAIN;
  867. goto out;
  868. }
  869. /*
  870. * To add new inline back ref, we have to make sure
  871. * there is no corresponding back ref item.
  872. * For simplicity, we just do not add new inline back
  873. * ref if there is any kind of item for this block
  874. */
  875. if (find_next_key(path, 0, &key) == 0 &&
  876. key.objectid == bytenr &&
  877. key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
  878. ret = -EAGAIN;
  879. goto out;
  880. }
  881. }
  882. *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
  883. out:
  884. if (insert) {
  885. path->keep_locks = 0;
  886. path->search_for_extension = 0;
  887. btrfs_unlock_up_safe(path, 1);
  888. }
  889. return ret;
  890. }
  891. /*
  892. * helper to add new inline back ref
  893. */
  894. static noinline_for_stack
  895. void setup_inline_extent_backref(struct btrfs_trans_handle *trans,
  896. struct btrfs_path *path,
  897. struct btrfs_extent_inline_ref *iref,
  898. u64 parent, u64 root_objectid,
  899. u64 owner, u64 offset, int refs_to_add,
  900. struct btrfs_delayed_extent_op *extent_op)
  901. {
  902. struct extent_buffer *leaf;
  903. struct btrfs_extent_item *ei;
  904. unsigned long ptr;
  905. unsigned long end;
  906. unsigned long item_offset;
  907. u64 refs;
  908. int size;
  909. int type;
  910. leaf = path->nodes[0];
  911. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  912. item_offset = (unsigned long)iref - (unsigned long)ei;
  913. type = extent_ref_type(parent, owner);
  914. size = btrfs_extent_inline_ref_size(type);
  915. btrfs_extend_item(trans, path, size);
  916. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  917. refs = btrfs_extent_refs(leaf, ei);
  918. refs += refs_to_add;
  919. btrfs_set_extent_refs(leaf, ei, refs);
  920. if (extent_op)
  921. __run_delayed_extent_op(extent_op, leaf, ei);
  922. ptr = (unsigned long)ei + item_offset;
  923. end = (unsigned long)ei + btrfs_item_size(leaf, path->slots[0]);
  924. if (ptr < end - size)
  925. memmove_extent_buffer(leaf, ptr + size, ptr,
  926. end - size - ptr);
  927. iref = (struct btrfs_extent_inline_ref *)ptr;
  928. btrfs_set_extent_inline_ref_type(leaf, iref, type);
  929. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  930. struct btrfs_extent_data_ref *dref;
  931. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  932. btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
  933. btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
  934. btrfs_set_extent_data_ref_offset(leaf, dref, offset);
  935. btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
  936. } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
  937. struct btrfs_shared_data_ref *sref;
  938. sref = (struct btrfs_shared_data_ref *)(iref + 1);
  939. btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
  940. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  941. } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
  942. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  943. } else {
  944. btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
  945. }
  946. btrfs_mark_buffer_dirty(trans, leaf);
  947. }
  948. static int lookup_extent_backref(struct btrfs_trans_handle *trans,
  949. struct btrfs_path *path,
  950. struct btrfs_extent_inline_ref **ref_ret,
  951. u64 bytenr, u64 num_bytes, u64 parent,
  952. u64 root_objectid, u64 owner, u64 offset)
  953. {
  954. int ret;
  955. ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
  956. num_bytes, parent, root_objectid,
  957. owner, offset, 0);
  958. if (ret != -ENOENT)
  959. return ret;
  960. btrfs_release_path(path);
  961. *ref_ret = NULL;
  962. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  963. ret = lookup_tree_block_ref(trans, path, bytenr, parent,
  964. root_objectid);
  965. } else {
  966. ret = lookup_extent_data_ref(trans, path, bytenr, parent,
  967. root_objectid, owner, offset);
  968. }
  969. return ret;
  970. }
  971. /*
  972. * helper to update/remove inline back ref
  973. */
  974. static noinline_for_stack int update_inline_extent_backref(
  975. struct btrfs_trans_handle *trans,
  976. struct btrfs_path *path,
  977. struct btrfs_extent_inline_ref *iref,
  978. int refs_to_mod,
  979. struct btrfs_delayed_extent_op *extent_op)
  980. {
  981. struct extent_buffer *leaf = path->nodes[0];
  982. struct btrfs_fs_info *fs_info = leaf->fs_info;
  983. struct btrfs_extent_item *ei;
  984. struct btrfs_extent_data_ref *dref = NULL;
  985. struct btrfs_shared_data_ref *sref = NULL;
  986. unsigned long ptr;
  987. unsigned long end;
  988. u32 item_size;
  989. int size;
  990. int type;
  991. u64 refs;
  992. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  993. refs = btrfs_extent_refs(leaf, ei);
  994. if (unlikely(refs_to_mod < 0 && refs + refs_to_mod <= 0)) {
  995. struct btrfs_key key;
  996. u32 extent_size;
  997. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  998. if (key.type == BTRFS_METADATA_ITEM_KEY)
  999. extent_size = fs_info->nodesize;
  1000. else
  1001. extent_size = key.offset;
  1002. btrfs_print_leaf(leaf);
  1003. btrfs_err(fs_info,
  1004. "invalid refs_to_mod for extent %llu num_bytes %u, has %d expect >= -%llu",
  1005. key.objectid, extent_size, refs_to_mod, refs);
  1006. return -EUCLEAN;
  1007. }
  1008. refs += refs_to_mod;
  1009. btrfs_set_extent_refs(leaf, ei, refs);
  1010. if (extent_op)
  1011. __run_delayed_extent_op(extent_op, leaf, ei);
  1012. type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
  1013. /*
  1014. * Function btrfs_get_extent_inline_ref_type() has already printed
  1015. * error messages.
  1016. */
  1017. if (unlikely(type == BTRFS_REF_TYPE_INVALID))
  1018. return -EUCLEAN;
  1019. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1020. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  1021. refs = btrfs_extent_data_ref_count(leaf, dref);
  1022. } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
  1023. sref = (struct btrfs_shared_data_ref *)(iref + 1);
  1024. refs = btrfs_shared_data_ref_count(leaf, sref);
  1025. } else {
  1026. refs = 1;
  1027. /*
  1028. * For tree blocks we can only drop one ref for it, and tree
  1029. * blocks should not have refs > 1.
  1030. *
  1031. * Furthermore if we're inserting a new inline backref, we
  1032. * won't reach this path either. That would be
  1033. * setup_inline_extent_backref().
  1034. */
  1035. if (unlikely(refs_to_mod != -1)) {
  1036. struct btrfs_key key;
  1037. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1038. btrfs_print_leaf(leaf);
  1039. btrfs_err(fs_info,
  1040. "invalid refs_to_mod for tree block %llu, has %d expect -1",
  1041. key.objectid, refs_to_mod);
  1042. return -EUCLEAN;
  1043. }
  1044. }
  1045. if (unlikely(refs_to_mod < 0 && refs < -refs_to_mod)) {
  1046. struct btrfs_key key;
  1047. u32 extent_size;
  1048. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1049. if (key.type == BTRFS_METADATA_ITEM_KEY)
  1050. extent_size = fs_info->nodesize;
  1051. else
  1052. extent_size = key.offset;
  1053. btrfs_print_leaf(leaf);
  1054. btrfs_err(fs_info,
  1055. "invalid refs_to_mod for backref entry, iref %lu extent %llu num_bytes %u, has %d expect >= -%llu",
  1056. (unsigned long)iref, key.objectid, extent_size,
  1057. refs_to_mod, refs);
  1058. return -EUCLEAN;
  1059. }
  1060. refs += refs_to_mod;
  1061. if (refs > 0) {
  1062. if (type == BTRFS_EXTENT_DATA_REF_KEY)
  1063. btrfs_set_extent_data_ref_count(leaf, dref, refs);
  1064. else
  1065. btrfs_set_shared_data_ref_count(leaf, sref, refs);
  1066. } else {
  1067. size = btrfs_extent_inline_ref_size(type);
  1068. item_size = btrfs_item_size(leaf, path->slots[0]);
  1069. ptr = (unsigned long)iref;
  1070. end = (unsigned long)ei + item_size;
  1071. if (ptr + size < end)
  1072. memmove_extent_buffer(leaf, ptr, ptr + size,
  1073. end - ptr - size);
  1074. item_size -= size;
  1075. btrfs_truncate_item(trans, path, item_size, 1);
  1076. }
  1077. btrfs_mark_buffer_dirty(trans, leaf);
  1078. return 0;
  1079. }
  1080. static noinline_for_stack
  1081. int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
  1082. struct btrfs_path *path,
  1083. u64 bytenr, u64 num_bytes, u64 parent,
  1084. u64 root_objectid, u64 owner,
  1085. u64 offset, int refs_to_add,
  1086. struct btrfs_delayed_extent_op *extent_op)
  1087. {
  1088. struct btrfs_extent_inline_ref *iref;
  1089. int ret;
  1090. ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
  1091. num_bytes, parent, root_objectid,
  1092. owner, offset, 1);
  1093. if (ret == 0) {
  1094. /*
  1095. * We're adding refs to a tree block we already own, this
  1096. * should not happen at all.
  1097. */
  1098. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1099. btrfs_print_leaf(path->nodes[0]);
  1100. btrfs_crit(trans->fs_info,
  1101. "adding refs to an existing tree ref, bytenr %llu num_bytes %llu root_objectid %llu slot %u",
  1102. bytenr, num_bytes, root_objectid, path->slots[0]);
  1103. return -EUCLEAN;
  1104. }
  1105. ret = update_inline_extent_backref(trans, path, iref,
  1106. refs_to_add, extent_op);
  1107. } else if (ret == -ENOENT) {
  1108. setup_inline_extent_backref(trans, path, iref, parent,
  1109. root_objectid, owner, offset,
  1110. refs_to_add, extent_op);
  1111. ret = 0;
  1112. }
  1113. return ret;
  1114. }
  1115. static int remove_extent_backref(struct btrfs_trans_handle *trans,
  1116. struct btrfs_root *root,
  1117. struct btrfs_path *path,
  1118. struct btrfs_extent_inline_ref *iref,
  1119. int refs_to_drop, int is_data)
  1120. {
  1121. int ret = 0;
  1122. BUG_ON(!is_data && refs_to_drop != 1);
  1123. if (iref)
  1124. ret = update_inline_extent_backref(trans, path, iref,
  1125. -refs_to_drop, NULL);
  1126. else if (is_data)
  1127. ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
  1128. else
  1129. ret = btrfs_del_item(trans, root, path);
  1130. return ret;
  1131. }
  1132. static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
  1133. u64 *discarded_bytes)
  1134. {
  1135. int j, ret = 0;
  1136. u64 bytes_left, end;
  1137. u64 aligned_start = ALIGN(start, 1 << SECTOR_SHIFT);
  1138. /* Adjust the range to be aligned to 512B sectors if necessary. */
  1139. if (start != aligned_start) {
  1140. len -= aligned_start - start;
  1141. len = round_down(len, 1 << SECTOR_SHIFT);
  1142. start = aligned_start;
  1143. }
  1144. *discarded_bytes = 0;
  1145. if (!len)
  1146. return 0;
  1147. end = start + len;
  1148. bytes_left = len;
  1149. /* Skip any superblocks on this device. */
  1150. for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
  1151. u64 sb_start = btrfs_sb_offset(j);
  1152. u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
  1153. u64 size = sb_start - start;
  1154. if (!in_range(sb_start, start, bytes_left) &&
  1155. !in_range(sb_end, start, bytes_left) &&
  1156. !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
  1157. continue;
  1158. /*
  1159. * Superblock spans beginning of range. Adjust start and
  1160. * try again.
  1161. */
  1162. if (sb_start <= start) {
  1163. start += sb_end - start;
  1164. if (start > end) {
  1165. bytes_left = 0;
  1166. break;
  1167. }
  1168. bytes_left = end - start;
  1169. continue;
  1170. }
  1171. if (size) {
  1172. ret = blkdev_issue_discard(bdev, start >> SECTOR_SHIFT,
  1173. size >> SECTOR_SHIFT,
  1174. GFP_NOFS);
  1175. if (!ret)
  1176. *discarded_bytes += size;
  1177. else if (ret != -EOPNOTSUPP)
  1178. return ret;
  1179. }
  1180. start = sb_end;
  1181. if (start > end) {
  1182. bytes_left = 0;
  1183. break;
  1184. }
  1185. bytes_left = end - start;
  1186. }
  1187. while (bytes_left) {
  1188. u64 bytes_to_discard = min(BTRFS_MAX_DISCARD_CHUNK_SIZE, bytes_left);
  1189. ret = blkdev_issue_discard(bdev, start >> SECTOR_SHIFT,
  1190. bytes_to_discard >> SECTOR_SHIFT,
  1191. GFP_NOFS);
  1192. if (ret) {
  1193. if (ret != -EOPNOTSUPP)
  1194. break;
  1195. continue;
  1196. }
  1197. start += bytes_to_discard;
  1198. bytes_left -= bytes_to_discard;
  1199. *discarded_bytes += bytes_to_discard;
  1200. if (btrfs_trim_interrupted()) {
  1201. ret = -ERESTARTSYS;
  1202. break;
  1203. }
  1204. }
  1205. return ret;
  1206. }
  1207. static int do_discard_extent(struct btrfs_discard_stripe *stripe, u64 *bytes)
  1208. {
  1209. struct btrfs_device *dev = stripe->dev;
  1210. struct btrfs_fs_info *fs_info = dev->fs_info;
  1211. struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
  1212. u64 phys = stripe->physical;
  1213. u64 len = stripe->length;
  1214. u64 discarded = 0;
  1215. int ret = 0;
  1216. /* Zone reset on a zoned filesystem */
  1217. if (btrfs_can_zone_reset(dev, phys, len)) {
  1218. u64 src_disc;
  1219. ret = btrfs_reset_device_zone(dev, phys, len, &discarded);
  1220. if (ret)
  1221. goto out;
  1222. if (!btrfs_dev_replace_is_ongoing(dev_replace) ||
  1223. dev != dev_replace->srcdev)
  1224. goto out;
  1225. src_disc = discarded;
  1226. /* Send to replace target as well */
  1227. ret = btrfs_reset_device_zone(dev_replace->tgtdev, phys, len,
  1228. &discarded);
  1229. discarded += src_disc;
  1230. } else if (bdev_max_discard_sectors(stripe->dev->bdev)) {
  1231. ret = btrfs_issue_discard(dev->bdev, phys, len, &discarded);
  1232. } else {
  1233. ret = 0;
  1234. *bytes = 0;
  1235. }
  1236. out:
  1237. *bytes = discarded;
  1238. return ret;
  1239. }
  1240. int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
  1241. u64 num_bytes, u64 *actual_bytes)
  1242. {
  1243. int ret = 0;
  1244. u64 discarded_bytes = 0;
  1245. u64 end = bytenr + num_bytes;
  1246. u64 cur = bytenr;
  1247. /*
  1248. * Avoid races with device replace and make sure the devices in the
  1249. * stripes don't go away while we are discarding.
  1250. */
  1251. btrfs_bio_counter_inc_blocked(fs_info);
  1252. while (cur < end) {
  1253. struct btrfs_discard_stripe *stripes;
  1254. unsigned int num_stripes;
  1255. int i;
  1256. num_bytes = end - cur;
  1257. stripes = btrfs_map_discard(fs_info, cur, &num_bytes, &num_stripes);
  1258. if (IS_ERR(stripes)) {
  1259. ret = PTR_ERR(stripes);
  1260. if (ret == -EOPNOTSUPP)
  1261. ret = 0;
  1262. break;
  1263. }
  1264. for (i = 0; i < num_stripes; i++) {
  1265. struct btrfs_discard_stripe *stripe = stripes + i;
  1266. u64 bytes;
  1267. if (!stripe->dev->bdev) {
  1268. ASSERT(btrfs_test_opt(fs_info, DEGRADED));
  1269. continue;
  1270. }
  1271. if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
  1272. &stripe->dev->dev_state))
  1273. continue;
  1274. ret = do_discard_extent(stripe, &bytes);
  1275. if (ret) {
  1276. /*
  1277. * Keep going if discard is not supported by the
  1278. * device.
  1279. */
  1280. if (ret != -EOPNOTSUPP)
  1281. break;
  1282. ret = 0;
  1283. } else {
  1284. discarded_bytes += bytes;
  1285. }
  1286. }
  1287. kfree(stripes);
  1288. if (ret)
  1289. break;
  1290. cur += num_bytes;
  1291. }
  1292. btrfs_bio_counter_dec(fs_info);
  1293. if (actual_bytes)
  1294. *actual_bytes = discarded_bytes;
  1295. return ret;
  1296. }
  1297. /* Can return -ENOMEM */
  1298. int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
  1299. struct btrfs_ref *generic_ref)
  1300. {
  1301. struct btrfs_fs_info *fs_info = trans->fs_info;
  1302. int ret;
  1303. ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
  1304. generic_ref->action);
  1305. BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
  1306. generic_ref->ref_root == BTRFS_TREE_LOG_OBJECTID);
  1307. if (generic_ref->type == BTRFS_REF_METADATA)
  1308. ret = btrfs_add_delayed_tree_ref(trans, generic_ref, NULL);
  1309. else
  1310. ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0);
  1311. btrfs_ref_tree_mod(fs_info, generic_ref);
  1312. return ret;
  1313. }
  1314. /*
  1315. * Insert backreference for a given extent.
  1316. *
  1317. * The counterpart is in __btrfs_free_extent(), with examples and more details
  1318. * how it works.
  1319. *
  1320. * @trans: Handle of transaction
  1321. *
  1322. * @node: The delayed ref node used to get the bytenr/length for
  1323. * extent whose references are incremented.
  1324. *
  1325. * @extent_op Pointer to a structure, holding information necessary when
  1326. * updating a tree block's flags
  1327. *
  1328. */
  1329. static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
  1330. struct btrfs_delayed_ref_node *node,
  1331. struct btrfs_delayed_extent_op *extent_op)
  1332. {
  1333. struct btrfs_path *path;
  1334. struct extent_buffer *leaf;
  1335. struct btrfs_extent_item *item;
  1336. struct btrfs_key key;
  1337. u64 bytenr = node->bytenr;
  1338. u64 num_bytes = node->num_bytes;
  1339. u64 owner = btrfs_delayed_ref_owner(node);
  1340. u64 offset = btrfs_delayed_ref_offset(node);
  1341. u64 refs;
  1342. int refs_to_add = node->ref_mod;
  1343. int ret;
  1344. path = btrfs_alloc_path();
  1345. if (!path)
  1346. return -ENOMEM;
  1347. /* this will setup the path even if it fails to insert the back ref */
  1348. ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
  1349. node->parent, node->ref_root, owner,
  1350. offset, refs_to_add, extent_op);
  1351. if ((ret < 0 && ret != -EAGAIN) || !ret)
  1352. goto out;
  1353. /*
  1354. * Ok we had -EAGAIN which means we didn't have space to insert and
  1355. * inline extent ref, so just update the reference count and add a
  1356. * normal backref.
  1357. */
  1358. leaf = path->nodes[0];
  1359. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1360. item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1361. refs = btrfs_extent_refs(leaf, item);
  1362. btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
  1363. if (extent_op)
  1364. __run_delayed_extent_op(extent_op, leaf, item);
  1365. btrfs_mark_buffer_dirty(trans, leaf);
  1366. btrfs_release_path(path);
  1367. /* now insert the actual backref */
  1368. if (owner < BTRFS_FIRST_FREE_OBJECTID)
  1369. ret = insert_tree_block_ref(trans, path, node, bytenr);
  1370. else
  1371. ret = insert_extent_data_ref(trans, path, node, bytenr);
  1372. if (ret)
  1373. btrfs_abort_transaction(trans, ret);
  1374. out:
  1375. btrfs_free_path(path);
  1376. return ret;
  1377. }
  1378. static void free_head_ref_squota_rsv(struct btrfs_fs_info *fs_info,
  1379. struct btrfs_delayed_ref_head *href)
  1380. {
  1381. u64 root = href->owning_root;
  1382. /*
  1383. * Don't check must_insert_reserved, as this is called from contexts
  1384. * where it has already been unset.
  1385. */
  1386. if (btrfs_qgroup_mode(fs_info) != BTRFS_QGROUP_MODE_SIMPLE ||
  1387. !href->is_data || !is_fstree(root))
  1388. return;
  1389. btrfs_qgroup_free_refroot(fs_info, root, href->reserved_bytes,
  1390. BTRFS_QGROUP_RSV_DATA);
  1391. }
  1392. static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
  1393. struct btrfs_delayed_ref_head *href,
  1394. struct btrfs_delayed_ref_node *node,
  1395. struct btrfs_delayed_extent_op *extent_op,
  1396. bool insert_reserved)
  1397. {
  1398. int ret = 0;
  1399. u64 parent = 0;
  1400. u64 flags = 0;
  1401. trace_run_delayed_data_ref(trans->fs_info, node);
  1402. if (node->type == BTRFS_SHARED_DATA_REF_KEY)
  1403. parent = node->parent;
  1404. if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
  1405. struct btrfs_key key;
  1406. struct btrfs_squota_delta delta = {
  1407. .root = href->owning_root,
  1408. .num_bytes = node->num_bytes,
  1409. .is_data = true,
  1410. .is_inc = true,
  1411. .generation = trans->transid,
  1412. };
  1413. u64 owner = btrfs_delayed_ref_owner(node);
  1414. u64 offset = btrfs_delayed_ref_offset(node);
  1415. if (extent_op)
  1416. flags |= extent_op->flags_to_set;
  1417. key.objectid = node->bytenr;
  1418. key.type = BTRFS_EXTENT_ITEM_KEY;
  1419. key.offset = node->num_bytes;
  1420. ret = alloc_reserved_file_extent(trans, parent, node->ref_root,
  1421. flags, owner, offset, &key,
  1422. node->ref_mod,
  1423. href->owning_root);
  1424. free_head_ref_squota_rsv(trans->fs_info, href);
  1425. if (!ret)
  1426. ret = btrfs_record_squota_delta(trans->fs_info, &delta);
  1427. } else if (node->action == BTRFS_ADD_DELAYED_REF) {
  1428. ret = __btrfs_inc_extent_ref(trans, node, extent_op);
  1429. } else if (node->action == BTRFS_DROP_DELAYED_REF) {
  1430. ret = __btrfs_free_extent(trans, href, node, extent_op);
  1431. } else {
  1432. BUG();
  1433. }
  1434. return ret;
  1435. }
  1436. static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
  1437. struct extent_buffer *leaf,
  1438. struct btrfs_extent_item *ei)
  1439. {
  1440. u64 flags = btrfs_extent_flags(leaf, ei);
  1441. if (extent_op->update_flags) {
  1442. flags |= extent_op->flags_to_set;
  1443. btrfs_set_extent_flags(leaf, ei, flags);
  1444. }
  1445. if (extent_op->update_key) {
  1446. struct btrfs_tree_block_info *bi;
  1447. BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
  1448. bi = (struct btrfs_tree_block_info *)(ei + 1);
  1449. btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
  1450. }
  1451. }
  1452. static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
  1453. struct btrfs_delayed_ref_head *head,
  1454. struct btrfs_delayed_extent_op *extent_op)
  1455. {
  1456. struct btrfs_fs_info *fs_info = trans->fs_info;
  1457. struct btrfs_root *root;
  1458. struct btrfs_key key;
  1459. struct btrfs_path *path;
  1460. struct btrfs_extent_item *ei;
  1461. struct extent_buffer *leaf;
  1462. u32 item_size;
  1463. int ret;
  1464. int metadata = 1;
  1465. if (TRANS_ABORTED(trans))
  1466. return 0;
  1467. if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
  1468. metadata = 0;
  1469. path = btrfs_alloc_path();
  1470. if (!path)
  1471. return -ENOMEM;
  1472. key.objectid = head->bytenr;
  1473. if (metadata) {
  1474. key.type = BTRFS_METADATA_ITEM_KEY;
  1475. key.offset = head->level;
  1476. } else {
  1477. key.type = BTRFS_EXTENT_ITEM_KEY;
  1478. key.offset = head->num_bytes;
  1479. }
  1480. root = btrfs_extent_root(fs_info, key.objectid);
  1481. again:
  1482. ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
  1483. if (ret < 0) {
  1484. goto out;
  1485. } else if (ret > 0) {
  1486. if (metadata) {
  1487. if (path->slots[0] > 0) {
  1488. path->slots[0]--;
  1489. btrfs_item_key_to_cpu(path->nodes[0], &key,
  1490. path->slots[0]);
  1491. if (key.objectid == head->bytenr &&
  1492. key.type == BTRFS_EXTENT_ITEM_KEY &&
  1493. key.offset == head->num_bytes)
  1494. ret = 0;
  1495. }
  1496. if (ret > 0) {
  1497. btrfs_release_path(path);
  1498. metadata = 0;
  1499. key.objectid = head->bytenr;
  1500. key.offset = head->num_bytes;
  1501. key.type = BTRFS_EXTENT_ITEM_KEY;
  1502. goto again;
  1503. }
  1504. } else {
  1505. ret = -EUCLEAN;
  1506. btrfs_err(fs_info,
  1507. "missing extent item for extent %llu num_bytes %llu level %d",
  1508. head->bytenr, head->num_bytes, head->level);
  1509. goto out;
  1510. }
  1511. }
  1512. leaf = path->nodes[0];
  1513. item_size = btrfs_item_size(leaf, path->slots[0]);
  1514. if (unlikely(item_size < sizeof(*ei))) {
  1515. ret = -EUCLEAN;
  1516. btrfs_err(fs_info,
  1517. "unexpected extent item size, has %u expect >= %zu",
  1518. item_size, sizeof(*ei));
  1519. btrfs_abort_transaction(trans, ret);
  1520. goto out;
  1521. }
  1522. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1523. __run_delayed_extent_op(extent_op, leaf, ei);
  1524. btrfs_mark_buffer_dirty(trans, leaf);
  1525. out:
  1526. btrfs_free_path(path);
  1527. return ret;
  1528. }
  1529. static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
  1530. struct btrfs_delayed_ref_head *href,
  1531. struct btrfs_delayed_ref_node *node,
  1532. struct btrfs_delayed_extent_op *extent_op,
  1533. bool insert_reserved)
  1534. {
  1535. int ret = 0;
  1536. struct btrfs_fs_info *fs_info = trans->fs_info;
  1537. u64 parent = 0;
  1538. u64 ref_root = 0;
  1539. trace_run_delayed_tree_ref(trans->fs_info, node);
  1540. if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
  1541. parent = node->parent;
  1542. ref_root = node->ref_root;
  1543. if (unlikely(node->ref_mod != 1)) {
  1544. btrfs_err(trans->fs_info,
  1545. "btree block %llu has %d references rather than 1: action %d ref_root %llu parent %llu",
  1546. node->bytenr, node->ref_mod, node->action, ref_root,
  1547. parent);
  1548. return -EUCLEAN;
  1549. }
  1550. if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
  1551. struct btrfs_squota_delta delta = {
  1552. .root = href->owning_root,
  1553. .num_bytes = fs_info->nodesize,
  1554. .is_data = false,
  1555. .is_inc = true,
  1556. .generation = trans->transid,
  1557. };
  1558. ret = alloc_reserved_tree_block(trans, node, extent_op);
  1559. if (!ret)
  1560. btrfs_record_squota_delta(fs_info, &delta);
  1561. } else if (node->action == BTRFS_ADD_DELAYED_REF) {
  1562. ret = __btrfs_inc_extent_ref(trans, node, extent_op);
  1563. } else if (node->action == BTRFS_DROP_DELAYED_REF) {
  1564. ret = __btrfs_free_extent(trans, href, node, extent_op);
  1565. } else {
  1566. BUG();
  1567. }
  1568. return ret;
  1569. }
  1570. /* helper function to actually process a single delayed ref entry */
  1571. static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
  1572. struct btrfs_delayed_ref_head *href,
  1573. struct btrfs_delayed_ref_node *node,
  1574. struct btrfs_delayed_extent_op *extent_op,
  1575. bool insert_reserved)
  1576. {
  1577. int ret = 0;
  1578. if (TRANS_ABORTED(trans)) {
  1579. if (insert_reserved) {
  1580. btrfs_pin_extent(trans, node->bytenr, node->num_bytes, 1);
  1581. free_head_ref_squota_rsv(trans->fs_info, href);
  1582. }
  1583. return 0;
  1584. }
  1585. if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
  1586. node->type == BTRFS_SHARED_BLOCK_REF_KEY)
  1587. ret = run_delayed_tree_ref(trans, href, node, extent_op,
  1588. insert_reserved);
  1589. else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
  1590. node->type == BTRFS_SHARED_DATA_REF_KEY)
  1591. ret = run_delayed_data_ref(trans, href, node, extent_op,
  1592. insert_reserved);
  1593. else if (node->type == BTRFS_EXTENT_OWNER_REF_KEY)
  1594. ret = 0;
  1595. else
  1596. BUG();
  1597. if (ret && insert_reserved)
  1598. btrfs_pin_extent(trans, node->bytenr, node->num_bytes, 1);
  1599. if (ret < 0)
  1600. btrfs_err(trans->fs_info,
  1601. "failed to run delayed ref for logical %llu num_bytes %llu type %u action %u ref_mod %d: %d",
  1602. node->bytenr, node->num_bytes, node->type,
  1603. node->action, node->ref_mod, ret);
  1604. return ret;
  1605. }
  1606. static inline struct btrfs_delayed_ref_node *
  1607. select_delayed_ref(struct btrfs_delayed_ref_head *head)
  1608. {
  1609. struct btrfs_delayed_ref_node *ref;
  1610. if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
  1611. return NULL;
  1612. /*
  1613. * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
  1614. * This is to prevent a ref count from going down to zero, which deletes
  1615. * the extent item from the extent tree, when there still are references
  1616. * to add, which would fail because they would not find the extent item.
  1617. */
  1618. if (!list_empty(&head->ref_add_list))
  1619. return list_first_entry(&head->ref_add_list,
  1620. struct btrfs_delayed_ref_node, add_list);
  1621. ref = rb_entry(rb_first_cached(&head->ref_tree),
  1622. struct btrfs_delayed_ref_node, ref_node);
  1623. ASSERT(list_empty(&ref->add_list));
  1624. return ref;
  1625. }
  1626. static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
  1627. struct btrfs_delayed_ref_head *head)
  1628. {
  1629. spin_lock(&delayed_refs->lock);
  1630. head->processing = false;
  1631. delayed_refs->num_heads_ready++;
  1632. spin_unlock(&delayed_refs->lock);
  1633. btrfs_delayed_ref_unlock(head);
  1634. }
  1635. static struct btrfs_delayed_extent_op *cleanup_extent_op(
  1636. struct btrfs_delayed_ref_head *head)
  1637. {
  1638. struct btrfs_delayed_extent_op *extent_op = head->extent_op;
  1639. if (!extent_op)
  1640. return NULL;
  1641. if (head->must_insert_reserved) {
  1642. head->extent_op = NULL;
  1643. btrfs_free_delayed_extent_op(extent_op);
  1644. return NULL;
  1645. }
  1646. return extent_op;
  1647. }
  1648. static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
  1649. struct btrfs_delayed_ref_head *head)
  1650. {
  1651. struct btrfs_delayed_extent_op *extent_op;
  1652. int ret;
  1653. extent_op = cleanup_extent_op(head);
  1654. if (!extent_op)
  1655. return 0;
  1656. head->extent_op = NULL;
  1657. spin_unlock(&head->lock);
  1658. ret = run_delayed_extent_op(trans, head, extent_op);
  1659. btrfs_free_delayed_extent_op(extent_op);
  1660. return ret ? ret : 1;
  1661. }
  1662. u64 btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
  1663. struct btrfs_delayed_ref_root *delayed_refs,
  1664. struct btrfs_delayed_ref_head *head)
  1665. {
  1666. u64 ret = 0;
  1667. /*
  1668. * We had csum deletions accounted for in our delayed refs rsv, we need
  1669. * to drop the csum leaves for this update from our delayed_refs_rsv.
  1670. */
  1671. if (head->total_ref_mod < 0 && head->is_data) {
  1672. int nr_csums;
  1673. spin_lock(&delayed_refs->lock);
  1674. delayed_refs->pending_csums -= head->num_bytes;
  1675. spin_unlock(&delayed_refs->lock);
  1676. nr_csums = btrfs_csum_bytes_to_leaves(fs_info, head->num_bytes);
  1677. btrfs_delayed_refs_rsv_release(fs_info, 0, nr_csums);
  1678. ret = btrfs_calc_delayed_ref_csum_bytes(fs_info, nr_csums);
  1679. }
  1680. /* must_insert_reserved can be set only if we didn't run the head ref. */
  1681. if (head->must_insert_reserved)
  1682. free_head_ref_squota_rsv(fs_info, head);
  1683. return ret;
  1684. }
  1685. static int cleanup_ref_head(struct btrfs_trans_handle *trans,
  1686. struct btrfs_delayed_ref_head *head,
  1687. u64 *bytes_released)
  1688. {
  1689. struct btrfs_fs_info *fs_info = trans->fs_info;
  1690. struct btrfs_delayed_ref_root *delayed_refs;
  1691. int ret;
  1692. delayed_refs = &trans->transaction->delayed_refs;
  1693. ret = run_and_cleanup_extent_op(trans, head);
  1694. if (ret < 0) {
  1695. unselect_delayed_ref_head(delayed_refs, head);
  1696. btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
  1697. return ret;
  1698. } else if (ret) {
  1699. return ret;
  1700. }
  1701. /*
  1702. * Need to drop our head ref lock and re-acquire the delayed ref lock
  1703. * and then re-check to make sure nobody got added.
  1704. */
  1705. spin_unlock(&head->lock);
  1706. spin_lock(&delayed_refs->lock);
  1707. spin_lock(&head->lock);
  1708. if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
  1709. spin_unlock(&head->lock);
  1710. spin_unlock(&delayed_refs->lock);
  1711. return 1;
  1712. }
  1713. btrfs_delete_ref_head(delayed_refs, head);
  1714. spin_unlock(&head->lock);
  1715. spin_unlock(&delayed_refs->lock);
  1716. if (head->must_insert_reserved) {
  1717. btrfs_pin_extent(trans, head->bytenr, head->num_bytes, 1);
  1718. if (head->is_data) {
  1719. struct btrfs_root *csum_root;
  1720. csum_root = btrfs_csum_root(fs_info, head->bytenr);
  1721. ret = btrfs_del_csums(trans, csum_root, head->bytenr,
  1722. head->num_bytes);
  1723. }
  1724. }
  1725. *bytes_released += btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
  1726. trace_run_delayed_ref_head(fs_info, head, 0);
  1727. btrfs_delayed_ref_unlock(head);
  1728. btrfs_put_delayed_ref_head(head);
  1729. return ret;
  1730. }
  1731. static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
  1732. struct btrfs_trans_handle *trans)
  1733. {
  1734. struct btrfs_delayed_ref_root *delayed_refs =
  1735. &trans->transaction->delayed_refs;
  1736. struct btrfs_delayed_ref_head *head = NULL;
  1737. int ret;
  1738. spin_lock(&delayed_refs->lock);
  1739. head = btrfs_select_ref_head(delayed_refs);
  1740. if (!head) {
  1741. spin_unlock(&delayed_refs->lock);
  1742. return head;
  1743. }
  1744. /*
  1745. * Grab the lock that says we are going to process all the refs for
  1746. * this head
  1747. */
  1748. ret = btrfs_delayed_ref_lock(delayed_refs, head);
  1749. spin_unlock(&delayed_refs->lock);
  1750. /*
  1751. * We may have dropped the spin lock to get the head mutex lock, and
  1752. * that might have given someone else time to free the head. If that's
  1753. * true, it has been removed from our list and we can move on.
  1754. */
  1755. if (ret == -EAGAIN)
  1756. head = ERR_PTR(-EAGAIN);
  1757. return head;
  1758. }
  1759. static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
  1760. struct btrfs_delayed_ref_head *locked_ref,
  1761. u64 *bytes_released)
  1762. {
  1763. struct btrfs_fs_info *fs_info = trans->fs_info;
  1764. struct btrfs_delayed_ref_root *delayed_refs;
  1765. struct btrfs_delayed_extent_op *extent_op;
  1766. struct btrfs_delayed_ref_node *ref;
  1767. bool must_insert_reserved;
  1768. int ret;
  1769. delayed_refs = &trans->transaction->delayed_refs;
  1770. lockdep_assert_held(&locked_ref->mutex);
  1771. lockdep_assert_held(&locked_ref->lock);
  1772. while ((ref = select_delayed_ref(locked_ref))) {
  1773. if (ref->seq &&
  1774. btrfs_check_delayed_seq(fs_info, ref->seq)) {
  1775. spin_unlock(&locked_ref->lock);
  1776. unselect_delayed_ref_head(delayed_refs, locked_ref);
  1777. return -EAGAIN;
  1778. }
  1779. rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
  1780. RB_CLEAR_NODE(&ref->ref_node);
  1781. if (!list_empty(&ref->add_list))
  1782. list_del(&ref->add_list);
  1783. /*
  1784. * When we play the delayed ref, also correct the ref_mod on
  1785. * head
  1786. */
  1787. switch (ref->action) {
  1788. case BTRFS_ADD_DELAYED_REF:
  1789. case BTRFS_ADD_DELAYED_EXTENT:
  1790. locked_ref->ref_mod -= ref->ref_mod;
  1791. break;
  1792. case BTRFS_DROP_DELAYED_REF:
  1793. locked_ref->ref_mod += ref->ref_mod;
  1794. break;
  1795. default:
  1796. WARN_ON(1);
  1797. }
  1798. atomic_dec(&delayed_refs->num_entries);
  1799. /*
  1800. * Record the must_insert_reserved flag before we drop the
  1801. * spin lock.
  1802. */
  1803. must_insert_reserved = locked_ref->must_insert_reserved;
  1804. /*
  1805. * Unsetting this on the head ref relinquishes ownership of
  1806. * the rsv_bytes, so it is critical that every possible code
  1807. * path from here forward frees all reserves including qgroup
  1808. * reserve.
  1809. */
  1810. locked_ref->must_insert_reserved = false;
  1811. extent_op = locked_ref->extent_op;
  1812. locked_ref->extent_op = NULL;
  1813. spin_unlock(&locked_ref->lock);
  1814. ret = run_one_delayed_ref(trans, locked_ref, ref, extent_op,
  1815. must_insert_reserved);
  1816. btrfs_delayed_refs_rsv_release(fs_info, 1, 0);
  1817. *bytes_released += btrfs_calc_delayed_ref_bytes(fs_info, 1);
  1818. btrfs_free_delayed_extent_op(extent_op);
  1819. if (ret) {
  1820. unselect_delayed_ref_head(delayed_refs, locked_ref);
  1821. btrfs_put_delayed_ref(ref);
  1822. return ret;
  1823. }
  1824. btrfs_put_delayed_ref(ref);
  1825. cond_resched();
  1826. spin_lock(&locked_ref->lock);
  1827. btrfs_merge_delayed_refs(fs_info, delayed_refs, locked_ref);
  1828. }
  1829. return 0;
  1830. }
  1831. /*
  1832. * Returns 0 on success or if called with an already aborted transaction.
  1833. * Returns -ENOMEM or -EIO on failure and will abort the transaction.
  1834. */
  1835. static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
  1836. u64 min_bytes)
  1837. {
  1838. struct btrfs_fs_info *fs_info = trans->fs_info;
  1839. struct btrfs_delayed_ref_root *delayed_refs;
  1840. struct btrfs_delayed_ref_head *locked_ref = NULL;
  1841. int ret;
  1842. unsigned long count = 0;
  1843. unsigned long max_count = 0;
  1844. u64 bytes_processed = 0;
  1845. delayed_refs = &trans->transaction->delayed_refs;
  1846. if (min_bytes == 0) {
  1847. max_count = delayed_refs->num_heads_ready;
  1848. min_bytes = U64_MAX;
  1849. }
  1850. do {
  1851. if (!locked_ref) {
  1852. locked_ref = btrfs_obtain_ref_head(trans);
  1853. if (IS_ERR_OR_NULL(locked_ref)) {
  1854. if (PTR_ERR(locked_ref) == -EAGAIN) {
  1855. continue;
  1856. } else {
  1857. break;
  1858. }
  1859. }
  1860. count++;
  1861. }
  1862. /*
  1863. * We need to try and merge add/drops of the same ref since we
  1864. * can run into issues with relocate dropping the implicit ref
  1865. * and then it being added back again before the drop can
  1866. * finish. If we merged anything we need to re-loop so we can
  1867. * get a good ref.
  1868. * Or we can get node references of the same type that weren't
  1869. * merged when created due to bumps in the tree mod seq, and
  1870. * we need to merge them to prevent adding an inline extent
  1871. * backref before dropping it (triggering a BUG_ON at
  1872. * insert_inline_extent_backref()).
  1873. */
  1874. spin_lock(&locked_ref->lock);
  1875. btrfs_merge_delayed_refs(fs_info, delayed_refs, locked_ref);
  1876. ret = btrfs_run_delayed_refs_for_head(trans, locked_ref, &bytes_processed);
  1877. if (ret < 0 && ret != -EAGAIN) {
  1878. /*
  1879. * Error, btrfs_run_delayed_refs_for_head already
  1880. * unlocked everything so just bail out
  1881. */
  1882. return ret;
  1883. } else if (!ret) {
  1884. /*
  1885. * Success, perform the usual cleanup of a processed
  1886. * head
  1887. */
  1888. ret = cleanup_ref_head(trans, locked_ref, &bytes_processed);
  1889. if (ret > 0 ) {
  1890. /* We dropped our lock, we need to loop. */
  1891. ret = 0;
  1892. continue;
  1893. } else if (ret) {
  1894. return ret;
  1895. }
  1896. }
  1897. /*
  1898. * Either success case or btrfs_run_delayed_refs_for_head
  1899. * returned -EAGAIN, meaning we need to select another head
  1900. */
  1901. locked_ref = NULL;
  1902. cond_resched();
  1903. } while ((min_bytes != U64_MAX && bytes_processed < min_bytes) ||
  1904. (max_count > 0 && count < max_count) ||
  1905. locked_ref);
  1906. return 0;
  1907. }
  1908. #ifdef SCRAMBLE_DELAYED_REFS
  1909. /*
  1910. * Normally delayed refs get processed in ascending bytenr order. This
  1911. * correlates in most cases to the order added. To expose dependencies on this
  1912. * order, we start to process the tree in the middle instead of the beginning
  1913. */
  1914. static u64 find_middle(struct rb_root *root)
  1915. {
  1916. struct rb_node *n = root->rb_node;
  1917. struct btrfs_delayed_ref_node *entry;
  1918. int alt = 1;
  1919. u64 middle;
  1920. u64 first = 0, last = 0;
  1921. n = rb_first(root);
  1922. if (n) {
  1923. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  1924. first = entry->bytenr;
  1925. }
  1926. n = rb_last(root);
  1927. if (n) {
  1928. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  1929. last = entry->bytenr;
  1930. }
  1931. n = root->rb_node;
  1932. while (n) {
  1933. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  1934. WARN_ON(!entry->in_tree);
  1935. middle = entry->bytenr;
  1936. if (alt)
  1937. n = n->rb_left;
  1938. else
  1939. n = n->rb_right;
  1940. alt = 1 - alt;
  1941. }
  1942. return middle;
  1943. }
  1944. #endif
  1945. /*
  1946. * Start processing the delayed reference count updates and extent insertions
  1947. * we have queued up so far.
  1948. *
  1949. * @trans: Transaction handle.
  1950. * @min_bytes: How many bytes of delayed references to process. After this
  1951. * many bytes we stop processing delayed references if there are
  1952. * any more. If 0 it means to run all existing delayed references,
  1953. * but not new ones added after running all existing ones.
  1954. * Use (u64)-1 (U64_MAX) to run all existing delayed references
  1955. * plus any new ones that are added.
  1956. *
  1957. * Returns 0 on success or if called with an aborted transaction
  1958. * Returns <0 on error and aborts the transaction
  1959. */
  1960. int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans, u64 min_bytes)
  1961. {
  1962. struct btrfs_fs_info *fs_info = trans->fs_info;
  1963. struct btrfs_delayed_ref_root *delayed_refs;
  1964. int ret;
  1965. /* We'll clean this up in btrfs_cleanup_transaction */
  1966. if (TRANS_ABORTED(trans))
  1967. return 0;
  1968. if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
  1969. return 0;
  1970. delayed_refs = &trans->transaction->delayed_refs;
  1971. again:
  1972. #ifdef SCRAMBLE_DELAYED_REFS
  1973. delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
  1974. #endif
  1975. ret = __btrfs_run_delayed_refs(trans, min_bytes);
  1976. if (ret < 0) {
  1977. btrfs_abort_transaction(trans, ret);
  1978. return ret;
  1979. }
  1980. if (min_bytes == U64_MAX) {
  1981. btrfs_create_pending_block_groups(trans);
  1982. spin_lock(&delayed_refs->lock);
  1983. if (RB_EMPTY_ROOT(&delayed_refs->href_root.rb_root)) {
  1984. spin_unlock(&delayed_refs->lock);
  1985. return 0;
  1986. }
  1987. spin_unlock(&delayed_refs->lock);
  1988. cond_resched();
  1989. goto again;
  1990. }
  1991. return 0;
  1992. }
  1993. int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
  1994. struct extent_buffer *eb, u64 flags)
  1995. {
  1996. struct btrfs_delayed_extent_op *extent_op;
  1997. int ret;
  1998. extent_op = btrfs_alloc_delayed_extent_op();
  1999. if (!extent_op)
  2000. return -ENOMEM;
  2001. extent_op->flags_to_set = flags;
  2002. extent_op->update_flags = true;
  2003. extent_op->update_key = false;
  2004. ret = btrfs_add_delayed_extent_op(trans, eb->start, eb->len,
  2005. btrfs_header_level(eb), extent_op);
  2006. if (ret)
  2007. btrfs_free_delayed_extent_op(extent_op);
  2008. return ret;
  2009. }
  2010. static noinline int check_delayed_ref(struct btrfs_root *root,
  2011. struct btrfs_path *path,
  2012. u64 objectid, u64 offset, u64 bytenr)
  2013. {
  2014. struct btrfs_delayed_ref_head *head;
  2015. struct btrfs_delayed_ref_node *ref;
  2016. struct btrfs_delayed_ref_root *delayed_refs;
  2017. struct btrfs_transaction *cur_trans;
  2018. struct rb_node *node;
  2019. int ret = 0;
  2020. spin_lock(&root->fs_info->trans_lock);
  2021. cur_trans = root->fs_info->running_transaction;
  2022. if (cur_trans)
  2023. refcount_inc(&cur_trans->use_count);
  2024. spin_unlock(&root->fs_info->trans_lock);
  2025. if (!cur_trans)
  2026. return 0;
  2027. delayed_refs = &cur_trans->delayed_refs;
  2028. spin_lock(&delayed_refs->lock);
  2029. head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
  2030. if (!head) {
  2031. spin_unlock(&delayed_refs->lock);
  2032. btrfs_put_transaction(cur_trans);
  2033. return 0;
  2034. }
  2035. if (!mutex_trylock(&head->mutex)) {
  2036. if (path->nowait) {
  2037. spin_unlock(&delayed_refs->lock);
  2038. btrfs_put_transaction(cur_trans);
  2039. return -EAGAIN;
  2040. }
  2041. refcount_inc(&head->refs);
  2042. spin_unlock(&delayed_refs->lock);
  2043. btrfs_release_path(path);
  2044. /*
  2045. * Mutex was contended, block until it's released and let
  2046. * caller try again
  2047. */
  2048. mutex_lock(&head->mutex);
  2049. mutex_unlock(&head->mutex);
  2050. btrfs_put_delayed_ref_head(head);
  2051. btrfs_put_transaction(cur_trans);
  2052. return -EAGAIN;
  2053. }
  2054. spin_unlock(&delayed_refs->lock);
  2055. spin_lock(&head->lock);
  2056. /*
  2057. * XXX: We should replace this with a proper search function in the
  2058. * future.
  2059. */
  2060. for (node = rb_first_cached(&head->ref_tree); node;
  2061. node = rb_next(node)) {
  2062. u64 ref_owner;
  2063. u64 ref_offset;
  2064. ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
  2065. /* If it's a shared ref we know a cross reference exists */
  2066. if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
  2067. ret = 1;
  2068. break;
  2069. }
  2070. ref_owner = btrfs_delayed_ref_owner(ref);
  2071. ref_offset = btrfs_delayed_ref_offset(ref);
  2072. /*
  2073. * If our ref doesn't match the one we're currently looking at
  2074. * then we have a cross reference.
  2075. */
  2076. if (ref->ref_root != btrfs_root_id(root) ||
  2077. ref_owner != objectid || ref_offset != offset) {
  2078. ret = 1;
  2079. break;
  2080. }
  2081. }
  2082. spin_unlock(&head->lock);
  2083. mutex_unlock(&head->mutex);
  2084. btrfs_put_transaction(cur_trans);
  2085. return ret;
  2086. }
  2087. static noinline int check_committed_ref(struct btrfs_root *root,
  2088. struct btrfs_path *path,
  2089. u64 objectid, u64 offset, u64 bytenr,
  2090. bool strict)
  2091. {
  2092. struct btrfs_fs_info *fs_info = root->fs_info;
  2093. struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
  2094. struct extent_buffer *leaf;
  2095. struct btrfs_extent_data_ref *ref;
  2096. struct btrfs_extent_inline_ref *iref;
  2097. struct btrfs_extent_item *ei;
  2098. struct btrfs_key key;
  2099. u32 item_size;
  2100. u32 expected_size;
  2101. int type;
  2102. int ret;
  2103. key.objectid = bytenr;
  2104. key.offset = (u64)-1;
  2105. key.type = BTRFS_EXTENT_ITEM_KEY;
  2106. ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
  2107. if (ret < 0)
  2108. goto out;
  2109. if (ret == 0) {
  2110. /*
  2111. * Key with offset -1 found, there would have to exist an extent
  2112. * item with such offset, but this is out of the valid range.
  2113. */
  2114. ret = -EUCLEAN;
  2115. goto out;
  2116. }
  2117. ret = -ENOENT;
  2118. if (path->slots[0] == 0)
  2119. goto out;
  2120. path->slots[0]--;
  2121. leaf = path->nodes[0];
  2122. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  2123. if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
  2124. goto out;
  2125. ret = 1;
  2126. item_size = btrfs_item_size(leaf, path->slots[0]);
  2127. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  2128. expected_size = sizeof(*ei) + btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY);
  2129. /* No inline refs; we need to bail before checking for owner ref. */
  2130. if (item_size == sizeof(*ei))
  2131. goto out;
  2132. /* Check for an owner ref; skip over it to the real inline refs. */
  2133. iref = (struct btrfs_extent_inline_ref *)(ei + 1);
  2134. type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
  2135. if (btrfs_fs_incompat(fs_info, SIMPLE_QUOTA) && type == BTRFS_EXTENT_OWNER_REF_KEY) {
  2136. expected_size += btrfs_extent_inline_ref_size(BTRFS_EXTENT_OWNER_REF_KEY);
  2137. iref = (struct btrfs_extent_inline_ref *)(iref + 1);
  2138. }
  2139. /* If extent item has more than 1 inline ref then it's shared */
  2140. if (item_size != expected_size)
  2141. goto out;
  2142. /*
  2143. * If extent created before last snapshot => it's shared unless the
  2144. * snapshot has been deleted. Use the heuristic if strict is false.
  2145. */
  2146. if (!strict &&
  2147. (btrfs_extent_generation(leaf, ei) <=
  2148. btrfs_root_last_snapshot(&root->root_item)))
  2149. goto out;
  2150. /* If this extent has SHARED_DATA_REF then it's shared */
  2151. type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
  2152. if (type != BTRFS_EXTENT_DATA_REF_KEY)
  2153. goto out;
  2154. ref = (struct btrfs_extent_data_ref *)(&iref->offset);
  2155. if (btrfs_extent_refs(leaf, ei) !=
  2156. btrfs_extent_data_ref_count(leaf, ref) ||
  2157. btrfs_extent_data_ref_root(leaf, ref) != btrfs_root_id(root) ||
  2158. btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
  2159. btrfs_extent_data_ref_offset(leaf, ref) != offset)
  2160. goto out;
  2161. ret = 0;
  2162. out:
  2163. return ret;
  2164. }
  2165. int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
  2166. u64 bytenr, bool strict, struct btrfs_path *path)
  2167. {
  2168. int ret;
  2169. do {
  2170. ret = check_committed_ref(root, path, objectid,
  2171. offset, bytenr, strict);
  2172. if (ret && ret != -ENOENT)
  2173. goto out;
  2174. ret = check_delayed_ref(root, path, objectid, offset, bytenr);
  2175. } while (ret == -EAGAIN && !path->nowait);
  2176. out:
  2177. btrfs_release_path(path);
  2178. if (btrfs_is_data_reloc_root(root))
  2179. WARN_ON(ret > 0);
  2180. return ret;
  2181. }
  2182. static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
  2183. struct btrfs_root *root,
  2184. struct extent_buffer *buf,
  2185. int full_backref, int inc)
  2186. {
  2187. struct btrfs_fs_info *fs_info = root->fs_info;
  2188. u64 parent;
  2189. u64 ref_root;
  2190. u32 nritems;
  2191. struct btrfs_key key;
  2192. struct btrfs_file_extent_item *fi;
  2193. bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
  2194. int i;
  2195. int action;
  2196. int level;
  2197. int ret = 0;
  2198. if (btrfs_is_testing(fs_info))
  2199. return 0;
  2200. ref_root = btrfs_header_owner(buf);
  2201. nritems = btrfs_header_nritems(buf);
  2202. level = btrfs_header_level(buf);
  2203. if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state) && level == 0)
  2204. return 0;
  2205. if (full_backref)
  2206. parent = buf->start;
  2207. else
  2208. parent = 0;
  2209. if (inc)
  2210. action = BTRFS_ADD_DELAYED_REF;
  2211. else
  2212. action = BTRFS_DROP_DELAYED_REF;
  2213. for (i = 0; i < nritems; i++) {
  2214. struct btrfs_ref ref = {
  2215. .action = action,
  2216. .parent = parent,
  2217. .ref_root = ref_root,
  2218. };
  2219. if (level == 0) {
  2220. btrfs_item_key_to_cpu(buf, &key, i);
  2221. if (key.type != BTRFS_EXTENT_DATA_KEY)
  2222. continue;
  2223. fi = btrfs_item_ptr(buf, i,
  2224. struct btrfs_file_extent_item);
  2225. if (btrfs_file_extent_type(buf, fi) ==
  2226. BTRFS_FILE_EXTENT_INLINE)
  2227. continue;
  2228. ref.bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
  2229. if (ref.bytenr == 0)
  2230. continue;
  2231. ref.num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
  2232. ref.owning_root = ref_root;
  2233. key.offset -= btrfs_file_extent_offset(buf, fi);
  2234. btrfs_init_data_ref(&ref, key.objectid, key.offset,
  2235. btrfs_root_id(root), for_reloc);
  2236. if (inc)
  2237. ret = btrfs_inc_extent_ref(trans, &ref);
  2238. else
  2239. ret = btrfs_free_extent(trans, &ref);
  2240. if (ret)
  2241. goto fail;
  2242. } else {
  2243. /* We don't know the owning_root, leave as 0. */
  2244. ref.bytenr = btrfs_node_blockptr(buf, i);
  2245. ref.num_bytes = fs_info->nodesize;
  2246. btrfs_init_tree_ref(&ref, level - 1,
  2247. btrfs_root_id(root), for_reloc);
  2248. if (inc)
  2249. ret = btrfs_inc_extent_ref(trans, &ref);
  2250. else
  2251. ret = btrfs_free_extent(trans, &ref);
  2252. if (ret)
  2253. goto fail;
  2254. }
  2255. }
  2256. return 0;
  2257. fail:
  2258. return ret;
  2259. }
  2260. int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  2261. struct extent_buffer *buf, int full_backref)
  2262. {
  2263. return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
  2264. }
  2265. int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  2266. struct extent_buffer *buf, int full_backref)
  2267. {
  2268. return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
  2269. }
  2270. static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
  2271. {
  2272. struct btrfs_fs_info *fs_info = root->fs_info;
  2273. u64 flags;
  2274. u64 ret;
  2275. if (data)
  2276. flags = BTRFS_BLOCK_GROUP_DATA;
  2277. else if (root == fs_info->chunk_root)
  2278. flags = BTRFS_BLOCK_GROUP_SYSTEM;
  2279. else
  2280. flags = BTRFS_BLOCK_GROUP_METADATA;
  2281. ret = btrfs_get_alloc_profile(fs_info, flags);
  2282. return ret;
  2283. }
  2284. static u64 first_logical_byte(struct btrfs_fs_info *fs_info)
  2285. {
  2286. struct rb_node *leftmost;
  2287. u64 bytenr = 0;
  2288. read_lock(&fs_info->block_group_cache_lock);
  2289. /* Get the block group with the lowest logical start address. */
  2290. leftmost = rb_first_cached(&fs_info->block_group_cache_tree);
  2291. if (leftmost) {
  2292. struct btrfs_block_group *bg;
  2293. bg = rb_entry(leftmost, struct btrfs_block_group, cache_node);
  2294. bytenr = bg->start;
  2295. }
  2296. read_unlock(&fs_info->block_group_cache_lock);
  2297. return bytenr;
  2298. }
  2299. static int pin_down_extent(struct btrfs_trans_handle *trans,
  2300. struct btrfs_block_group *cache,
  2301. u64 bytenr, u64 num_bytes, int reserved)
  2302. {
  2303. struct btrfs_fs_info *fs_info = cache->fs_info;
  2304. spin_lock(&cache->space_info->lock);
  2305. spin_lock(&cache->lock);
  2306. cache->pinned += num_bytes;
  2307. btrfs_space_info_update_bytes_pinned(fs_info, cache->space_info,
  2308. num_bytes);
  2309. if (reserved) {
  2310. cache->reserved -= num_bytes;
  2311. cache->space_info->bytes_reserved -= num_bytes;
  2312. }
  2313. spin_unlock(&cache->lock);
  2314. spin_unlock(&cache->space_info->lock);
  2315. set_extent_bit(&trans->transaction->pinned_extents, bytenr,
  2316. bytenr + num_bytes - 1, EXTENT_DIRTY, NULL);
  2317. return 0;
  2318. }
  2319. int btrfs_pin_extent(struct btrfs_trans_handle *trans,
  2320. u64 bytenr, u64 num_bytes, int reserved)
  2321. {
  2322. struct btrfs_block_group *cache;
  2323. cache = btrfs_lookup_block_group(trans->fs_info, bytenr);
  2324. BUG_ON(!cache); /* Logic error */
  2325. pin_down_extent(trans, cache, bytenr, num_bytes, reserved);
  2326. btrfs_put_block_group(cache);
  2327. return 0;
  2328. }
  2329. int btrfs_pin_extent_for_log_replay(struct btrfs_trans_handle *trans,
  2330. const struct extent_buffer *eb)
  2331. {
  2332. struct btrfs_block_group *cache;
  2333. int ret;
  2334. cache = btrfs_lookup_block_group(trans->fs_info, eb->start);
  2335. if (!cache)
  2336. return -EINVAL;
  2337. /*
  2338. * Fully cache the free space first so that our pin removes the free space
  2339. * from the cache.
  2340. */
  2341. ret = btrfs_cache_block_group(cache, true);
  2342. if (ret)
  2343. goto out;
  2344. pin_down_extent(trans, cache, eb->start, eb->len, 0);
  2345. /* remove us from the free space cache (if we're there at all) */
  2346. ret = btrfs_remove_free_space(cache, eb->start, eb->len);
  2347. out:
  2348. btrfs_put_block_group(cache);
  2349. return ret;
  2350. }
  2351. static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
  2352. u64 start, u64 num_bytes)
  2353. {
  2354. int ret;
  2355. struct btrfs_block_group *block_group;
  2356. block_group = btrfs_lookup_block_group(fs_info, start);
  2357. if (!block_group)
  2358. return -EINVAL;
  2359. ret = btrfs_cache_block_group(block_group, true);
  2360. if (ret)
  2361. goto out;
  2362. ret = btrfs_remove_free_space(block_group, start, num_bytes);
  2363. out:
  2364. btrfs_put_block_group(block_group);
  2365. return ret;
  2366. }
  2367. int btrfs_exclude_logged_extents(struct extent_buffer *eb)
  2368. {
  2369. struct btrfs_fs_info *fs_info = eb->fs_info;
  2370. struct btrfs_file_extent_item *item;
  2371. struct btrfs_key key;
  2372. int found_type;
  2373. int i;
  2374. int ret = 0;
  2375. if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
  2376. return 0;
  2377. for (i = 0; i < btrfs_header_nritems(eb); i++) {
  2378. btrfs_item_key_to_cpu(eb, &key, i);
  2379. if (key.type != BTRFS_EXTENT_DATA_KEY)
  2380. continue;
  2381. item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
  2382. found_type = btrfs_file_extent_type(eb, item);
  2383. if (found_type == BTRFS_FILE_EXTENT_INLINE)
  2384. continue;
  2385. if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
  2386. continue;
  2387. key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
  2388. key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
  2389. ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
  2390. if (ret)
  2391. break;
  2392. }
  2393. return ret;
  2394. }
  2395. static void
  2396. btrfs_inc_block_group_reservations(struct btrfs_block_group *bg)
  2397. {
  2398. atomic_inc(&bg->reservations);
  2399. }
  2400. /*
  2401. * Returns the free cluster for the given space info and sets empty_cluster to
  2402. * what it should be based on the mount options.
  2403. */
  2404. static struct btrfs_free_cluster *
  2405. fetch_cluster_info(struct btrfs_fs_info *fs_info,
  2406. struct btrfs_space_info *space_info, u64 *empty_cluster)
  2407. {
  2408. struct btrfs_free_cluster *ret = NULL;
  2409. *empty_cluster = 0;
  2410. if (btrfs_mixed_space_info(space_info))
  2411. return ret;
  2412. if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
  2413. ret = &fs_info->meta_alloc_cluster;
  2414. if (btrfs_test_opt(fs_info, SSD))
  2415. *empty_cluster = SZ_2M;
  2416. else
  2417. *empty_cluster = SZ_64K;
  2418. } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
  2419. btrfs_test_opt(fs_info, SSD_SPREAD)) {
  2420. *empty_cluster = SZ_2M;
  2421. ret = &fs_info->data_alloc_cluster;
  2422. }
  2423. return ret;
  2424. }
  2425. static int unpin_extent_range(struct btrfs_fs_info *fs_info,
  2426. u64 start, u64 end,
  2427. const bool return_free_space)
  2428. {
  2429. struct btrfs_block_group *cache = NULL;
  2430. struct btrfs_space_info *space_info;
  2431. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  2432. struct btrfs_free_cluster *cluster = NULL;
  2433. u64 len;
  2434. u64 total_unpinned = 0;
  2435. u64 empty_cluster = 0;
  2436. bool readonly;
  2437. int ret = 0;
  2438. while (start <= end) {
  2439. readonly = false;
  2440. if (!cache ||
  2441. start >= cache->start + cache->length) {
  2442. if (cache)
  2443. btrfs_put_block_group(cache);
  2444. total_unpinned = 0;
  2445. cache = btrfs_lookup_block_group(fs_info, start);
  2446. if (cache == NULL) {
  2447. /* Logic error, something removed the block group. */
  2448. ret = -EUCLEAN;
  2449. goto out;
  2450. }
  2451. cluster = fetch_cluster_info(fs_info,
  2452. cache->space_info,
  2453. &empty_cluster);
  2454. empty_cluster <<= 1;
  2455. }
  2456. len = cache->start + cache->length - start;
  2457. len = min(len, end + 1 - start);
  2458. if (return_free_space)
  2459. btrfs_add_free_space(cache, start, len);
  2460. start += len;
  2461. total_unpinned += len;
  2462. space_info = cache->space_info;
  2463. /*
  2464. * If this space cluster has been marked as fragmented and we've
  2465. * unpinned enough in this block group to potentially allow a
  2466. * cluster to be created inside of it go ahead and clear the
  2467. * fragmented check.
  2468. */
  2469. if (cluster && cluster->fragmented &&
  2470. total_unpinned > empty_cluster) {
  2471. spin_lock(&cluster->lock);
  2472. cluster->fragmented = 0;
  2473. spin_unlock(&cluster->lock);
  2474. }
  2475. spin_lock(&space_info->lock);
  2476. spin_lock(&cache->lock);
  2477. cache->pinned -= len;
  2478. btrfs_space_info_update_bytes_pinned(fs_info, space_info, -len);
  2479. space_info->max_extent_size = 0;
  2480. if (cache->ro) {
  2481. space_info->bytes_readonly += len;
  2482. readonly = true;
  2483. } else if (btrfs_is_zoned(fs_info)) {
  2484. /* Need reset before reusing in a zoned block group */
  2485. btrfs_space_info_update_bytes_zone_unusable(fs_info, space_info,
  2486. len);
  2487. readonly = true;
  2488. }
  2489. spin_unlock(&cache->lock);
  2490. if (!readonly && return_free_space &&
  2491. global_rsv->space_info == space_info) {
  2492. spin_lock(&global_rsv->lock);
  2493. if (!global_rsv->full) {
  2494. u64 to_add = min(len, global_rsv->size -
  2495. global_rsv->reserved);
  2496. global_rsv->reserved += to_add;
  2497. btrfs_space_info_update_bytes_may_use(fs_info,
  2498. space_info, to_add);
  2499. if (global_rsv->reserved >= global_rsv->size)
  2500. global_rsv->full = 1;
  2501. len -= to_add;
  2502. }
  2503. spin_unlock(&global_rsv->lock);
  2504. }
  2505. /* Add to any tickets we may have */
  2506. if (!readonly && return_free_space && len)
  2507. btrfs_try_granting_tickets(fs_info, space_info);
  2508. spin_unlock(&space_info->lock);
  2509. }
  2510. if (cache)
  2511. btrfs_put_block_group(cache);
  2512. out:
  2513. return ret;
  2514. }
  2515. int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
  2516. {
  2517. struct btrfs_fs_info *fs_info = trans->fs_info;
  2518. struct btrfs_block_group *block_group, *tmp;
  2519. struct list_head *deleted_bgs;
  2520. struct extent_io_tree *unpin;
  2521. u64 start;
  2522. u64 end;
  2523. int ret;
  2524. unpin = &trans->transaction->pinned_extents;
  2525. while (!TRANS_ABORTED(trans)) {
  2526. struct extent_state *cached_state = NULL;
  2527. mutex_lock(&fs_info->unused_bg_unpin_mutex);
  2528. if (!find_first_extent_bit(unpin, 0, &start, &end,
  2529. EXTENT_DIRTY, &cached_state)) {
  2530. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  2531. break;
  2532. }
  2533. if (btrfs_test_opt(fs_info, DISCARD_SYNC))
  2534. ret = btrfs_discard_extent(fs_info, start,
  2535. end + 1 - start, NULL);
  2536. clear_extent_dirty(unpin, start, end, &cached_state);
  2537. ret = unpin_extent_range(fs_info, start, end, true);
  2538. BUG_ON(ret);
  2539. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  2540. free_extent_state(cached_state);
  2541. cond_resched();
  2542. }
  2543. if (btrfs_test_opt(fs_info, DISCARD_ASYNC)) {
  2544. btrfs_discard_calc_delay(&fs_info->discard_ctl);
  2545. btrfs_discard_schedule_work(&fs_info->discard_ctl, true);
  2546. }
  2547. /*
  2548. * Transaction is finished. We don't need the lock anymore. We
  2549. * do need to clean up the block groups in case of a transaction
  2550. * abort.
  2551. */
  2552. deleted_bgs = &trans->transaction->deleted_bgs;
  2553. list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
  2554. u64 trimmed = 0;
  2555. ret = -EROFS;
  2556. if (!TRANS_ABORTED(trans))
  2557. ret = btrfs_discard_extent(fs_info,
  2558. block_group->start,
  2559. block_group->length,
  2560. &trimmed);
  2561. /*
  2562. * Not strictly necessary to lock, as the block_group should be
  2563. * read-only from btrfs_delete_unused_bgs().
  2564. */
  2565. ASSERT(block_group->ro);
  2566. spin_lock(&fs_info->unused_bgs_lock);
  2567. list_del_init(&block_group->bg_list);
  2568. spin_unlock(&fs_info->unused_bgs_lock);
  2569. btrfs_unfreeze_block_group(block_group);
  2570. btrfs_put_block_group(block_group);
  2571. if (ret) {
  2572. const char *errstr = btrfs_decode_error(ret);
  2573. btrfs_warn(fs_info,
  2574. "discard failed while removing blockgroup: errno=%d %s",
  2575. ret, errstr);
  2576. }
  2577. }
  2578. return 0;
  2579. }
  2580. /*
  2581. * Parse an extent item's inline extents looking for a simple quotas owner ref.
  2582. *
  2583. * @fs_info: the btrfs_fs_info for this mount
  2584. * @leaf: a leaf in the extent tree containing the extent item
  2585. * @slot: the slot in the leaf where the extent item is found
  2586. *
  2587. * Returns the objectid of the root that originally allocated the extent item
  2588. * if the inline owner ref is expected and present, otherwise 0.
  2589. *
  2590. * If an extent item has an owner ref item, it will be the first inline ref
  2591. * item. Therefore the logic is to check whether there are any inline ref
  2592. * items, then check the type of the first one.
  2593. */
  2594. u64 btrfs_get_extent_owner_root(struct btrfs_fs_info *fs_info,
  2595. struct extent_buffer *leaf, int slot)
  2596. {
  2597. struct btrfs_extent_item *ei;
  2598. struct btrfs_extent_inline_ref *iref;
  2599. struct btrfs_extent_owner_ref *oref;
  2600. unsigned long ptr;
  2601. unsigned long end;
  2602. int type;
  2603. if (!btrfs_fs_incompat(fs_info, SIMPLE_QUOTA))
  2604. return 0;
  2605. ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
  2606. ptr = (unsigned long)(ei + 1);
  2607. end = (unsigned long)ei + btrfs_item_size(leaf, slot);
  2608. /* No inline ref items of any kind, can't check type. */
  2609. if (ptr == end)
  2610. return 0;
  2611. iref = (struct btrfs_extent_inline_ref *)ptr;
  2612. type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
  2613. /* We found an owner ref, get the root out of it. */
  2614. if (type == BTRFS_EXTENT_OWNER_REF_KEY) {
  2615. oref = (struct btrfs_extent_owner_ref *)(&iref->offset);
  2616. return btrfs_extent_owner_ref_root_id(leaf, oref);
  2617. }
  2618. /* We have inline refs, but not an owner ref. */
  2619. return 0;
  2620. }
  2621. static int do_free_extent_accounting(struct btrfs_trans_handle *trans,
  2622. u64 bytenr, struct btrfs_squota_delta *delta)
  2623. {
  2624. int ret;
  2625. u64 num_bytes = delta->num_bytes;
  2626. if (delta->is_data) {
  2627. struct btrfs_root *csum_root;
  2628. csum_root = btrfs_csum_root(trans->fs_info, bytenr);
  2629. ret = btrfs_del_csums(trans, csum_root, bytenr, num_bytes);
  2630. if (ret) {
  2631. btrfs_abort_transaction(trans, ret);
  2632. return ret;
  2633. }
  2634. ret = btrfs_delete_raid_extent(trans, bytenr, num_bytes);
  2635. if (ret) {
  2636. btrfs_abort_transaction(trans, ret);
  2637. return ret;
  2638. }
  2639. }
  2640. ret = btrfs_record_squota_delta(trans->fs_info, delta);
  2641. if (ret) {
  2642. btrfs_abort_transaction(trans, ret);
  2643. return ret;
  2644. }
  2645. ret = add_to_free_space_tree(trans, bytenr, num_bytes);
  2646. if (ret) {
  2647. btrfs_abort_transaction(trans, ret);
  2648. return ret;
  2649. }
  2650. ret = btrfs_update_block_group(trans, bytenr, num_bytes, false);
  2651. if (ret)
  2652. btrfs_abort_transaction(trans, ret);
  2653. return ret;
  2654. }
  2655. #define abort_and_dump(trans, path, fmt, args...) \
  2656. ({ \
  2657. btrfs_abort_transaction(trans, -EUCLEAN); \
  2658. btrfs_print_leaf(path->nodes[0]); \
  2659. btrfs_crit(trans->fs_info, fmt, ##args); \
  2660. })
  2661. /*
  2662. * Drop one or more refs of @node.
  2663. *
  2664. * 1. Locate the extent refs.
  2665. * It's either inline in EXTENT/METADATA_ITEM or in keyed SHARED_* item.
  2666. * Locate it, then reduce the refs number or remove the ref line completely.
  2667. *
  2668. * 2. Update the refs count in EXTENT/METADATA_ITEM
  2669. *
  2670. * Inline backref case:
  2671. *
  2672. * in extent tree we have:
  2673. *
  2674. * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
  2675. * refs 2 gen 6 flags DATA
  2676. * extent data backref root FS_TREE objectid 258 offset 0 count 1
  2677. * extent data backref root FS_TREE objectid 257 offset 0 count 1
  2678. *
  2679. * This function gets called with:
  2680. *
  2681. * node->bytenr = 13631488
  2682. * node->num_bytes = 1048576
  2683. * root_objectid = FS_TREE
  2684. * owner_objectid = 257
  2685. * owner_offset = 0
  2686. * refs_to_drop = 1
  2687. *
  2688. * Then we should get some like:
  2689. *
  2690. * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 16201 itemsize 82
  2691. * refs 1 gen 6 flags DATA
  2692. * extent data backref root FS_TREE objectid 258 offset 0 count 1
  2693. *
  2694. * Keyed backref case:
  2695. *
  2696. * in extent tree we have:
  2697. *
  2698. * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
  2699. * refs 754 gen 6 flags DATA
  2700. * [...]
  2701. * item 2 key (13631488 EXTENT_DATA_REF <HASH>) itemoff 3915 itemsize 28
  2702. * extent data backref root FS_TREE objectid 866 offset 0 count 1
  2703. *
  2704. * This function get called with:
  2705. *
  2706. * node->bytenr = 13631488
  2707. * node->num_bytes = 1048576
  2708. * root_objectid = FS_TREE
  2709. * owner_objectid = 866
  2710. * owner_offset = 0
  2711. * refs_to_drop = 1
  2712. *
  2713. * Then we should get some like:
  2714. *
  2715. * item 0 key (13631488 EXTENT_ITEM 1048576) itemoff 3971 itemsize 24
  2716. * refs 753 gen 6 flags DATA
  2717. *
  2718. * And that (13631488 EXTENT_DATA_REF <HASH>) gets removed.
  2719. */
  2720. static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
  2721. struct btrfs_delayed_ref_head *href,
  2722. struct btrfs_delayed_ref_node *node,
  2723. struct btrfs_delayed_extent_op *extent_op)
  2724. {
  2725. struct btrfs_fs_info *info = trans->fs_info;
  2726. struct btrfs_key key;
  2727. struct btrfs_path *path;
  2728. struct btrfs_root *extent_root;
  2729. struct extent_buffer *leaf;
  2730. struct btrfs_extent_item *ei;
  2731. struct btrfs_extent_inline_ref *iref;
  2732. int ret;
  2733. int is_data;
  2734. int extent_slot = 0;
  2735. int found_extent = 0;
  2736. int num_to_del = 1;
  2737. int refs_to_drop = node->ref_mod;
  2738. u32 item_size;
  2739. u64 refs;
  2740. u64 bytenr = node->bytenr;
  2741. u64 num_bytes = node->num_bytes;
  2742. u64 owner_objectid = btrfs_delayed_ref_owner(node);
  2743. u64 owner_offset = btrfs_delayed_ref_offset(node);
  2744. bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
  2745. u64 delayed_ref_root = href->owning_root;
  2746. extent_root = btrfs_extent_root(info, bytenr);
  2747. ASSERT(extent_root);
  2748. path = btrfs_alloc_path();
  2749. if (!path)
  2750. return -ENOMEM;
  2751. is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
  2752. if (!is_data && refs_to_drop != 1) {
  2753. btrfs_crit(info,
  2754. "invalid refs_to_drop, dropping more than 1 refs for tree block %llu refs_to_drop %u",
  2755. node->bytenr, refs_to_drop);
  2756. ret = -EINVAL;
  2757. btrfs_abort_transaction(trans, ret);
  2758. goto out;
  2759. }
  2760. if (is_data)
  2761. skinny_metadata = false;
  2762. ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
  2763. node->parent, node->ref_root, owner_objectid,
  2764. owner_offset);
  2765. if (ret == 0) {
  2766. /*
  2767. * Either the inline backref or the SHARED_DATA_REF/
  2768. * SHARED_BLOCK_REF is found
  2769. *
  2770. * Here is a quick path to locate EXTENT/METADATA_ITEM.
  2771. * It's possible the EXTENT/METADATA_ITEM is near current slot.
  2772. */
  2773. extent_slot = path->slots[0];
  2774. while (extent_slot >= 0) {
  2775. btrfs_item_key_to_cpu(path->nodes[0], &key,
  2776. extent_slot);
  2777. if (key.objectid != bytenr)
  2778. break;
  2779. if (key.type == BTRFS_EXTENT_ITEM_KEY &&
  2780. key.offset == num_bytes) {
  2781. found_extent = 1;
  2782. break;
  2783. }
  2784. if (key.type == BTRFS_METADATA_ITEM_KEY &&
  2785. key.offset == owner_objectid) {
  2786. found_extent = 1;
  2787. break;
  2788. }
  2789. /* Quick path didn't find the EXTEMT/METADATA_ITEM */
  2790. if (path->slots[0] - extent_slot > 5)
  2791. break;
  2792. extent_slot--;
  2793. }
  2794. if (!found_extent) {
  2795. if (iref) {
  2796. abort_and_dump(trans, path,
  2797. "invalid iref slot %u, no EXTENT/METADATA_ITEM found but has inline extent ref",
  2798. path->slots[0]);
  2799. ret = -EUCLEAN;
  2800. goto out;
  2801. }
  2802. /* Must be SHARED_* item, remove the backref first */
  2803. ret = remove_extent_backref(trans, extent_root, path,
  2804. NULL, refs_to_drop, is_data);
  2805. if (ret) {
  2806. btrfs_abort_transaction(trans, ret);
  2807. goto out;
  2808. }
  2809. btrfs_release_path(path);
  2810. /* Slow path to locate EXTENT/METADATA_ITEM */
  2811. key.objectid = bytenr;
  2812. key.type = BTRFS_EXTENT_ITEM_KEY;
  2813. key.offset = num_bytes;
  2814. if (!is_data && skinny_metadata) {
  2815. key.type = BTRFS_METADATA_ITEM_KEY;
  2816. key.offset = owner_objectid;
  2817. }
  2818. ret = btrfs_search_slot(trans, extent_root,
  2819. &key, path, -1, 1);
  2820. if (ret > 0 && skinny_metadata && path->slots[0]) {
  2821. /*
  2822. * Couldn't find our skinny metadata item,
  2823. * see if we have ye olde extent item.
  2824. */
  2825. path->slots[0]--;
  2826. btrfs_item_key_to_cpu(path->nodes[0], &key,
  2827. path->slots[0]);
  2828. if (key.objectid == bytenr &&
  2829. key.type == BTRFS_EXTENT_ITEM_KEY &&
  2830. key.offset == num_bytes)
  2831. ret = 0;
  2832. }
  2833. if (ret > 0 && skinny_metadata) {
  2834. skinny_metadata = false;
  2835. key.objectid = bytenr;
  2836. key.type = BTRFS_EXTENT_ITEM_KEY;
  2837. key.offset = num_bytes;
  2838. btrfs_release_path(path);
  2839. ret = btrfs_search_slot(trans, extent_root,
  2840. &key, path, -1, 1);
  2841. }
  2842. if (ret) {
  2843. if (ret > 0)
  2844. btrfs_print_leaf(path->nodes[0]);
  2845. btrfs_err(info,
  2846. "umm, got %d back from search, was looking for %llu, slot %d",
  2847. ret, bytenr, path->slots[0]);
  2848. }
  2849. if (ret < 0) {
  2850. btrfs_abort_transaction(trans, ret);
  2851. goto out;
  2852. }
  2853. extent_slot = path->slots[0];
  2854. }
  2855. } else if (WARN_ON(ret == -ENOENT)) {
  2856. abort_and_dump(trans, path,
  2857. "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu slot %d",
  2858. bytenr, node->parent, node->ref_root, owner_objectid,
  2859. owner_offset, path->slots[0]);
  2860. goto out;
  2861. } else {
  2862. btrfs_abort_transaction(trans, ret);
  2863. goto out;
  2864. }
  2865. leaf = path->nodes[0];
  2866. item_size = btrfs_item_size(leaf, extent_slot);
  2867. if (unlikely(item_size < sizeof(*ei))) {
  2868. ret = -EUCLEAN;
  2869. btrfs_err(trans->fs_info,
  2870. "unexpected extent item size, has %u expect >= %zu",
  2871. item_size, sizeof(*ei));
  2872. btrfs_abort_transaction(trans, ret);
  2873. goto out;
  2874. }
  2875. ei = btrfs_item_ptr(leaf, extent_slot,
  2876. struct btrfs_extent_item);
  2877. if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
  2878. key.type == BTRFS_EXTENT_ITEM_KEY) {
  2879. struct btrfs_tree_block_info *bi;
  2880. if (item_size < sizeof(*ei) + sizeof(*bi)) {
  2881. abort_and_dump(trans, path,
  2882. "invalid extent item size for key (%llu, %u, %llu) slot %u owner %llu, has %u expect >= %zu",
  2883. key.objectid, key.type, key.offset,
  2884. path->slots[0], owner_objectid, item_size,
  2885. sizeof(*ei) + sizeof(*bi));
  2886. ret = -EUCLEAN;
  2887. goto out;
  2888. }
  2889. bi = (struct btrfs_tree_block_info *)(ei + 1);
  2890. WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
  2891. }
  2892. refs = btrfs_extent_refs(leaf, ei);
  2893. if (refs < refs_to_drop) {
  2894. abort_and_dump(trans, path,
  2895. "trying to drop %d refs but we only have %llu for bytenr %llu slot %u",
  2896. refs_to_drop, refs, bytenr, path->slots[0]);
  2897. ret = -EUCLEAN;
  2898. goto out;
  2899. }
  2900. refs -= refs_to_drop;
  2901. if (refs > 0) {
  2902. if (extent_op)
  2903. __run_delayed_extent_op(extent_op, leaf, ei);
  2904. /*
  2905. * In the case of inline back ref, reference count will
  2906. * be updated by remove_extent_backref
  2907. */
  2908. if (iref) {
  2909. if (!found_extent) {
  2910. abort_and_dump(trans, path,
  2911. "invalid iref, got inlined extent ref but no EXTENT/METADATA_ITEM found, slot %u",
  2912. path->slots[0]);
  2913. ret = -EUCLEAN;
  2914. goto out;
  2915. }
  2916. } else {
  2917. btrfs_set_extent_refs(leaf, ei, refs);
  2918. btrfs_mark_buffer_dirty(trans, leaf);
  2919. }
  2920. if (found_extent) {
  2921. ret = remove_extent_backref(trans, extent_root, path,
  2922. iref, refs_to_drop, is_data);
  2923. if (ret) {
  2924. btrfs_abort_transaction(trans, ret);
  2925. goto out;
  2926. }
  2927. }
  2928. } else {
  2929. struct btrfs_squota_delta delta = {
  2930. .root = delayed_ref_root,
  2931. .num_bytes = num_bytes,
  2932. .is_data = is_data,
  2933. .is_inc = false,
  2934. .generation = btrfs_extent_generation(leaf, ei),
  2935. };
  2936. /* In this branch refs == 1 */
  2937. if (found_extent) {
  2938. if (is_data && refs_to_drop !=
  2939. extent_data_ref_count(path, iref)) {
  2940. abort_and_dump(trans, path,
  2941. "invalid refs_to_drop, current refs %u refs_to_drop %u slot %u",
  2942. extent_data_ref_count(path, iref),
  2943. refs_to_drop, path->slots[0]);
  2944. ret = -EUCLEAN;
  2945. goto out;
  2946. }
  2947. if (iref) {
  2948. if (path->slots[0] != extent_slot) {
  2949. abort_and_dump(trans, path,
  2950. "invalid iref, extent item key (%llu %u %llu) slot %u doesn't have wanted iref",
  2951. key.objectid, key.type,
  2952. key.offset, path->slots[0]);
  2953. ret = -EUCLEAN;
  2954. goto out;
  2955. }
  2956. } else {
  2957. /*
  2958. * No inline ref, we must be at SHARED_* item,
  2959. * And it's single ref, it must be:
  2960. * | extent_slot ||extent_slot + 1|
  2961. * [ EXTENT/METADATA_ITEM ][ SHARED_* ITEM ]
  2962. */
  2963. if (path->slots[0] != extent_slot + 1) {
  2964. abort_and_dump(trans, path,
  2965. "invalid SHARED_* item slot %u, previous item is not EXTENT/METADATA_ITEM",
  2966. path->slots[0]);
  2967. ret = -EUCLEAN;
  2968. goto out;
  2969. }
  2970. path->slots[0] = extent_slot;
  2971. num_to_del = 2;
  2972. }
  2973. }
  2974. /*
  2975. * We can't infer the data owner from the delayed ref, so we need
  2976. * to try to get it from the owning ref item.
  2977. *
  2978. * If it is not present, then that extent was not written under
  2979. * simple quotas mode, so we don't need to account for its deletion.
  2980. */
  2981. if (is_data)
  2982. delta.root = btrfs_get_extent_owner_root(trans->fs_info,
  2983. leaf, extent_slot);
  2984. ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
  2985. num_to_del);
  2986. if (ret) {
  2987. btrfs_abort_transaction(trans, ret);
  2988. goto out;
  2989. }
  2990. btrfs_release_path(path);
  2991. ret = do_free_extent_accounting(trans, bytenr, &delta);
  2992. }
  2993. btrfs_release_path(path);
  2994. out:
  2995. btrfs_free_path(path);
  2996. return ret;
  2997. }
  2998. /*
  2999. * when we free an block, it is possible (and likely) that we free the last
  3000. * delayed ref for that extent as well. This searches the delayed ref tree for
  3001. * a given extent, and if there are no other delayed refs to be processed, it
  3002. * removes it from the tree.
  3003. */
  3004. static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
  3005. u64 bytenr)
  3006. {
  3007. struct btrfs_delayed_ref_head *head;
  3008. struct btrfs_delayed_ref_root *delayed_refs;
  3009. int ret = 0;
  3010. delayed_refs = &trans->transaction->delayed_refs;
  3011. spin_lock(&delayed_refs->lock);
  3012. head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
  3013. if (!head)
  3014. goto out_delayed_unlock;
  3015. spin_lock(&head->lock);
  3016. if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
  3017. goto out;
  3018. if (cleanup_extent_op(head) != NULL)
  3019. goto out;
  3020. /*
  3021. * waiting for the lock here would deadlock. If someone else has it
  3022. * locked they are already in the process of dropping it anyway
  3023. */
  3024. if (!mutex_trylock(&head->mutex))
  3025. goto out;
  3026. btrfs_delete_ref_head(delayed_refs, head);
  3027. head->processing = false;
  3028. spin_unlock(&head->lock);
  3029. spin_unlock(&delayed_refs->lock);
  3030. BUG_ON(head->extent_op);
  3031. if (head->must_insert_reserved)
  3032. ret = 1;
  3033. btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
  3034. mutex_unlock(&head->mutex);
  3035. btrfs_put_delayed_ref_head(head);
  3036. return ret;
  3037. out:
  3038. spin_unlock(&head->lock);
  3039. out_delayed_unlock:
  3040. spin_unlock(&delayed_refs->lock);
  3041. return 0;
  3042. }
  3043. int btrfs_free_tree_block(struct btrfs_trans_handle *trans,
  3044. u64 root_id,
  3045. struct extent_buffer *buf,
  3046. u64 parent, int last_ref)
  3047. {
  3048. struct btrfs_fs_info *fs_info = trans->fs_info;
  3049. struct btrfs_block_group *bg;
  3050. int ret;
  3051. if (root_id != BTRFS_TREE_LOG_OBJECTID) {
  3052. struct btrfs_ref generic_ref = {
  3053. .action = BTRFS_DROP_DELAYED_REF,
  3054. .bytenr = buf->start,
  3055. .num_bytes = buf->len,
  3056. .parent = parent,
  3057. .owning_root = btrfs_header_owner(buf),
  3058. .ref_root = root_id,
  3059. };
  3060. /*
  3061. * Assert that the extent buffer is not cleared due to
  3062. * EXTENT_BUFFER_ZONED_ZEROOUT. Please refer
  3063. * btrfs_clear_buffer_dirty() and btree_csum_one_bio() for
  3064. * detail.
  3065. */
  3066. ASSERT(btrfs_header_bytenr(buf) != 0);
  3067. btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf), 0, false);
  3068. btrfs_ref_tree_mod(fs_info, &generic_ref);
  3069. ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL);
  3070. if (ret < 0)
  3071. return ret;
  3072. }
  3073. if (!last_ref)
  3074. return 0;
  3075. if (btrfs_header_generation(buf) != trans->transid)
  3076. goto out;
  3077. if (root_id != BTRFS_TREE_LOG_OBJECTID) {
  3078. ret = check_ref_cleanup(trans, buf->start);
  3079. if (!ret)
  3080. goto out;
  3081. }
  3082. bg = btrfs_lookup_block_group(fs_info, buf->start);
  3083. if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
  3084. pin_down_extent(trans, bg, buf->start, buf->len, 1);
  3085. btrfs_put_block_group(bg);
  3086. goto out;
  3087. }
  3088. /*
  3089. * If there are tree mod log users we may have recorded mod log
  3090. * operations for this node. If we re-allocate this node we
  3091. * could replay operations on this node that happened when it
  3092. * existed in a completely different root. For example if it
  3093. * was part of root A, then was reallocated to root B, and we
  3094. * are doing a btrfs_old_search_slot(root b), we could replay
  3095. * operations that happened when the block was part of root A,
  3096. * giving us an inconsistent view of the btree.
  3097. *
  3098. * We are safe from races here because at this point no other
  3099. * node or root points to this extent buffer, so if after this
  3100. * check a new tree mod log user joins we will not have an
  3101. * existing log of operations on this node that we have to
  3102. * contend with.
  3103. */
  3104. if (test_bit(BTRFS_FS_TREE_MOD_LOG_USERS, &fs_info->flags)
  3105. || btrfs_is_zoned(fs_info)) {
  3106. pin_down_extent(trans, bg, buf->start, buf->len, 1);
  3107. btrfs_put_block_group(bg);
  3108. goto out;
  3109. }
  3110. WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
  3111. btrfs_add_free_space(bg, buf->start, buf->len);
  3112. btrfs_free_reserved_bytes(bg, buf->len, 0);
  3113. btrfs_put_block_group(bg);
  3114. trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
  3115. out:
  3116. /*
  3117. * Deleting the buffer, clear the corrupt flag since it doesn't
  3118. * matter anymore.
  3119. */
  3120. clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
  3121. return 0;
  3122. }
  3123. /* Can return -ENOMEM */
  3124. int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
  3125. {
  3126. struct btrfs_fs_info *fs_info = trans->fs_info;
  3127. int ret;
  3128. if (btrfs_is_testing(fs_info))
  3129. return 0;
  3130. /*
  3131. * tree log blocks never actually go into the extent allocation
  3132. * tree, just update pinning info and exit early.
  3133. */
  3134. if (ref->ref_root == BTRFS_TREE_LOG_OBJECTID) {
  3135. btrfs_pin_extent(trans, ref->bytenr, ref->num_bytes, 1);
  3136. ret = 0;
  3137. } else if (ref->type == BTRFS_REF_METADATA) {
  3138. ret = btrfs_add_delayed_tree_ref(trans, ref, NULL);
  3139. } else {
  3140. ret = btrfs_add_delayed_data_ref(trans, ref, 0);
  3141. }
  3142. if (ref->ref_root != BTRFS_TREE_LOG_OBJECTID)
  3143. btrfs_ref_tree_mod(fs_info, ref);
  3144. return ret;
  3145. }
  3146. enum btrfs_loop_type {
  3147. /*
  3148. * Start caching block groups but do not wait for progress or for them
  3149. * to be done.
  3150. */
  3151. LOOP_CACHING_NOWAIT,
  3152. /*
  3153. * Wait for the block group free_space >= the space we're waiting for if
  3154. * the block group isn't cached.
  3155. */
  3156. LOOP_CACHING_WAIT,
  3157. /*
  3158. * Allow allocations to happen from block groups that do not yet have a
  3159. * size classification.
  3160. */
  3161. LOOP_UNSET_SIZE_CLASS,
  3162. /*
  3163. * Allocate a chunk and then retry the allocation.
  3164. */
  3165. LOOP_ALLOC_CHUNK,
  3166. /*
  3167. * Ignore the size class restrictions for this allocation.
  3168. */
  3169. LOOP_WRONG_SIZE_CLASS,
  3170. /*
  3171. * Ignore the empty size, only try to allocate the number of bytes
  3172. * needed for this allocation.
  3173. */
  3174. LOOP_NO_EMPTY_SIZE,
  3175. };
  3176. static inline void
  3177. btrfs_lock_block_group(struct btrfs_block_group *cache,
  3178. int delalloc)
  3179. {
  3180. if (delalloc)
  3181. down_read(&cache->data_rwsem);
  3182. }
  3183. static inline void btrfs_grab_block_group(struct btrfs_block_group *cache,
  3184. int delalloc)
  3185. {
  3186. btrfs_get_block_group(cache);
  3187. if (delalloc)
  3188. down_read(&cache->data_rwsem);
  3189. }
  3190. static struct btrfs_block_group *btrfs_lock_cluster(
  3191. struct btrfs_block_group *block_group,
  3192. struct btrfs_free_cluster *cluster,
  3193. int delalloc)
  3194. __acquires(&cluster->refill_lock)
  3195. {
  3196. struct btrfs_block_group *used_bg = NULL;
  3197. spin_lock(&cluster->refill_lock);
  3198. while (1) {
  3199. used_bg = cluster->block_group;
  3200. if (!used_bg)
  3201. return NULL;
  3202. if (used_bg == block_group)
  3203. return used_bg;
  3204. btrfs_get_block_group(used_bg);
  3205. if (!delalloc)
  3206. return used_bg;
  3207. if (down_read_trylock(&used_bg->data_rwsem))
  3208. return used_bg;
  3209. spin_unlock(&cluster->refill_lock);
  3210. /* We should only have one-level nested. */
  3211. down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
  3212. spin_lock(&cluster->refill_lock);
  3213. if (used_bg == cluster->block_group)
  3214. return used_bg;
  3215. up_read(&used_bg->data_rwsem);
  3216. btrfs_put_block_group(used_bg);
  3217. }
  3218. }
  3219. static inline void
  3220. btrfs_release_block_group(struct btrfs_block_group *cache,
  3221. int delalloc)
  3222. {
  3223. if (delalloc)
  3224. up_read(&cache->data_rwsem);
  3225. btrfs_put_block_group(cache);
  3226. }
  3227. static bool find_free_extent_check_size_class(const struct find_free_extent_ctl *ffe_ctl,
  3228. const struct btrfs_block_group *bg)
  3229. {
  3230. if (ffe_ctl->policy == BTRFS_EXTENT_ALLOC_ZONED)
  3231. return true;
  3232. if (!btrfs_block_group_should_use_size_class(bg))
  3233. return true;
  3234. if (ffe_ctl->loop >= LOOP_WRONG_SIZE_CLASS)
  3235. return true;
  3236. if (ffe_ctl->loop >= LOOP_UNSET_SIZE_CLASS &&
  3237. bg->size_class == BTRFS_BG_SZ_NONE)
  3238. return true;
  3239. return ffe_ctl->size_class == bg->size_class;
  3240. }
  3241. /*
  3242. * Helper function for find_free_extent().
  3243. *
  3244. * Return -ENOENT to inform caller that we need fallback to unclustered mode.
  3245. * Return >0 to inform caller that we find nothing
  3246. * Return 0 means we have found a location and set ffe_ctl->found_offset.
  3247. */
  3248. static int find_free_extent_clustered(struct btrfs_block_group *bg,
  3249. struct find_free_extent_ctl *ffe_ctl,
  3250. struct btrfs_block_group **cluster_bg_ret)
  3251. {
  3252. struct btrfs_block_group *cluster_bg;
  3253. struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
  3254. u64 aligned_cluster;
  3255. u64 offset;
  3256. int ret;
  3257. cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
  3258. if (!cluster_bg)
  3259. goto refill_cluster;
  3260. if (cluster_bg != bg && (cluster_bg->ro ||
  3261. !block_group_bits(cluster_bg, ffe_ctl->flags) ||
  3262. !find_free_extent_check_size_class(ffe_ctl, cluster_bg)))
  3263. goto release_cluster;
  3264. offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
  3265. ffe_ctl->num_bytes, cluster_bg->start,
  3266. &ffe_ctl->max_extent_size);
  3267. if (offset) {
  3268. /* We have a block, we're done */
  3269. spin_unlock(&last_ptr->refill_lock);
  3270. trace_btrfs_reserve_extent_cluster(cluster_bg, ffe_ctl);
  3271. *cluster_bg_ret = cluster_bg;
  3272. ffe_ctl->found_offset = offset;
  3273. return 0;
  3274. }
  3275. WARN_ON(last_ptr->block_group != cluster_bg);
  3276. release_cluster:
  3277. /*
  3278. * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
  3279. * lets just skip it and let the allocator find whatever block it can
  3280. * find. If we reach this point, we will have tried the cluster
  3281. * allocator plenty of times and not have found anything, so we are
  3282. * likely way too fragmented for the clustering stuff to find anything.
  3283. *
  3284. * However, if the cluster is taken from the current block group,
  3285. * release the cluster first, so that we stand a better chance of
  3286. * succeeding in the unclustered allocation.
  3287. */
  3288. if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
  3289. spin_unlock(&last_ptr->refill_lock);
  3290. btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
  3291. return -ENOENT;
  3292. }
  3293. /* This cluster didn't work out, free it and start over */
  3294. btrfs_return_cluster_to_free_space(NULL, last_ptr);
  3295. if (cluster_bg != bg)
  3296. btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
  3297. refill_cluster:
  3298. if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
  3299. spin_unlock(&last_ptr->refill_lock);
  3300. return -ENOENT;
  3301. }
  3302. aligned_cluster = max_t(u64,
  3303. ffe_ctl->empty_cluster + ffe_ctl->empty_size,
  3304. bg->full_stripe_len);
  3305. ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
  3306. ffe_ctl->num_bytes, aligned_cluster);
  3307. if (ret == 0) {
  3308. /* Now pull our allocation out of this cluster */
  3309. offset = btrfs_alloc_from_cluster(bg, last_ptr,
  3310. ffe_ctl->num_bytes, ffe_ctl->search_start,
  3311. &ffe_ctl->max_extent_size);
  3312. if (offset) {
  3313. /* We found one, proceed */
  3314. spin_unlock(&last_ptr->refill_lock);
  3315. ffe_ctl->found_offset = offset;
  3316. trace_btrfs_reserve_extent_cluster(bg, ffe_ctl);
  3317. return 0;
  3318. }
  3319. }
  3320. /*
  3321. * At this point we either didn't find a cluster or we weren't able to
  3322. * allocate a block from our cluster. Free the cluster we've been
  3323. * trying to use, and go to the next block group.
  3324. */
  3325. btrfs_return_cluster_to_free_space(NULL, last_ptr);
  3326. spin_unlock(&last_ptr->refill_lock);
  3327. return 1;
  3328. }
  3329. /*
  3330. * Return >0 to inform caller that we find nothing
  3331. * Return 0 when we found an free extent and set ffe_ctrl->found_offset
  3332. */
  3333. static int find_free_extent_unclustered(struct btrfs_block_group *bg,
  3334. struct find_free_extent_ctl *ffe_ctl)
  3335. {
  3336. struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
  3337. u64 offset;
  3338. /*
  3339. * We are doing an unclustered allocation, set the fragmented flag so
  3340. * we don't bother trying to setup a cluster again until we get more
  3341. * space.
  3342. */
  3343. if (unlikely(last_ptr)) {
  3344. spin_lock(&last_ptr->lock);
  3345. last_ptr->fragmented = 1;
  3346. spin_unlock(&last_ptr->lock);
  3347. }
  3348. if (ffe_ctl->cached) {
  3349. struct btrfs_free_space_ctl *free_space_ctl;
  3350. free_space_ctl = bg->free_space_ctl;
  3351. spin_lock(&free_space_ctl->tree_lock);
  3352. if (free_space_ctl->free_space <
  3353. ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
  3354. ffe_ctl->empty_size) {
  3355. ffe_ctl->total_free_space = max_t(u64,
  3356. ffe_ctl->total_free_space,
  3357. free_space_ctl->free_space);
  3358. spin_unlock(&free_space_ctl->tree_lock);
  3359. return 1;
  3360. }
  3361. spin_unlock(&free_space_ctl->tree_lock);
  3362. }
  3363. offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
  3364. ffe_ctl->num_bytes, ffe_ctl->empty_size,
  3365. &ffe_ctl->max_extent_size);
  3366. if (!offset)
  3367. return 1;
  3368. ffe_ctl->found_offset = offset;
  3369. return 0;
  3370. }
  3371. static int do_allocation_clustered(struct btrfs_block_group *block_group,
  3372. struct find_free_extent_ctl *ffe_ctl,
  3373. struct btrfs_block_group **bg_ret)
  3374. {
  3375. int ret;
  3376. /* We want to try and use the cluster allocator, so lets look there */
  3377. if (ffe_ctl->last_ptr && ffe_ctl->use_cluster) {
  3378. ret = find_free_extent_clustered(block_group, ffe_ctl, bg_ret);
  3379. if (ret >= 0)
  3380. return ret;
  3381. /* ret == -ENOENT case falls through */
  3382. }
  3383. return find_free_extent_unclustered(block_group, ffe_ctl);
  3384. }
  3385. /*
  3386. * Tree-log block group locking
  3387. * ============================
  3388. *
  3389. * fs_info::treelog_bg_lock protects the fs_info::treelog_bg which
  3390. * indicates the starting address of a block group, which is reserved only
  3391. * for tree-log metadata.
  3392. *
  3393. * Lock nesting
  3394. * ============
  3395. *
  3396. * space_info::lock
  3397. * block_group::lock
  3398. * fs_info::treelog_bg_lock
  3399. */
  3400. /*
  3401. * Simple allocator for sequential-only block group. It only allows sequential
  3402. * allocation. No need to play with trees. This function also reserves the
  3403. * bytes as in btrfs_add_reserved_bytes.
  3404. */
  3405. static int do_allocation_zoned(struct btrfs_block_group *block_group,
  3406. struct find_free_extent_ctl *ffe_ctl,
  3407. struct btrfs_block_group **bg_ret)
  3408. {
  3409. struct btrfs_fs_info *fs_info = block_group->fs_info;
  3410. struct btrfs_space_info *space_info = block_group->space_info;
  3411. struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
  3412. u64 start = block_group->start;
  3413. u64 num_bytes = ffe_ctl->num_bytes;
  3414. u64 avail;
  3415. u64 bytenr = block_group->start;
  3416. u64 log_bytenr;
  3417. u64 data_reloc_bytenr;
  3418. int ret = 0;
  3419. bool skip = false;
  3420. ASSERT(btrfs_is_zoned(block_group->fs_info));
  3421. /*
  3422. * Do not allow non-tree-log blocks in the dedicated tree-log block
  3423. * group, and vice versa.
  3424. */
  3425. spin_lock(&fs_info->treelog_bg_lock);
  3426. log_bytenr = fs_info->treelog_bg;
  3427. if (log_bytenr && ((ffe_ctl->for_treelog && bytenr != log_bytenr) ||
  3428. (!ffe_ctl->for_treelog && bytenr == log_bytenr)))
  3429. skip = true;
  3430. spin_unlock(&fs_info->treelog_bg_lock);
  3431. if (skip)
  3432. return 1;
  3433. /*
  3434. * Do not allow non-relocation blocks in the dedicated relocation block
  3435. * group, and vice versa.
  3436. */
  3437. spin_lock(&fs_info->relocation_bg_lock);
  3438. data_reloc_bytenr = fs_info->data_reloc_bg;
  3439. if (data_reloc_bytenr &&
  3440. ((ffe_ctl->for_data_reloc && bytenr != data_reloc_bytenr) ||
  3441. (!ffe_ctl->for_data_reloc && bytenr == data_reloc_bytenr)))
  3442. skip = true;
  3443. spin_unlock(&fs_info->relocation_bg_lock);
  3444. if (skip)
  3445. return 1;
  3446. /* Check RO and no space case before trying to activate it */
  3447. spin_lock(&block_group->lock);
  3448. if (block_group->ro || btrfs_zoned_bg_is_full(block_group)) {
  3449. ret = 1;
  3450. /*
  3451. * May need to clear fs_info->{treelog,data_reloc}_bg.
  3452. * Return the error after taking the locks.
  3453. */
  3454. }
  3455. spin_unlock(&block_group->lock);
  3456. /* Metadata block group is activated at write time. */
  3457. if (!ret && (block_group->flags & BTRFS_BLOCK_GROUP_DATA) &&
  3458. !btrfs_zone_activate(block_group)) {
  3459. ret = 1;
  3460. /*
  3461. * May need to clear fs_info->{treelog,data_reloc}_bg.
  3462. * Return the error after taking the locks.
  3463. */
  3464. }
  3465. spin_lock(&space_info->lock);
  3466. spin_lock(&block_group->lock);
  3467. spin_lock(&fs_info->treelog_bg_lock);
  3468. spin_lock(&fs_info->relocation_bg_lock);
  3469. if (ret)
  3470. goto out;
  3471. ASSERT(!ffe_ctl->for_treelog ||
  3472. block_group->start == fs_info->treelog_bg ||
  3473. fs_info->treelog_bg == 0);
  3474. ASSERT(!ffe_ctl->for_data_reloc ||
  3475. block_group->start == fs_info->data_reloc_bg ||
  3476. fs_info->data_reloc_bg == 0);
  3477. if (block_group->ro ||
  3478. (!ffe_ctl->for_data_reloc &&
  3479. test_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags))) {
  3480. ret = 1;
  3481. goto out;
  3482. }
  3483. /*
  3484. * Do not allow currently using block group to be tree-log dedicated
  3485. * block group.
  3486. */
  3487. if (ffe_ctl->for_treelog && !fs_info->treelog_bg &&
  3488. (block_group->used || block_group->reserved)) {
  3489. ret = 1;
  3490. goto out;
  3491. }
  3492. /*
  3493. * Do not allow currently used block group to be the data relocation
  3494. * dedicated block group.
  3495. */
  3496. if (ffe_ctl->for_data_reloc && !fs_info->data_reloc_bg &&
  3497. (block_group->used || block_group->reserved)) {
  3498. ret = 1;
  3499. goto out;
  3500. }
  3501. WARN_ON_ONCE(block_group->alloc_offset > block_group->zone_capacity);
  3502. avail = block_group->zone_capacity - block_group->alloc_offset;
  3503. if (avail < num_bytes) {
  3504. if (ffe_ctl->max_extent_size < avail) {
  3505. /*
  3506. * With sequential allocator, free space is always
  3507. * contiguous
  3508. */
  3509. ffe_ctl->max_extent_size = avail;
  3510. ffe_ctl->total_free_space = avail;
  3511. }
  3512. ret = 1;
  3513. goto out;
  3514. }
  3515. if (ffe_ctl->for_treelog && !fs_info->treelog_bg)
  3516. fs_info->treelog_bg = block_group->start;
  3517. if (ffe_ctl->for_data_reloc) {
  3518. if (!fs_info->data_reloc_bg)
  3519. fs_info->data_reloc_bg = block_group->start;
  3520. /*
  3521. * Do not allow allocations from this block group, unless it is
  3522. * for data relocation. Compared to increasing the ->ro, setting
  3523. * the ->zoned_data_reloc_ongoing flag still allows nocow
  3524. * writers to come in. See btrfs_inc_nocow_writers().
  3525. *
  3526. * We need to disable an allocation to avoid an allocation of
  3527. * regular (non-relocation data) extent. With mix of relocation
  3528. * extents and regular extents, we can dispatch WRITE commands
  3529. * (for relocation extents) and ZONE APPEND commands (for
  3530. * regular extents) at the same time to the same zone, which
  3531. * easily break the write pointer.
  3532. *
  3533. * Also, this flag avoids this block group to be zone finished.
  3534. */
  3535. set_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags);
  3536. }
  3537. ffe_ctl->found_offset = start + block_group->alloc_offset;
  3538. block_group->alloc_offset += num_bytes;
  3539. spin_lock(&ctl->tree_lock);
  3540. ctl->free_space -= num_bytes;
  3541. spin_unlock(&ctl->tree_lock);
  3542. /*
  3543. * We do not check if found_offset is aligned to stripesize. The
  3544. * address is anyway rewritten when using zone append writing.
  3545. */
  3546. ffe_ctl->search_start = ffe_ctl->found_offset;
  3547. out:
  3548. if (ret && ffe_ctl->for_treelog)
  3549. fs_info->treelog_bg = 0;
  3550. if (ret && ffe_ctl->for_data_reloc)
  3551. fs_info->data_reloc_bg = 0;
  3552. spin_unlock(&fs_info->relocation_bg_lock);
  3553. spin_unlock(&fs_info->treelog_bg_lock);
  3554. spin_unlock(&block_group->lock);
  3555. spin_unlock(&space_info->lock);
  3556. return ret;
  3557. }
  3558. static int do_allocation(struct btrfs_block_group *block_group,
  3559. struct find_free_extent_ctl *ffe_ctl,
  3560. struct btrfs_block_group **bg_ret)
  3561. {
  3562. switch (ffe_ctl->policy) {
  3563. case BTRFS_EXTENT_ALLOC_CLUSTERED:
  3564. return do_allocation_clustered(block_group, ffe_ctl, bg_ret);
  3565. case BTRFS_EXTENT_ALLOC_ZONED:
  3566. return do_allocation_zoned(block_group, ffe_ctl, bg_ret);
  3567. default:
  3568. BUG();
  3569. }
  3570. }
  3571. static void release_block_group(struct btrfs_block_group *block_group,
  3572. struct find_free_extent_ctl *ffe_ctl,
  3573. int delalloc)
  3574. {
  3575. switch (ffe_ctl->policy) {
  3576. case BTRFS_EXTENT_ALLOC_CLUSTERED:
  3577. ffe_ctl->retry_uncached = false;
  3578. break;
  3579. case BTRFS_EXTENT_ALLOC_ZONED:
  3580. /* Nothing to do */
  3581. break;
  3582. default:
  3583. BUG();
  3584. }
  3585. BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
  3586. ffe_ctl->index);
  3587. btrfs_release_block_group(block_group, delalloc);
  3588. }
  3589. static void found_extent_clustered(struct find_free_extent_ctl *ffe_ctl,
  3590. struct btrfs_key *ins)
  3591. {
  3592. struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
  3593. if (!ffe_ctl->use_cluster && last_ptr) {
  3594. spin_lock(&last_ptr->lock);
  3595. last_ptr->window_start = ins->objectid;
  3596. spin_unlock(&last_ptr->lock);
  3597. }
  3598. }
  3599. static void found_extent(struct find_free_extent_ctl *ffe_ctl,
  3600. struct btrfs_key *ins)
  3601. {
  3602. switch (ffe_ctl->policy) {
  3603. case BTRFS_EXTENT_ALLOC_CLUSTERED:
  3604. found_extent_clustered(ffe_ctl, ins);
  3605. break;
  3606. case BTRFS_EXTENT_ALLOC_ZONED:
  3607. /* Nothing to do */
  3608. break;
  3609. default:
  3610. BUG();
  3611. }
  3612. }
  3613. static int can_allocate_chunk_zoned(struct btrfs_fs_info *fs_info,
  3614. struct find_free_extent_ctl *ffe_ctl)
  3615. {
  3616. /* Block group's activeness is not a requirement for METADATA block groups. */
  3617. if (!(ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA))
  3618. return 0;
  3619. /* If we can activate new zone, just allocate a chunk and use it */
  3620. if (btrfs_can_activate_zone(fs_info->fs_devices, ffe_ctl->flags))
  3621. return 0;
  3622. /*
  3623. * We already reached the max active zones. Try to finish one block
  3624. * group to make a room for a new block group. This is only possible
  3625. * for a data block group because btrfs_zone_finish() may need to wait
  3626. * for a running transaction which can cause a deadlock for metadata
  3627. * allocation.
  3628. */
  3629. if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA) {
  3630. int ret = btrfs_zone_finish_one_bg(fs_info);
  3631. if (ret == 1)
  3632. return 0;
  3633. else if (ret < 0)
  3634. return ret;
  3635. }
  3636. /*
  3637. * If we have enough free space left in an already active block group
  3638. * and we can't activate any other zone now, do not allow allocating a
  3639. * new chunk and let find_free_extent() retry with a smaller size.
  3640. */
  3641. if (ffe_ctl->max_extent_size >= ffe_ctl->min_alloc_size)
  3642. return -ENOSPC;
  3643. /*
  3644. * Even min_alloc_size is not left in any block groups. Since we cannot
  3645. * activate a new block group, allocating it may not help. Let's tell a
  3646. * caller to try again and hope it progress something by writing some
  3647. * parts of the region. That is only possible for data block groups,
  3648. * where a part of the region can be written.
  3649. */
  3650. if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA)
  3651. return -EAGAIN;
  3652. /*
  3653. * We cannot activate a new block group and no enough space left in any
  3654. * block groups. So, allocating a new block group may not help. But,
  3655. * there is nothing to do anyway, so let's go with it.
  3656. */
  3657. return 0;
  3658. }
  3659. static int can_allocate_chunk(struct btrfs_fs_info *fs_info,
  3660. struct find_free_extent_ctl *ffe_ctl)
  3661. {
  3662. switch (ffe_ctl->policy) {
  3663. case BTRFS_EXTENT_ALLOC_CLUSTERED:
  3664. return 0;
  3665. case BTRFS_EXTENT_ALLOC_ZONED:
  3666. return can_allocate_chunk_zoned(fs_info, ffe_ctl);
  3667. default:
  3668. BUG();
  3669. }
  3670. }
  3671. /*
  3672. * Return >0 means caller needs to re-search for free extent
  3673. * Return 0 means we have the needed free extent.
  3674. * Return <0 means we failed to locate any free extent.
  3675. */
  3676. static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
  3677. struct btrfs_key *ins,
  3678. struct find_free_extent_ctl *ffe_ctl,
  3679. bool full_search)
  3680. {
  3681. struct btrfs_root *root = fs_info->chunk_root;
  3682. int ret;
  3683. if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
  3684. ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
  3685. ffe_ctl->orig_have_caching_bg = true;
  3686. if (ins->objectid) {
  3687. found_extent(ffe_ctl, ins);
  3688. return 0;
  3689. }
  3690. if (ffe_ctl->loop >= LOOP_CACHING_WAIT && ffe_ctl->have_caching_bg)
  3691. return 1;
  3692. ffe_ctl->index++;
  3693. if (ffe_ctl->index < BTRFS_NR_RAID_TYPES)
  3694. return 1;
  3695. /* See the comments for btrfs_loop_type for an explanation of the phases. */
  3696. if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
  3697. ffe_ctl->index = 0;
  3698. /*
  3699. * We want to skip the LOOP_CACHING_WAIT step if we don't have
  3700. * any uncached bgs and we've already done a full search
  3701. * through.
  3702. */
  3703. if (ffe_ctl->loop == LOOP_CACHING_NOWAIT &&
  3704. (!ffe_ctl->orig_have_caching_bg && full_search))
  3705. ffe_ctl->loop++;
  3706. ffe_ctl->loop++;
  3707. if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
  3708. struct btrfs_trans_handle *trans;
  3709. int exist = 0;
  3710. /* Check if allocation policy allows to create a new chunk */
  3711. ret = can_allocate_chunk(fs_info, ffe_ctl);
  3712. if (ret)
  3713. return ret;
  3714. trans = current->journal_info;
  3715. if (trans)
  3716. exist = 1;
  3717. else
  3718. trans = btrfs_join_transaction(root);
  3719. if (IS_ERR(trans)) {
  3720. ret = PTR_ERR(trans);
  3721. return ret;
  3722. }
  3723. ret = btrfs_chunk_alloc(trans, ffe_ctl->flags,
  3724. CHUNK_ALLOC_FORCE_FOR_EXTENT);
  3725. /* Do not bail out on ENOSPC since we can do more. */
  3726. if (ret == -ENOSPC) {
  3727. ret = 0;
  3728. ffe_ctl->loop++;
  3729. }
  3730. else if (ret < 0)
  3731. btrfs_abort_transaction(trans, ret);
  3732. else
  3733. ret = 0;
  3734. if (!exist)
  3735. btrfs_end_transaction(trans);
  3736. if (ret)
  3737. return ret;
  3738. }
  3739. if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
  3740. if (ffe_ctl->policy != BTRFS_EXTENT_ALLOC_CLUSTERED)
  3741. return -ENOSPC;
  3742. /*
  3743. * Don't loop again if we already have no empty_size and
  3744. * no empty_cluster.
  3745. */
  3746. if (ffe_ctl->empty_size == 0 &&
  3747. ffe_ctl->empty_cluster == 0)
  3748. return -ENOSPC;
  3749. ffe_ctl->empty_size = 0;
  3750. ffe_ctl->empty_cluster = 0;
  3751. }
  3752. return 1;
  3753. }
  3754. return -ENOSPC;
  3755. }
  3756. static int prepare_allocation_clustered(struct btrfs_fs_info *fs_info,
  3757. struct find_free_extent_ctl *ffe_ctl,
  3758. struct btrfs_space_info *space_info,
  3759. struct btrfs_key *ins)
  3760. {
  3761. /*
  3762. * If our free space is heavily fragmented we may not be able to make
  3763. * big contiguous allocations, so instead of doing the expensive search
  3764. * for free space, simply return ENOSPC with our max_extent_size so we
  3765. * can go ahead and search for a more manageable chunk.
  3766. *
  3767. * If our max_extent_size is large enough for our allocation simply
  3768. * disable clustering since we will likely not be able to find enough
  3769. * space to create a cluster and induce latency trying.
  3770. */
  3771. if (space_info->max_extent_size) {
  3772. spin_lock(&space_info->lock);
  3773. if (space_info->max_extent_size &&
  3774. ffe_ctl->num_bytes > space_info->max_extent_size) {
  3775. ins->offset = space_info->max_extent_size;
  3776. spin_unlock(&space_info->lock);
  3777. return -ENOSPC;
  3778. } else if (space_info->max_extent_size) {
  3779. ffe_ctl->use_cluster = false;
  3780. }
  3781. spin_unlock(&space_info->lock);
  3782. }
  3783. ffe_ctl->last_ptr = fetch_cluster_info(fs_info, space_info,
  3784. &ffe_ctl->empty_cluster);
  3785. if (ffe_ctl->last_ptr) {
  3786. struct btrfs_free_cluster *last_ptr = ffe_ctl->last_ptr;
  3787. spin_lock(&last_ptr->lock);
  3788. if (last_ptr->block_group)
  3789. ffe_ctl->hint_byte = last_ptr->window_start;
  3790. if (last_ptr->fragmented) {
  3791. /*
  3792. * We still set window_start so we can keep track of the
  3793. * last place we found an allocation to try and save
  3794. * some time.
  3795. */
  3796. ffe_ctl->hint_byte = last_ptr->window_start;
  3797. ffe_ctl->use_cluster = false;
  3798. }
  3799. spin_unlock(&last_ptr->lock);
  3800. }
  3801. return 0;
  3802. }
  3803. static int prepare_allocation_zoned(struct btrfs_fs_info *fs_info,
  3804. struct find_free_extent_ctl *ffe_ctl)
  3805. {
  3806. if (ffe_ctl->for_treelog) {
  3807. spin_lock(&fs_info->treelog_bg_lock);
  3808. if (fs_info->treelog_bg)
  3809. ffe_ctl->hint_byte = fs_info->treelog_bg;
  3810. spin_unlock(&fs_info->treelog_bg_lock);
  3811. } else if (ffe_ctl->for_data_reloc) {
  3812. spin_lock(&fs_info->relocation_bg_lock);
  3813. if (fs_info->data_reloc_bg)
  3814. ffe_ctl->hint_byte = fs_info->data_reloc_bg;
  3815. spin_unlock(&fs_info->relocation_bg_lock);
  3816. } else if (ffe_ctl->flags & BTRFS_BLOCK_GROUP_DATA) {
  3817. struct btrfs_block_group *block_group;
  3818. spin_lock(&fs_info->zone_active_bgs_lock);
  3819. list_for_each_entry(block_group, &fs_info->zone_active_bgs, active_bg_list) {
  3820. /*
  3821. * No lock is OK here because avail is monotinically
  3822. * decreasing, and this is just a hint.
  3823. */
  3824. u64 avail = block_group->zone_capacity - block_group->alloc_offset;
  3825. if (block_group_bits(block_group, ffe_ctl->flags) &&
  3826. avail >= ffe_ctl->num_bytes) {
  3827. ffe_ctl->hint_byte = block_group->start;
  3828. break;
  3829. }
  3830. }
  3831. spin_unlock(&fs_info->zone_active_bgs_lock);
  3832. }
  3833. return 0;
  3834. }
  3835. static int prepare_allocation(struct btrfs_fs_info *fs_info,
  3836. struct find_free_extent_ctl *ffe_ctl,
  3837. struct btrfs_space_info *space_info,
  3838. struct btrfs_key *ins)
  3839. {
  3840. switch (ffe_ctl->policy) {
  3841. case BTRFS_EXTENT_ALLOC_CLUSTERED:
  3842. return prepare_allocation_clustered(fs_info, ffe_ctl,
  3843. space_info, ins);
  3844. case BTRFS_EXTENT_ALLOC_ZONED:
  3845. return prepare_allocation_zoned(fs_info, ffe_ctl);
  3846. default:
  3847. BUG();
  3848. }
  3849. }
  3850. /*
  3851. * walks the btree of allocated extents and find a hole of a given size.
  3852. * The key ins is changed to record the hole:
  3853. * ins->objectid == start position
  3854. * ins->flags = BTRFS_EXTENT_ITEM_KEY
  3855. * ins->offset == the size of the hole.
  3856. * Any available blocks before search_start are skipped.
  3857. *
  3858. * If there is no suitable free space, we will record the max size of
  3859. * the free space extent currently.
  3860. *
  3861. * The overall logic and call chain:
  3862. *
  3863. * find_free_extent()
  3864. * |- Iterate through all block groups
  3865. * | |- Get a valid block group
  3866. * | |- Try to do clustered allocation in that block group
  3867. * | |- Try to do unclustered allocation in that block group
  3868. * | |- Check if the result is valid
  3869. * | | |- If valid, then exit
  3870. * | |- Jump to next block group
  3871. * |
  3872. * |- Push harder to find free extents
  3873. * |- If not found, re-iterate all block groups
  3874. */
  3875. static noinline int find_free_extent(struct btrfs_root *root,
  3876. struct btrfs_key *ins,
  3877. struct find_free_extent_ctl *ffe_ctl)
  3878. {
  3879. struct btrfs_fs_info *fs_info = root->fs_info;
  3880. int ret = 0;
  3881. int cache_block_group_error = 0;
  3882. struct btrfs_block_group *block_group = NULL;
  3883. struct btrfs_space_info *space_info;
  3884. bool full_search = false;
  3885. WARN_ON(ffe_ctl->num_bytes < fs_info->sectorsize);
  3886. ffe_ctl->search_start = 0;
  3887. /* For clustered allocation */
  3888. ffe_ctl->empty_cluster = 0;
  3889. ffe_ctl->last_ptr = NULL;
  3890. ffe_ctl->use_cluster = true;
  3891. ffe_ctl->have_caching_bg = false;
  3892. ffe_ctl->orig_have_caching_bg = false;
  3893. ffe_ctl->index = btrfs_bg_flags_to_raid_index(ffe_ctl->flags);
  3894. ffe_ctl->loop = 0;
  3895. ffe_ctl->retry_uncached = false;
  3896. ffe_ctl->cached = 0;
  3897. ffe_ctl->max_extent_size = 0;
  3898. ffe_ctl->total_free_space = 0;
  3899. ffe_ctl->found_offset = 0;
  3900. ffe_ctl->policy = BTRFS_EXTENT_ALLOC_CLUSTERED;
  3901. ffe_ctl->size_class = btrfs_calc_block_group_size_class(ffe_ctl->num_bytes);
  3902. if (btrfs_is_zoned(fs_info))
  3903. ffe_ctl->policy = BTRFS_EXTENT_ALLOC_ZONED;
  3904. ins->type = BTRFS_EXTENT_ITEM_KEY;
  3905. ins->objectid = 0;
  3906. ins->offset = 0;
  3907. trace_find_free_extent(root, ffe_ctl);
  3908. space_info = btrfs_find_space_info(fs_info, ffe_ctl->flags);
  3909. if (!space_info) {
  3910. btrfs_err(fs_info, "No space info for %llu", ffe_ctl->flags);
  3911. return -ENOSPC;
  3912. }
  3913. ret = prepare_allocation(fs_info, ffe_ctl, space_info, ins);
  3914. if (ret < 0)
  3915. return ret;
  3916. ffe_ctl->search_start = max(ffe_ctl->search_start,
  3917. first_logical_byte(fs_info));
  3918. ffe_ctl->search_start = max(ffe_ctl->search_start, ffe_ctl->hint_byte);
  3919. if (ffe_ctl->search_start == ffe_ctl->hint_byte) {
  3920. block_group = btrfs_lookup_block_group(fs_info,
  3921. ffe_ctl->search_start);
  3922. /*
  3923. * we don't want to use the block group if it doesn't match our
  3924. * allocation bits, or if its not cached.
  3925. *
  3926. * However if we are re-searching with an ideal block group
  3927. * picked out then we don't care that the block group is cached.
  3928. */
  3929. if (block_group && block_group_bits(block_group, ffe_ctl->flags) &&
  3930. block_group->cached != BTRFS_CACHE_NO) {
  3931. down_read(&space_info->groups_sem);
  3932. if (list_empty(&block_group->list) ||
  3933. block_group->ro) {
  3934. /*
  3935. * someone is removing this block group,
  3936. * we can't jump into the have_block_group
  3937. * target because our list pointers are not
  3938. * valid
  3939. */
  3940. btrfs_put_block_group(block_group);
  3941. up_read(&space_info->groups_sem);
  3942. } else {
  3943. ffe_ctl->index = btrfs_bg_flags_to_raid_index(
  3944. block_group->flags);
  3945. btrfs_lock_block_group(block_group,
  3946. ffe_ctl->delalloc);
  3947. ffe_ctl->hinted = true;
  3948. goto have_block_group;
  3949. }
  3950. } else if (block_group) {
  3951. btrfs_put_block_group(block_group);
  3952. }
  3953. }
  3954. search:
  3955. trace_find_free_extent_search_loop(root, ffe_ctl);
  3956. ffe_ctl->have_caching_bg = false;
  3957. if (ffe_ctl->index == btrfs_bg_flags_to_raid_index(ffe_ctl->flags) ||
  3958. ffe_ctl->index == 0)
  3959. full_search = true;
  3960. down_read(&space_info->groups_sem);
  3961. list_for_each_entry(block_group,
  3962. &space_info->block_groups[ffe_ctl->index], list) {
  3963. struct btrfs_block_group *bg_ret;
  3964. ffe_ctl->hinted = false;
  3965. /* If the block group is read-only, we can skip it entirely. */
  3966. if (unlikely(block_group->ro)) {
  3967. if (ffe_ctl->for_treelog)
  3968. btrfs_clear_treelog_bg(block_group);
  3969. if (ffe_ctl->for_data_reloc)
  3970. btrfs_clear_data_reloc_bg(block_group);
  3971. continue;
  3972. }
  3973. btrfs_grab_block_group(block_group, ffe_ctl->delalloc);
  3974. ffe_ctl->search_start = block_group->start;
  3975. /*
  3976. * this can happen if we end up cycling through all the
  3977. * raid types, but we want to make sure we only allocate
  3978. * for the proper type.
  3979. */
  3980. if (!block_group_bits(block_group, ffe_ctl->flags)) {
  3981. u64 extra = BTRFS_BLOCK_GROUP_DUP |
  3982. BTRFS_BLOCK_GROUP_RAID1_MASK |
  3983. BTRFS_BLOCK_GROUP_RAID56_MASK |
  3984. BTRFS_BLOCK_GROUP_RAID10;
  3985. /*
  3986. * if they asked for extra copies and this block group
  3987. * doesn't provide them, bail. This does allow us to
  3988. * fill raid0 from raid1.
  3989. */
  3990. if ((ffe_ctl->flags & extra) && !(block_group->flags & extra))
  3991. goto loop;
  3992. /*
  3993. * This block group has different flags than we want.
  3994. * It's possible that we have MIXED_GROUP flag but no
  3995. * block group is mixed. Just skip such block group.
  3996. */
  3997. btrfs_release_block_group(block_group, ffe_ctl->delalloc);
  3998. continue;
  3999. }
  4000. have_block_group:
  4001. trace_find_free_extent_have_block_group(root, ffe_ctl, block_group);
  4002. ffe_ctl->cached = btrfs_block_group_done(block_group);
  4003. if (unlikely(!ffe_ctl->cached)) {
  4004. ffe_ctl->have_caching_bg = true;
  4005. ret = btrfs_cache_block_group(block_group, false);
  4006. /*
  4007. * If we get ENOMEM here or something else we want to
  4008. * try other block groups, because it may not be fatal.
  4009. * However if we can't find anything else we need to
  4010. * save our return here so that we return the actual
  4011. * error that caused problems, not ENOSPC.
  4012. */
  4013. if (ret < 0) {
  4014. if (!cache_block_group_error)
  4015. cache_block_group_error = ret;
  4016. ret = 0;
  4017. goto loop;
  4018. }
  4019. ret = 0;
  4020. }
  4021. if (unlikely(block_group->cached == BTRFS_CACHE_ERROR)) {
  4022. if (!cache_block_group_error)
  4023. cache_block_group_error = -EIO;
  4024. goto loop;
  4025. }
  4026. if (!find_free_extent_check_size_class(ffe_ctl, block_group))
  4027. goto loop;
  4028. bg_ret = NULL;
  4029. ret = do_allocation(block_group, ffe_ctl, &bg_ret);
  4030. if (ret > 0)
  4031. goto loop;
  4032. if (bg_ret && bg_ret != block_group) {
  4033. btrfs_release_block_group(block_group, ffe_ctl->delalloc);
  4034. block_group = bg_ret;
  4035. }
  4036. /* Checks */
  4037. ffe_ctl->search_start = round_up(ffe_ctl->found_offset,
  4038. fs_info->stripesize);
  4039. /* move on to the next group */
  4040. if (ffe_ctl->search_start + ffe_ctl->num_bytes >
  4041. block_group->start + block_group->length) {
  4042. btrfs_add_free_space_unused(block_group,
  4043. ffe_ctl->found_offset,
  4044. ffe_ctl->num_bytes);
  4045. goto loop;
  4046. }
  4047. if (ffe_ctl->found_offset < ffe_ctl->search_start)
  4048. btrfs_add_free_space_unused(block_group,
  4049. ffe_ctl->found_offset,
  4050. ffe_ctl->search_start - ffe_ctl->found_offset);
  4051. ret = btrfs_add_reserved_bytes(block_group, ffe_ctl->ram_bytes,
  4052. ffe_ctl->num_bytes,
  4053. ffe_ctl->delalloc,
  4054. ffe_ctl->loop >= LOOP_WRONG_SIZE_CLASS);
  4055. if (ret == -EAGAIN) {
  4056. btrfs_add_free_space_unused(block_group,
  4057. ffe_ctl->found_offset,
  4058. ffe_ctl->num_bytes);
  4059. goto loop;
  4060. }
  4061. btrfs_inc_block_group_reservations(block_group);
  4062. /* we are all good, lets return */
  4063. ins->objectid = ffe_ctl->search_start;
  4064. ins->offset = ffe_ctl->num_bytes;
  4065. trace_btrfs_reserve_extent(block_group, ffe_ctl);
  4066. btrfs_release_block_group(block_group, ffe_ctl->delalloc);
  4067. break;
  4068. loop:
  4069. if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
  4070. !ffe_ctl->retry_uncached) {
  4071. ffe_ctl->retry_uncached = true;
  4072. btrfs_wait_block_group_cache_progress(block_group,
  4073. ffe_ctl->num_bytes +
  4074. ffe_ctl->empty_cluster +
  4075. ffe_ctl->empty_size);
  4076. goto have_block_group;
  4077. }
  4078. release_block_group(block_group, ffe_ctl, ffe_ctl->delalloc);
  4079. cond_resched();
  4080. }
  4081. up_read(&space_info->groups_sem);
  4082. ret = find_free_extent_update_loop(fs_info, ins, ffe_ctl, full_search);
  4083. if (ret > 0)
  4084. goto search;
  4085. if (ret == -ENOSPC && !cache_block_group_error) {
  4086. /*
  4087. * Use ffe_ctl->total_free_space as fallback if we can't find
  4088. * any contiguous hole.
  4089. */
  4090. if (!ffe_ctl->max_extent_size)
  4091. ffe_ctl->max_extent_size = ffe_ctl->total_free_space;
  4092. spin_lock(&space_info->lock);
  4093. space_info->max_extent_size = ffe_ctl->max_extent_size;
  4094. spin_unlock(&space_info->lock);
  4095. ins->offset = ffe_ctl->max_extent_size;
  4096. } else if (ret == -ENOSPC) {
  4097. ret = cache_block_group_error;
  4098. }
  4099. return ret;
  4100. }
  4101. /*
  4102. * Entry point to the extent allocator. Tries to find a hole that is at least
  4103. * as big as @num_bytes.
  4104. *
  4105. * @root - The root that will contain this extent
  4106. *
  4107. * @ram_bytes - The amount of space in ram that @num_bytes take. This
  4108. * is used for accounting purposes. This value differs
  4109. * from @num_bytes only in the case of compressed extents.
  4110. *
  4111. * @num_bytes - Number of bytes to allocate on-disk.
  4112. *
  4113. * @min_alloc_size - Indicates the minimum amount of space that the
  4114. * allocator should try to satisfy. In some cases
  4115. * @num_bytes may be larger than what is required and if
  4116. * the filesystem is fragmented then allocation fails.
  4117. * However, the presence of @min_alloc_size gives a
  4118. * chance to try and satisfy the smaller allocation.
  4119. *
  4120. * @empty_size - A hint that you plan on doing more COW. This is the
  4121. * size in bytes the allocator should try to find free
  4122. * next to the block it returns. This is just a hint and
  4123. * may be ignored by the allocator.
  4124. *
  4125. * @hint_byte - Hint to the allocator to start searching above the byte
  4126. * address passed. It might be ignored.
  4127. *
  4128. * @ins - This key is modified to record the found hole. It will
  4129. * have the following values:
  4130. * ins->objectid == start position
  4131. * ins->flags = BTRFS_EXTENT_ITEM_KEY
  4132. * ins->offset == the size of the hole.
  4133. *
  4134. * @is_data - Boolean flag indicating whether an extent is
  4135. * allocated for data (true) or metadata (false)
  4136. *
  4137. * @delalloc - Boolean flag indicating whether this allocation is for
  4138. * delalloc or not. If 'true' data_rwsem of block groups
  4139. * is going to be acquired.
  4140. *
  4141. *
  4142. * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
  4143. * case -ENOSPC is returned then @ins->offset will contain the size of the
  4144. * largest available hole the allocator managed to find.
  4145. */
  4146. int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
  4147. u64 num_bytes, u64 min_alloc_size,
  4148. u64 empty_size, u64 hint_byte,
  4149. struct btrfs_key *ins, int is_data, int delalloc)
  4150. {
  4151. struct btrfs_fs_info *fs_info = root->fs_info;
  4152. struct find_free_extent_ctl ffe_ctl = {};
  4153. bool final_tried = num_bytes == min_alloc_size;
  4154. u64 flags;
  4155. int ret;
  4156. bool for_treelog = (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID);
  4157. bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
  4158. flags = get_alloc_profile_by_root(root, is_data);
  4159. again:
  4160. WARN_ON(num_bytes < fs_info->sectorsize);
  4161. ffe_ctl.ram_bytes = ram_bytes;
  4162. ffe_ctl.num_bytes = num_bytes;
  4163. ffe_ctl.min_alloc_size = min_alloc_size;
  4164. ffe_ctl.empty_size = empty_size;
  4165. ffe_ctl.flags = flags;
  4166. ffe_ctl.delalloc = delalloc;
  4167. ffe_ctl.hint_byte = hint_byte;
  4168. ffe_ctl.for_treelog = for_treelog;
  4169. ffe_ctl.for_data_reloc = for_data_reloc;
  4170. ret = find_free_extent(root, ins, &ffe_ctl);
  4171. if (!ret && !is_data) {
  4172. btrfs_dec_block_group_reservations(fs_info, ins->objectid);
  4173. } else if (ret == -ENOSPC) {
  4174. if (!final_tried && ins->offset) {
  4175. num_bytes = min(num_bytes >> 1, ins->offset);
  4176. num_bytes = round_down(num_bytes,
  4177. fs_info->sectorsize);
  4178. num_bytes = max(num_bytes, min_alloc_size);
  4179. ram_bytes = num_bytes;
  4180. if (num_bytes == min_alloc_size)
  4181. final_tried = true;
  4182. goto again;
  4183. } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
  4184. struct btrfs_space_info *sinfo;
  4185. sinfo = btrfs_find_space_info(fs_info, flags);
  4186. btrfs_err(fs_info,
  4187. "allocation failed flags %llu, wanted %llu tree-log %d, relocation: %d",
  4188. flags, num_bytes, for_treelog, for_data_reloc);
  4189. if (sinfo)
  4190. btrfs_dump_space_info(fs_info, sinfo,
  4191. num_bytes, 1);
  4192. }
  4193. }
  4194. return ret;
  4195. }
  4196. int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
  4197. u64 start, u64 len, int delalloc)
  4198. {
  4199. struct btrfs_block_group *cache;
  4200. cache = btrfs_lookup_block_group(fs_info, start);
  4201. if (!cache) {
  4202. btrfs_err(fs_info, "Unable to find block group for %llu",
  4203. start);
  4204. return -ENOSPC;
  4205. }
  4206. btrfs_add_free_space(cache, start, len);
  4207. btrfs_free_reserved_bytes(cache, len, delalloc);
  4208. trace_btrfs_reserved_extent_free(fs_info, start, len);
  4209. btrfs_put_block_group(cache);
  4210. return 0;
  4211. }
  4212. int btrfs_pin_reserved_extent(struct btrfs_trans_handle *trans,
  4213. const struct extent_buffer *eb)
  4214. {
  4215. struct btrfs_block_group *cache;
  4216. int ret = 0;
  4217. cache = btrfs_lookup_block_group(trans->fs_info, eb->start);
  4218. if (!cache) {
  4219. btrfs_err(trans->fs_info, "unable to find block group for %llu",
  4220. eb->start);
  4221. return -ENOSPC;
  4222. }
  4223. ret = pin_down_extent(trans, cache, eb->start, eb->len, 1);
  4224. btrfs_put_block_group(cache);
  4225. return ret;
  4226. }
  4227. static int alloc_reserved_extent(struct btrfs_trans_handle *trans, u64 bytenr,
  4228. u64 num_bytes)
  4229. {
  4230. struct btrfs_fs_info *fs_info = trans->fs_info;
  4231. int ret;
  4232. ret = remove_from_free_space_tree(trans, bytenr, num_bytes);
  4233. if (ret)
  4234. return ret;
  4235. ret = btrfs_update_block_group(trans, bytenr, num_bytes, true);
  4236. if (ret) {
  4237. ASSERT(!ret);
  4238. btrfs_err(fs_info, "update block group failed for %llu %llu",
  4239. bytenr, num_bytes);
  4240. return ret;
  4241. }
  4242. trace_btrfs_reserved_extent_alloc(fs_info, bytenr, num_bytes);
  4243. return 0;
  4244. }
  4245. static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
  4246. u64 parent, u64 root_objectid,
  4247. u64 flags, u64 owner, u64 offset,
  4248. struct btrfs_key *ins, int ref_mod, u64 oref_root)
  4249. {
  4250. struct btrfs_fs_info *fs_info = trans->fs_info;
  4251. struct btrfs_root *extent_root;
  4252. int ret;
  4253. struct btrfs_extent_item *extent_item;
  4254. struct btrfs_extent_owner_ref *oref;
  4255. struct btrfs_extent_inline_ref *iref;
  4256. struct btrfs_path *path;
  4257. struct extent_buffer *leaf;
  4258. int type;
  4259. u32 size;
  4260. const bool simple_quota = (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE);
  4261. if (parent > 0)
  4262. type = BTRFS_SHARED_DATA_REF_KEY;
  4263. else
  4264. type = BTRFS_EXTENT_DATA_REF_KEY;
  4265. size = sizeof(*extent_item);
  4266. if (simple_quota)
  4267. size += btrfs_extent_inline_ref_size(BTRFS_EXTENT_OWNER_REF_KEY);
  4268. size += btrfs_extent_inline_ref_size(type);
  4269. path = btrfs_alloc_path();
  4270. if (!path)
  4271. return -ENOMEM;
  4272. extent_root = btrfs_extent_root(fs_info, ins->objectid);
  4273. ret = btrfs_insert_empty_item(trans, extent_root, path, ins, size);
  4274. if (ret) {
  4275. btrfs_free_path(path);
  4276. return ret;
  4277. }
  4278. leaf = path->nodes[0];
  4279. extent_item = btrfs_item_ptr(leaf, path->slots[0],
  4280. struct btrfs_extent_item);
  4281. btrfs_set_extent_refs(leaf, extent_item, ref_mod);
  4282. btrfs_set_extent_generation(leaf, extent_item, trans->transid);
  4283. btrfs_set_extent_flags(leaf, extent_item,
  4284. flags | BTRFS_EXTENT_FLAG_DATA);
  4285. iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
  4286. if (simple_quota) {
  4287. btrfs_set_extent_inline_ref_type(leaf, iref, BTRFS_EXTENT_OWNER_REF_KEY);
  4288. oref = (struct btrfs_extent_owner_ref *)(&iref->offset);
  4289. btrfs_set_extent_owner_ref_root_id(leaf, oref, oref_root);
  4290. iref = (struct btrfs_extent_inline_ref *)(oref + 1);
  4291. }
  4292. btrfs_set_extent_inline_ref_type(leaf, iref, type);
  4293. if (parent > 0) {
  4294. struct btrfs_shared_data_ref *ref;
  4295. ref = (struct btrfs_shared_data_ref *)(iref + 1);
  4296. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  4297. btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
  4298. } else {
  4299. struct btrfs_extent_data_ref *ref;
  4300. ref = (struct btrfs_extent_data_ref *)(&iref->offset);
  4301. btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
  4302. btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
  4303. btrfs_set_extent_data_ref_offset(leaf, ref, offset);
  4304. btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
  4305. }
  4306. btrfs_mark_buffer_dirty(trans, path->nodes[0]);
  4307. btrfs_free_path(path);
  4308. return alloc_reserved_extent(trans, ins->objectid, ins->offset);
  4309. }
  4310. static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
  4311. struct btrfs_delayed_ref_node *node,
  4312. struct btrfs_delayed_extent_op *extent_op)
  4313. {
  4314. struct btrfs_fs_info *fs_info = trans->fs_info;
  4315. struct btrfs_root *extent_root;
  4316. int ret;
  4317. struct btrfs_extent_item *extent_item;
  4318. struct btrfs_key extent_key;
  4319. struct btrfs_tree_block_info *block_info;
  4320. struct btrfs_extent_inline_ref *iref;
  4321. struct btrfs_path *path;
  4322. struct extent_buffer *leaf;
  4323. u32 size = sizeof(*extent_item) + sizeof(*iref);
  4324. const u64 flags = (extent_op ? extent_op->flags_to_set : 0);
  4325. /* The owner of a tree block is the level. */
  4326. int level = btrfs_delayed_ref_owner(node);
  4327. bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
  4328. extent_key.objectid = node->bytenr;
  4329. if (skinny_metadata) {
  4330. /* The owner of a tree block is the level. */
  4331. extent_key.offset = level;
  4332. extent_key.type = BTRFS_METADATA_ITEM_KEY;
  4333. } else {
  4334. extent_key.offset = node->num_bytes;
  4335. extent_key.type = BTRFS_EXTENT_ITEM_KEY;
  4336. size += sizeof(*block_info);
  4337. }
  4338. path = btrfs_alloc_path();
  4339. if (!path)
  4340. return -ENOMEM;
  4341. extent_root = btrfs_extent_root(fs_info, extent_key.objectid);
  4342. ret = btrfs_insert_empty_item(trans, extent_root, path, &extent_key,
  4343. size);
  4344. if (ret) {
  4345. btrfs_free_path(path);
  4346. return ret;
  4347. }
  4348. leaf = path->nodes[0];
  4349. extent_item = btrfs_item_ptr(leaf, path->slots[0],
  4350. struct btrfs_extent_item);
  4351. btrfs_set_extent_refs(leaf, extent_item, 1);
  4352. btrfs_set_extent_generation(leaf, extent_item, trans->transid);
  4353. btrfs_set_extent_flags(leaf, extent_item,
  4354. flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
  4355. if (skinny_metadata) {
  4356. iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
  4357. } else {
  4358. block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
  4359. btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
  4360. btrfs_set_tree_block_level(leaf, block_info, level);
  4361. iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
  4362. }
  4363. if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
  4364. btrfs_set_extent_inline_ref_type(leaf, iref,
  4365. BTRFS_SHARED_BLOCK_REF_KEY);
  4366. btrfs_set_extent_inline_ref_offset(leaf, iref, node->parent);
  4367. } else {
  4368. btrfs_set_extent_inline_ref_type(leaf, iref,
  4369. BTRFS_TREE_BLOCK_REF_KEY);
  4370. btrfs_set_extent_inline_ref_offset(leaf, iref, node->ref_root);
  4371. }
  4372. btrfs_mark_buffer_dirty(trans, leaf);
  4373. btrfs_free_path(path);
  4374. return alloc_reserved_extent(trans, node->bytenr, fs_info->nodesize);
  4375. }
  4376. int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
  4377. struct btrfs_root *root, u64 owner,
  4378. u64 offset, u64 ram_bytes,
  4379. struct btrfs_key *ins)
  4380. {
  4381. struct btrfs_ref generic_ref = {
  4382. .action = BTRFS_ADD_DELAYED_EXTENT,
  4383. .bytenr = ins->objectid,
  4384. .num_bytes = ins->offset,
  4385. .owning_root = btrfs_root_id(root),
  4386. .ref_root = btrfs_root_id(root),
  4387. };
  4388. ASSERT(generic_ref.ref_root != BTRFS_TREE_LOG_OBJECTID);
  4389. if (btrfs_is_data_reloc_root(root) && is_fstree(root->relocation_src_root))
  4390. generic_ref.owning_root = root->relocation_src_root;
  4391. btrfs_init_data_ref(&generic_ref, owner, offset, 0, false);
  4392. btrfs_ref_tree_mod(root->fs_info, &generic_ref);
  4393. return btrfs_add_delayed_data_ref(trans, &generic_ref, ram_bytes);
  4394. }
  4395. /*
  4396. * this is used by the tree logging recovery code. It records that
  4397. * an extent has been allocated and makes sure to clear the free
  4398. * space cache bits as well
  4399. */
  4400. int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
  4401. u64 root_objectid, u64 owner, u64 offset,
  4402. struct btrfs_key *ins)
  4403. {
  4404. struct btrfs_fs_info *fs_info = trans->fs_info;
  4405. int ret;
  4406. struct btrfs_block_group *block_group;
  4407. struct btrfs_space_info *space_info;
  4408. struct btrfs_squota_delta delta = {
  4409. .root = root_objectid,
  4410. .num_bytes = ins->offset,
  4411. .generation = trans->transid,
  4412. .is_data = true,
  4413. .is_inc = true,
  4414. };
  4415. /*
  4416. * Mixed block groups will exclude before processing the log so we only
  4417. * need to do the exclude dance if this fs isn't mixed.
  4418. */
  4419. if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
  4420. ret = __exclude_logged_extent(fs_info, ins->objectid,
  4421. ins->offset);
  4422. if (ret)
  4423. return ret;
  4424. }
  4425. block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
  4426. if (!block_group)
  4427. return -EINVAL;
  4428. space_info = block_group->space_info;
  4429. spin_lock(&space_info->lock);
  4430. spin_lock(&block_group->lock);
  4431. space_info->bytes_reserved += ins->offset;
  4432. block_group->reserved += ins->offset;
  4433. spin_unlock(&block_group->lock);
  4434. spin_unlock(&space_info->lock);
  4435. ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
  4436. offset, ins, 1, root_objectid);
  4437. if (ret)
  4438. btrfs_pin_extent(trans, ins->objectid, ins->offset, 1);
  4439. ret = btrfs_record_squota_delta(fs_info, &delta);
  4440. btrfs_put_block_group(block_group);
  4441. return ret;
  4442. }
  4443. #ifdef CONFIG_BTRFS_DEBUG
  4444. /*
  4445. * Extra safety check in case the extent tree is corrupted and extent allocator
  4446. * chooses to use a tree block which is already used and locked.
  4447. */
  4448. static bool check_eb_lock_owner(const struct extent_buffer *eb)
  4449. {
  4450. if (eb->lock_owner == current->pid) {
  4451. btrfs_err_rl(eb->fs_info,
  4452. "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
  4453. eb->start, btrfs_header_owner(eb), current->pid);
  4454. return true;
  4455. }
  4456. return false;
  4457. }
  4458. #else
  4459. static bool check_eb_lock_owner(struct extent_buffer *eb)
  4460. {
  4461. return false;
  4462. }
  4463. #endif
  4464. static struct extent_buffer *
  4465. btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  4466. u64 bytenr, int level, u64 owner,
  4467. enum btrfs_lock_nesting nest)
  4468. {
  4469. struct btrfs_fs_info *fs_info = root->fs_info;
  4470. struct extent_buffer *buf;
  4471. u64 lockdep_owner = owner;
  4472. buf = btrfs_find_create_tree_block(fs_info, bytenr, owner, level);
  4473. if (IS_ERR(buf))
  4474. return buf;
  4475. if (check_eb_lock_owner(buf)) {
  4476. free_extent_buffer(buf);
  4477. return ERR_PTR(-EUCLEAN);
  4478. }
  4479. /*
  4480. * The reloc trees are just snapshots, so we need them to appear to be
  4481. * just like any other fs tree WRT lockdep.
  4482. *
  4483. * The exception however is in replace_path() in relocation, where we
  4484. * hold the lock on the original fs root and then search for the reloc
  4485. * root. At that point we need to make sure any reloc root buffers are
  4486. * set to the BTRFS_TREE_RELOC_OBJECTID lockdep class in order to make
  4487. * lockdep happy.
  4488. */
  4489. if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID &&
  4490. !test_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &root->state))
  4491. lockdep_owner = BTRFS_FS_TREE_OBJECTID;
  4492. /* btrfs_clear_buffer_dirty() accesses generation field. */
  4493. btrfs_set_header_generation(buf, trans->transid);
  4494. /*
  4495. * This needs to stay, because we could allocate a freed block from an
  4496. * old tree into a new tree, so we need to make sure this new block is
  4497. * set to the appropriate level and owner.
  4498. */
  4499. btrfs_set_buffer_lockdep_class(lockdep_owner, buf, level);
  4500. btrfs_tree_lock_nested(buf, nest);
  4501. btrfs_clear_buffer_dirty(trans, buf);
  4502. clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
  4503. clear_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &buf->bflags);
  4504. set_extent_buffer_uptodate(buf);
  4505. memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
  4506. btrfs_set_header_level(buf, level);
  4507. btrfs_set_header_bytenr(buf, buf->start);
  4508. btrfs_set_header_generation(buf, trans->transid);
  4509. btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
  4510. btrfs_set_header_owner(buf, owner);
  4511. write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
  4512. write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
  4513. if (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID) {
  4514. buf->log_index = root->log_transid % 2;
  4515. /*
  4516. * we allow two log transactions at a time, use different
  4517. * EXTENT bit to differentiate dirty pages.
  4518. */
  4519. if (buf->log_index == 0)
  4520. set_extent_bit(&root->dirty_log_pages, buf->start,
  4521. buf->start + buf->len - 1,
  4522. EXTENT_DIRTY, NULL);
  4523. else
  4524. set_extent_bit(&root->dirty_log_pages, buf->start,
  4525. buf->start + buf->len - 1,
  4526. EXTENT_NEW, NULL);
  4527. } else {
  4528. buf->log_index = -1;
  4529. set_extent_bit(&trans->transaction->dirty_pages, buf->start,
  4530. buf->start + buf->len - 1, EXTENT_DIRTY, NULL);
  4531. }
  4532. /* this returns a buffer locked for blocking */
  4533. return buf;
  4534. }
  4535. /*
  4536. * finds a free extent and does all the dirty work required for allocation
  4537. * returns the tree buffer or an ERR_PTR on error.
  4538. */
  4539. struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
  4540. struct btrfs_root *root,
  4541. u64 parent, u64 root_objectid,
  4542. const struct btrfs_disk_key *key,
  4543. int level, u64 hint,
  4544. u64 empty_size,
  4545. u64 reloc_src_root,
  4546. enum btrfs_lock_nesting nest)
  4547. {
  4548. struct btrfs_fs_info *fs_info = root->fs_info;
  4549. struct btrfs_key ins;
  4550. struct btrfs_block_rsv *block_rsv;
  4551. struct extent_buffer *buf;
  4552. u64 flags = 0;
  4553. int ret;
  4554. u32 blocksize = fs_info->nodesize;
  4555. bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
  4556. u64 owning_root;
  4557. #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
  4558. if (btrfs_is_testing(fs_info)) {
  4559. buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
  4560. level, root_objectid, nest);
  4561. if (!IS_ERR(buf))
  4562. root->alloc_bytenr += blocksize;
  4563. return buf;
  4564. }
  4565. #endif
  4566. block_rsv = btrfs_use_block_rsv(trans, root, blocksize);
  4567. if (IS_ERR(block_rsv))
  4568. return ERR_CAST(block_rsv);
  4569. ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
  4570. empty_size, hint, &ins, 0, 0);
  4571. if (ret)
  4572. goto out_unuse;
  4573. buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
  4574. root_objectid, nest);
  4575. if (IS_ERR(buf)) {
  4576. ret = PTR_ERR(buf);
  4577. goto out_free_reserved;
  4578. }
  4579. owning_root = btrfs_header_owner(buf);
  4580. if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
  4581. if (parent == 0)
  4582. parent = ins.objectid;
  4583. flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
  4584. owning_root = reloc_src_root;
  4585. } else
  4586. BUG_ON(parent > 0);
  4587. if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
  4588. struct btrfs_delayed_extent_op *extent_op;
  4589. struct btrfs_ref generic_ref = {
  4590. .action = BTRFS_ADD_DELAYED_EXTENT,
  4591. .bytenr = ins.objectid,
  4592. .num_bytes = ins.offset,
  4593. .parent = parent,
  4594. .owning_root = owning_root,
  4595. .ref_root = root_objectid,
  4596. };
  4597. if (!skinny_metadata || flags != 0) {
  4598. extent_op = btrfs_alloc_delayed_extent_op();
  4599. if (!extent_op) {
  4600. ret = -ENOMEM;
  4601. goto out_free_buf;
  4602. }
  4603. if (key)
  4604. memcpy(&extent_op->key, key, sizeof(extent_op->key));
  4605. else
  4606. memset(&extent_op->key, 0, sizeof(extent_op->key));
  4607. extent_op->flags_to_set = flags;
  4608. extent_op->update_key = (skinny_metadata ? false : true);
  4609. extent_op->update_flags = (flags != 0);
  4610. } else {
  4611. extent_op = NULL;
  4612. }
  4613. btrfs_init_tree_ref(&generic_ref, level, btrfs_root_id(root), false);
  4614. btrfs_ref_tree_mod(fs_info, &generic_ref);
  4615. ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, extent_op);
  4616. if (ret) {
  4617. btrfs_free_delayed_extent_op(extent_op);
  4618. goto out_free_buf;
  4619. }
  4620. }
  4621. return buf;
  4622. out_free_buf:
  4623. btrfs_tree_unlock(buf);
  4624. free_extent_buffer(buf);
  4625. out_free_reserved:
  4626. btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
  4627. out_unuse:
  4628. btrfs_unuse_block_rsv(fs_info, block_rsv, blocksize);
  4629. return ERR_PTR(ret);
  4630. }
  4631. struct walk_control {
  4632. u64 refs[BTRFS_MAX_LEVEL];
  4633. u64 flags[BTRFS_MAX_LEVEL];
  4634. struct btrfs_key update_progress;
  4635. struct btrfs_key drop_progress;
  4636. int drop_level;
  4637. int stage;
  4638. int level;
  4639. int shared_level;
  4640. int update_ref;
  4641. int keep_locks;
  4642. int reada_slot;
  4643. int reada_count;
  4644. int restarted;
  4645. /* Indicate that extent info needs to be looked up when walking the tree. */
  4646. int lookup_info;
  4647. };
  4648. /*
  4649. * This is our normal stage. We are traversing blocks the current snapshot owns
  4650. * and we are dropping any of our references to any children we are able to, and
  4651. * then freeing the block once we've processed all of the children.
  4652. */
  4653. #define DROP_REFERENCE 1
  4654. /*
  4655. * We enter this stage when we have to walk into a child block (meaning we can't
  4656. * simply drop our reference to it from our current parent node) and there are
  4657. * more than one reference on it. If we are the owner of any of the children
  4658. * blocks from the current parent node then we have to do the FULL_BACKREF dance
  4659. * on them in order to drop our normal ref and add the shared ref.
  4660. */
  4661. #define UPDATE_BACKREF 2
  4662. /*
  4663. * Decide if we need to walk down into this node to adjust the references.
  4664. *
  4665. * @root: the root we are currently deleting
  4666. * @wc: the walk control for this deletion
  4667. * @eb: the parent eb that we're currently visiting
  4668. * @refs: the number of refs for wc->level - 1
  4669. * @flags: the flags for wc->level - 1
  4670. * @slot: the slot in the eb that we're currently checking
  4671. *
  4672. * This is meant to be called when we're evaluating if a node we point to at
  4673. * wc->level should be read and walked into, or if we can simply delete our
  4674. * reference to it. We return true if we should walk into the node, false if we
  4675. * can skip it.
  4676. *
  4677. * We have assertions in here to make sure this is called correctly. We assume
  4678. * that sanity checking on the blocks read to this point has been done, so any
  4679. * corrupted file systems must have been caught before calling this function.
  4680. */
  4681. static bool visit_node_for_delete(struct btrfs_root *root, struct walk_control *wc,
  4682. struct extent_buffer *eb, u64 refs, u64 flags, int slot)
  4683. {
  4684. struct btrfs_key key;
  4685. u64 generation;
  4686. int level = wc->level;
  4687. ASSERT(level > 0);
  4688. ASSERT(wc->refs[level - 1] > 0);
  4689. /*
  4690. * The update backref stage we only want to skip if we already have
  4691. * FULL_BACKREF set, otherwise we need to read.
  4692. */
  4693. if (wc->stage == UPDATE_BACKREF) {
  4694. if (level == 1 && flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  4695. return false;
  4696. return true;
  4697. }
  4698. /*
  4699. * We're the last ref on this block, we must walk into it and process
  4700. * any refs it's pointing at.
  4701. */
  4702. if (wc->refs[level - 1] == 1)
  4703. return true;
  4704. /*
  4705. * If we're already FULL_BACKREF then we know we can just drop our
  4706. * current reference.
  4707. */
  4708. if (level == 1 && flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  4709. return false;
  4710. /*
  4711. * This block is older than our creation generation, we can drop our
  4712. * reference to it.
  4713. */
  4714. generation = btrfs_node_ptr_generation(eb, slot);
  4715. if (!wc->update_ref || generation <= btrfs_root_origin_generation(root))
  4716. return false;
  4717. /*
  4718. * This block was processed from a previous snapshot deletion run, we
  4719. * can skip it.
  4720. */
  4721. btrfs_node_key_to_cpu(eb, &key, slot);
  4722. if (btrfs_comp_cpu_keys(&key, &wc->update_progress) < 0)
  4723. return false;
  4724. /* All other cases we need to wander into the node. */
  4725. return true;
  4726. }
  4727. static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
  4728. struct btrfs_root *root,
  4729. struct walk_control *wc,
  4730. struct btrfs_path *path)
  4731. {
  4732. struct btrfs_fs_info *fs_info = root->fs_info;
  4733. u64 bytenr;
  4734. u64 generation;
  4735. u64 refs;
  4736. u64 flags;
  4737. u32 nritems;
  4738. struct extent_buffer *eb;
  4739. int ret;
  4740. int slot;
  4741. int nread = 0;
  4742. if (path->slots[wc->level] < wc->reada_slot) {
  4743. wc->reada_count = wc->reada_count * 2 / 3;
  4744. wc->reada_count = max(wc->reada_count, 2);
  4745. } else {
  4746. wc->reada_count = wc->reada_count * 3 / 2;
  4747. wc->reada_count = min_t(int, wc->reada_count,
  4748. BTRFS_NODEPTRS_PER_BLOCK(fs_info));
  4749. }
  4750. eb = path->nodes[wc->level];
  4751. nritems = btrfs_header_nritems(eb);
  4752. for (slot = path->slots[wc->level]; slot < nritems; slot++) {
  4753. if (nread >= wc->reada_count)
  4754. break;
  4755. cond_resched();
  4756. bytenr = btrfs_node_blockptr(eb, slot);
  4757. generation = btrfs_node_ptr_generation(eb, slot);
  4758. if (slot == path->slots[wc->level])
  4759. goto reada;
  4760. if (wc->stage == UPDATE_BACKREF &&
  4761. generation <= btrfs_root_origin_generation(root))
  4762. continue;
  4763. /* We don't lock the tree block, it's OK to be racy here */
  4764. ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
  4765. wc->level - 1, 1, &refs,
  4766. &flags, NULL);
  4767. /* We don't care about errors in readahead. */
  4768. if (ret < 0)
  4769. continue;
  4770. /*
  4771. * This could be racey, it's conceivable that we raced and end
  4772. * up with a bogus refs count, if that's the case just skip, if
  4773. * we are actually corrupt we will notice when we look up
  4774. * everything again with our locks.
  4775. */
  4776. if (refs == 0)
  4777. continue;
  4778. /* If we don't need to visit this node don't reada. */
  4779. if (!visit_node_for_delete(root, wc, eb, refs, flags, slot))
  4780. continue;
  4781. reada:
  4782. btrfs_readahead_node_child(eb, slot);
  4783. nread++;
  4784. }
  4785. wc->reada_slot = slot;
  4786. }
  4787. /*
  4788. * helper to process tree block while walking down the tree.
  4789. *
  4790. * when wc->stage == UPDATE_BACKREF, this function updates
  4791. * back refs for pointers in the block.
  4792. *
  4793. * NOTE: return value 1 means we should stop walking down.
  4794. */
  4795. static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
  4796. struct btrfs_root *root,
  4797. struct btrfs_path *path,
  4798. struct walk_control *wc)
  4799. {
  4800. struct btrfs_fs_info *fs_info = root->fs_info;
  4801. int level = wc->level;
  4802. struct extent_buffer *eb = path->nodes[level];
  4803. u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  4804. int ret;
  4805. if (wc->stage == UPDATE_BACKREF && btrfs_header_owner(eb) != btrfs_root_id(root))
  4806. return 1;
  4807. /*
  4808. * when reference count of tree block is 1, it won't increase
  4809. * again. once full backref flag is set, we never clear it.
  4810. */
  4811. if (wc->lookup_info &&
  4812. ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
  4813. (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
  4814. ASSERT(path->locks[level]);
  4815. ret = btrfs_lookup_extent_info(trans, fs_info,
  4816. eb->start, level, 1,
  4817. &wc->refs[level],
  4818. &wc->flags[level],
  4819. NULL);
  4820. if (ret)
  4821. return ret;
  4822. if (unlikely(wc->refs[level] == 0)) {
  4823. btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0",
  4824. eb->start);
  4825. return -EUCLEAN;
  4826. }
  4827. }
  4828. if (wc->stage == DROP_REFERENCE) {
  4829. if (wc->refs[level] > 1)
  4830. return 1;
  4831. if (path->locks[level] && !wc->keep_locks) {
  4832. btrfs_tree_unlock_rw(eb, path->locks[level]);
  4833. path->locks[level] = 0;
  4834. }
  4835. return 0;
  4836. }
  4837. /* wc->stage == UPDATE_BACKREF */
  4838. if (!(wc->flags[level] & flag)) {
  4839. ASSERT(path->locks[level]);
  4840. ret = btrfs_inc_ref(trans, root, eb, 1);
  4841. if (ret) {
  4842. btrfs_abort_transaction(trans, ret);
  4843. return ret;
  4844. }
  4845. ret = btrfs_dec_ref(trans, root, eb, 0);
  4846. if (ret) {
  4847. btrfs_abort_transaction(trans, ret);
  4848. return ret;
  4849. }
  4850. ret = btrfs_set_disk_extent_flags(trans, eb, flag);
  4851. if (ret) {
  4852. btrfs_abort_transaction(trans, ret);
  4853. return ret;
  4854. }
  4855. wc->flags[level] |= flag;
  4856. }
  4857. /*
  4858. * the block is shared by multiple trees, so it's not good to
  4859. * keep the tree lock
  4860. */
  4861. if (path->locks[level] && level > 0) {
  4862. btrfs_tree_unlock_rw(eb, path->locks[level]);
  4863. path->locks[level] = 0;
  4864. }
  4865. return 0;
  4866. }
  4867. /*
  4868. * This is used to verify a ref exists for this root to deal with a bug where we
  4869. * would have a drop_progress key that hadn't been updated properly.
  4870. */
  4871. static int check_ref_exists(struct btrfs_trans_handle *trans,
  4872. struct btrfs_root *root, u64 bytenr, u64 parent,
  4873. int level)
  4874. {
  4875. struct btrfs_delayed_ref_root *delayed_refs;
  4876. struct btrfs_delayed_ref_head *head;
  4877. struct btrfs_path *path;
  4878. struct btrfs_extent_inline_ref *iref;
  4879. int ret;
  4880. bool exists = false;
  4881. path = btrfs_alloc_path();
  4882. if (!path)
  4883. return -ENOMEM;
  4884. again:
  4885. ret = lookup_extent_backref(trans, path, &iref, bytenr,
  4886. root->fs_info->nodesize, parent,
  4887. btrfs_root_id(root), level, 0);
  4888. if (ret != -ENOENT) {
  4889. /*
  4890. * If we get 0 then we found our reference, return 1, else
  4891. * return the error if it's not -ENOENT;
  4892. */
  4893. btrfs_free_path(path);
  4894. return (ret < 0 ) ? ret : 1;
  4895. }
  4896. /*
  4897. * We could have a delayed ref with this reference, so look it up while
  4898. * we're holding the path open to make sure we don't race with the
  4899. * delayed ref running.
  4900. */
  4901. delayed_refs = &trans->transaction->delayed_refs;
  4902. spin_lock(&delayed_refs->lock);
  4903. head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
  4904. if (!head)
  4905. goto out;
  4906. if (!mutex_trylock(&head->mutex)) {
  4907. /*
  4908. * We're contended, means that the delayed ref is running, get a
  4909. * reference and wait for the ref head to be complete and then
  4910. * try again.
  4911. */
  4912. refcount_inc(&head->refs);
  4913. spin_unlock(&delayed_refs->lock);
  4914. btrfs_release_path(path);
  4915. mutex_lock(&head->mutex);
  4916. mutex_unlock(&head->mutex);
  4917. btrfs_put_delayed_ref_head(head);
  4918. goto again;
  4919. }
  4920. exists = btrfs_find_delayed_tree_ref(head, root->root_key.objectid, parent);
  4921. mutex_unlock(&head->mutex);
  4922. out:
  4923. spin_unlock(&delayed_refs->lock);
  4924. btrfs_free_path(path);
  4925. return exists ? 1 : 0;
  4926. }
  4927. /*
  4928. * We may not have an uptodate block, so if we are going to walk down into this
  4929. * block we need to drop the lock, read it off of the disk, re-lock it and
  4930. * return to continue dropping the snapshot.
  4931. */
  4932. static int check_next_block_uptodate(struct btrfs_trans_handle *trans,
  4933. struct btrfs_root *root,
  4934. struct btrfs_path *path,
  4935. struct walk_control *wc,
  4936. struct extent_buffer *next)
  4937. {
  4938. struct btrfs_tree_parent_check check = { 0 };
  4939. u64 generation;
  4940. int level = wc->level;
  4941. int ret;
  4942. btrfs_assert_tree_write_locked(next);
  4943. generation = btrfs_node_ptr_generation(path->nodes[level], path->slots[level]);
  4944. if (btrfs_buffer_uptodate(next, generation, 0))
  4945. return 0;
  4946. check.level = level - 1;
  4947. check.transid = generation;
  4948. check.owner_root = btrfs_root_id(root);
  4949. check.has_first_key = true;
  4950. btrfs_node_key_to_cpu(path->nodes[level], &check.first_key, path->slots[level]);
  4951. btrfs_tree_unlock(next);
  4952. if (level == 1)
  4953. reada_walk_down(trans, root, wc, path);
  4954. ret = btrfs_read_extent_buffer(next, &check);
  4955. if (ret) {
  4956. free_extent_buffer(next);
  4957. return ret;
  4958. }
  4959. btrfs_tree_lock(next);
  4960. wc->lookup_info = 1;
  4961. return 0;
  4962. }
  4963. /*
  4964. * If we determine that we don't have to visit wc->level - 1 then we need to
  4965. * determine if we can drop our reference.
  4966. *
  4967. * If we are UPDATE_BACKREF then we will not, we need to update our backrefs.
  4968. *
  4969. * If we are DROP_REFERENCE this will figure out if we need to drop our current
  4970. * reference, skipping it if we dropped it from a previous incompleted drop, or
  4971. * dropping it if we still have a reference to it.
  4972. */
  4973. static int maybe_drop_reference(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  4974. struct btrfs_path *path, struct walk_control *wc,
  4975. struct extent_buffer *next, u64 owner_root)
  4976. {
  4977. struct btrfs_ref ref = {
  4978. .action = BTRFS_DROP_DELAYED_REF,
  4979. .bytenr = next->start,
  4980. .num_bytes = root->fs_info->nodesize,
  4981. .owning_root = owner_root,
  4982. .ref_root = btrfs_root_id(root),
  4983. };
  4984. int level = wc->level;
  4985. int ret;
  4986. /* We are UPDATE_BACKREF, we're not dropping anything. */
  4987. if (wc->stage == UPDATE_BACKREF)
  4988. return 0;
  4989. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
  4990. ref.parent = path->nodes[level]->start;
  4991. } else {
  4992. ASSERT(btrfs_root_id(root) == btrfs_header_owner(path->nodes[level]));
  4993. if (btrfs_root_id(root) != btrfs_header_owner(path->nodes[level])) {
  4994. btrfs_err(root->fs_info, "mismatched block owner");
  4995. return -EIO;
  4996. }
  4997. }
  4998. /*
  4999. * If we had a drop_progress we need to verify the refs are set as
  5000. * expected. If we find our ref then we know that from here on out
  5001. * everything should be correct, and we can clear the
  5002. * ->restarted flag.
  5003. */
  5004. if (wc->restarted) {
  5005. ret = check_ref_exists(trans, root, next->start, ref.parent,
  5006. level - 1);
  5007. if (ret <= 0)
  5008. return ret;
  5009. ret = 0;
  5010. wc->restarted = 0;
  5011. }
  5012. /*
  5013. * Reloc tree doesn't contribute to qgroup numbers, and we have already
  5014. * accounted them at merge time (replace_path), thus we could skip
  5015. * expensive subtree trace here.
  5016. */
  5017. if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID &&
  5018. wc->refs[level - 1] > 1) {
  5019. u64 generation = btrfs_node_ptr_generation(path->nodes[level],
  5020. path->slots[level]);
  5021. ret = btrfs_qgroup_trace_subtree(trans, next, generation, level - 1);
  5022. if (ret) {
  5023. btrfs_err_rl(root->fs_info,
  5024. "error %d accounting shared subtree, quota is out of sync, rescan required",
  5025. ret);
  5026. }
  5027. }
  5028. /*
  5029. * We need to update the next key in our walk control so we can update
  5030. * the drop_progress key accordingly. We don't care if find_next_key
  5031. * doesn't find a key because that means we're at the end and are going
  5032. * to clean up now.
  5033. */
  5034. wc->drop_level = level;
  5035. find_next_key(path, level, &wc->drop_progress);
  5036. btrfs_init_tree_ref(&ref, level - 1, 0, false);
  5037. return btrfs_free_extent(trans, &ref);
  5038. }
  5039. /*
  5040. * helper to process tree block pointer.
  5041. *
  5042. * when wc->stage == DROP_REFERENCE, this function checks
  5043. * reference count of the block pointed to. if the block
  5044. * is shared and we need update back refs for the subtree
  5045. * rooted at the block, this function changes wc->stage to
  5046. * UPDATE_BACKREF. if the block is shared and there is no
  5047. * need to update back, this function drops the reference
  5048. * to the block.
  5049. *
  5050. * NOTE: return value 1 means we should stop walking down.
  5051. */
  5052. static noinline int do_walk_down(struct btrfs_trans_handle *trans,
  5053. struct btrfs_root *root,
  5054. struct btrfs_path *path,
  5055. struct walk_control *wc)
  5056. {
  5057. struct btrfs_fs_info *fs_info = root->fs_info;
  5058. u64 bytenr;
  5059. u64 generation;
  5060. u64 owner_root = 0;
  5061. struct extent_buffer *next;
  5062. int level = wc->level;
  5063. int ret = 0;
  5064. generation = btrfs_node_ptr_generation(path->nodes[level],
  5065. path->slots[level]);
  5066. /*
  5067. * if the lower level block was created before the snapshot
  5068. * was created, we know there is no need to update back refs
  5069. * for the subtree
  5070. */
  5071. if (wc->stage == UPDATE_BACKREF &&
  5072. generation <= btrfs_root_origin_generation(root)) {
  5073. wc->lookup_info = 1;
  5074. return 1;
  5075. }
  5076. bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
  5077. next = btrfs_find_create_tree_block(fs_info, bytenr, btrfs_root_id(root),
  5078. level - 1);
  5079. if (IS_ERR(next))
  5080. return PTR_ERR(next);
  5081. btrfs_tree_lock(next);
  5082. ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
  5083. &wc->refs[level - 1],
  5084. &wc->flags[level - 1],
  5085. &owner_root);
  5086. if (ret < 0)
  5087. goto out_unlock;
  5088. if (unlikely(wc->refs[level - 1] == 0)) {
  5089. btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0",
  5090. bytenr);
  5091. ret = -EUCLEAN;
  5092. goto out_unlock;
  5093. }
  5094. wc->lookup_info = 0;
  5095. /* If we don't have to walk into this node skip it. */
  5096. if (!visit_node_for_delete(root, wc, path->nodes[level],
  5097. wc->refs[level - 1], wc->flags[level - 1],
  5098. path->slots[level]))
  5099. goto skip;
  5100. /*
  5101. * We have to walk down into this node, and if we're currently at the
  5102. * DROP_REFERNCE stage and this block is shared then we need to switch
  5103. * to the UPDATE_BACKREF stage in order to convert to FULL_BACKREF.
  5104. */
  5105. if (wc->stage == DROP_REFERENCE && wc->refs[level - 1] > 1) {
  5106. wc->stage = UPDATE_BACKREF;
  5107. wc->shared_level = level - 1;
  5108. }
  5109. ret = check_next_block_uptodate(trans, root, path, wc, next);
  5110. if (ret)
  5111. return ret;
  5112. level--;
  5113. ASSERT(level == btrfs_header_level(next));
  5114. if (level != btrfs_header_level(next)) {
  5115. btrfs_err(root->fs_info, "mismatched level");
  5116. ret = -EIO;
  5117. goto out_unlock;
  5118. }
  5119. path->nodes[level] = next;
  5120. path->slots[level] = 0;
  5121. path->locks[level] = BTRFS_WRITE_LOCK;
  5122. wc->level = level;
  5123. if (wc->level == 1)
  5124. wc->reada_slot = 0;
  5125. return 0;
  5126. skip:
  5127. ret = maybe_drop_reference(trans, root, path, wc, next, owner_root);
  5128. if (ret)
  5129. goto out_unlock;
  5130. wc->refs[level - 1] = 0;
  5131. wc->flags[level - 1] = 0;
  5132. wc->lookup_info = 1;
  5133. ret = 1;
  5134. out_unlock:
  5135. btrfs_tree_unlock(next);
  5136. free_extent_buffer(next);
  5137. return ret;
  5138. }
  5139. /*
  5140. * helper to process tree block while walking up the tree.
  5141. *
  5142. * when wc->stage == DROP_REFERENCE, this function drops
  5143. * reference count on the block.
  5144. *
  5145. * when wc->stage == UPDATE_BACKREF, this function changes
  5146. * wc->stage back to DROP_REFERENCE if we changed wc->stage
  5147. * to UPDATE_BACKREF previously while processing the block.
  5148. *
  5149. * NOTE: return value 1 means we should stop walking up.
  5150. */
  5151. static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
  5152. struct btrfs_root *root,
  5153. struct btrfs_path *path,
  5154. struct walk_control *wc)
  5155. {
  5156. struct btrfs_fs_info *fs_info = root->fs_info;
  5157. int ret = 0;
  5158. int level = wc->level;
  5159. struct extent_buffer *eb = path->nodes[level];
  5160. u64 parent = 0;
  5161. if (wc->stage == UPDATE_BACKREF) {
  5162. ASSERT(wc->shared_level >= level);
  5163. if (level < wc->shared_level)
  5164. goto out;
  5165. ret = find_next_key(path, level + 1, &wc->update_progress);
  5166. if (ret > 0)
  5167. wc->update_ref = 0;
  5168. wc->stage = DROP_REFERENCE;
  5169. wc->shared_level = -1;
  5170. path->slots[level] = 0;
  5171. /*
  5172. * check reference count again if the block isn't locked.
  5173. * we should start walking down the tree again if reference
  5174. * count is one.
  5175. */
  5176. if (!path->locks[level]) {
  5177. ASSERT(level > 0);
  5178. btrfs_tree_lock(eb);
  5179. path->locks[level] = BTRFS_WRITE_LOCK;
  5180. ret = btrfs_lookup_extent_info(trans, fs_info,
  5181. eb->start, level, 1,
  5182. &wc->refs[level],
  5183. &wc->flags[level],
  5184. NULL);
  5185. if (ret < 0) {
  5186. btrfs_tree_unlock_rw(eb, path->locks[level]);
  5187. path->locks[level] = 0;
  5188. return ret;
  5189. }
  5190. if (unlikely(wc->refs[level] == 0)) {
  5191. btrfs_tree_unlock_rw(eb, path->locks[level]);
  5192. btrfs_err(fs_info, "bytenr %llu has 0 references, expect > 0",
  5193. eb->start);
  5194. return -EUCLEAN;
  5195. }
  5196. if (wc->refs[level] == 1) {
  5197. btrfs_tree_unlock_rw(eb, path->locks[level]);
  5198. path->locks[level] = 0;
  5199. return 1;
  5200. }
  5201. }
  5202. }
  5203. /* wc->stage == DROP_REFERENCE */
  5204. ASSERT(path->locks[level] || wc->refs[level] == 1);
  5205. if (wc->refs[level] == 1) {
  5206. if (level == 0) {
  5207. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  5208. ret = btrfs_dec_ref(trans, root, eb, 1);
  5209. else
  5210. ret = btrfs_dec_ref(trans, root, eb, 0);
  5211. if (ret) {
  5212. btrfs_abort_transaction(trans, ret);
  5213. return ret;
  5214. }
  5215. if (is_fstree(btrfs_root_id(root))) {
  5216. ret = btrfs_qgroup_trace_leaf_items(trans, eb);
  5217. if (ret) {
  5218. btrfs_err_rl(fs_info,
  5219. "error %d accounting leaf items, quota is out of sync, rescan required",
  5220. ret);
  5221. }
  5222. }
  5223. }
  5224. /* Make block locked assertion in btrfs_clear_buffer_dirty happy. */
  5225. if (!path->locks[level]) {
  5226. btrfs_tree_lock(eb);
  5227. path->locks[level] = BTRFS_WRITE_LOCK;
  5228. }
  5229. btrfs_clear_buffer_dirty(trans, eb);
  5230. }
  5231. if (eb == root->node) {
  5232. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  5233. parent = eb->start;
  5234. else if (btrfs_root_id(root) != btrfs_header_owner(eb))
  5235. goto owner_mismatch;
  5236. } else {
  5237. if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  5238. parent = path->nodes[level + 1]->start;
  5239. else if (btrfs_root_id(root) !=
  5240. btrfs_header_owner(path->nodes[level + 1]))
  5241. goto owner_mismatch;
  5242. }
  5243. ret = btrfs_free_tree_block(trans, btrfs_root_id(root), eb, parent,
  5244. wc->refs[level] == 1);
  5245. if (ret < 0)
  5246. btrfs_abort_transaction(trans, ret);
  5247. out:
  5248. wc->refs[level] = 0;
  5249. wc->flags[level] = 0;
  5250. return ret;
  5251. owner_mismatch:
  5252. btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
  5253. btrfs_header_owner(eb), btrfs_root_id(root));
  5254. return -EUCLEAN;
  5255. }
  5256. /*
  5257. * walk_down_tree consists of two steps.
  5258. *
  5259. * walk_down_proc(). Look up the reference count and reference of our current
  5260. * wc->level. At this point path->nodes[wc->level] should be populated and
  5261. * uptodate, and in most cases should already be locked. If we are in
  5262. * DROP_REFERENCE and our refcount is > 1 then we've entered a shared node and
  5263. * we can walk back up the tree. If we are UPDATE_BACKREF we have to set
  5264. * FULL_BACKREF on this node if it's not already set, and then do the
  5265. * FULL_BACKREF conversion dance, which is to drop the root reference and add
  5266. * the shared reference to all of this nodes children.
  5267. *
  5268. * do_walk_down(). This is where we actually start iterating on the children of
  5269. * our current path->nodes[wc->level]. For DROP_REFERENCE that means dropping
  5270. * our reference to the children that return false from visit_node_for_delete(),
  5271. * which has various conditions where we know we can just drop our reference
  5272. * without visiting the node. For UPDATE_BACKREF we will skip any children that
  5273. * visit_node_for_delete() returns false for, only walking down when necessary.
  5274. * The bulk of the work for UPDATE_BACKREF occurs in the walk_up_tree() part of
  5275. * snapshot deletion.
  5276. */
  5277. static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
  5278. struct btrfs_root *root,
  5279. struct btrfs_path *path,
  5280. struct walk_control *wc)
  5281. {
  5282. int level = wc->level;
  5283. int ret = 0;
  5284. wc->lookup_info = 1;
  5285. while (level >= 0) {
  5286. ret = walk_down_proc(trans, root, path, wc);
  5287. if (ret)
  5288. break;
  5289. if (level == 0)
  5290. break;
  5291. if (path->slots[level] >=
  5292. btrfs_header_nritems(path->nodes[level]))
  5293. break;
  5294. ret = do_walk_down(trans, root, path, wc);
  5295. if (ret > 0) {
  5296. path->slots[level]++;
  5297. continue;
  5298. } else if (ret < 0)
  5299. break;
  5300. level = wc->level;
  5301. }
  5302. return (ret == 1) ? 0 : ret;
  5303. }
  5304. /*
  5305. * walk_up_tree() is responsible for making sure we visit every slot on our
  5306. * current node, and if we're at the end of that node then we call
  5307. * walk_up_proc() on our current node which will do one of a few things based on
  5308. * our stage.
  5309. *
  5310. * UPDATE_BACKREF. If we wc->level is currently less than our wc->shared_level
  5311. * then we need to walk back up the tree, and then going back down into the
  5312. * other slots via walk_down_tree to update any other children from our original
  5313. * wc->shared_level. Once we're at or above our wc->shared_level we can switch
  5314. * back to DROP_REFERENCE, lookup the current nodes refs and flags, and carry on.
  5315. *
  5316. * DROP_REFERENCE. If our refs == 1 then we're going to free this tree block.
  5317. * If we're level 0 then we need to btrfs_dec_ref() on all of the data extents
  5318. * in our current leaf. After that we call btrfs_free_tree_block() on the
  5319. * current node and walk up to the next node to walk down the next slot.
  5320. */
  5321. static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
  5322. struct btrfs_root *root,
  5323. struct btrfs_path *path,
  5324. struct walk_control *wc, int max_level)
  5325. {
  5326. int level = wc->level;
  5327. int ret;
  5328. path->slots[level] = btrfs_header_nritems(path->nodes[level]);
  5329. while (level < max_level && path->nodes[level]) {
  5330. wc->level = level;
  5331. if (path->slots[level] + 1 <
  5332. btrfs_header_nritems(path->nodes[level])) {
  5333. path->slots[level]++;
  5334. return 0;
  5335. } else {
  5336. ret = walk_up_proc(trans, root, path, wc);
  5337. if (ret > 0)
  5338. return 0;
  5339. if (ret < 0)
  5340. return ret;
  5341. if (path->locks[level]) {
  5342. btrfs_tree_unlock_rw(path->nodes[level],
  5343. path->locks[level]);
  5344. path->locks[level] = 0;
  5345. }
  5346. free_extent_buffer(path->nodes[level]);
  5347. path->nodes[level] = NULL;
  5348. level++;
  5349. }
  5350. }
  5351. return 1;
  5352. }
  5353. /*
  5354. * drop a subvolume tree.
  5355. *
  5356. * this function traverses the tree freeing any blocks that only
  5357. * referenced by the tree.
  5358. *
  5359. * when a shared tree block is found. this function decreases its
  5360. * reference count by one. if update_ref is true, this function
  5361. * also make sure backrefs for the shared block and all lower level
  5362. * blocks are properly updated.
  5363. *
  5364. * If called with for_reloc == 0, may exit early with -EAGAIN
  5365. */
  5366. int btrfs_drop_snapshot(struct btrfs_root *root, int update_ref, int for_reloc)
  5367. {
  5368. const bool is_reloc_root = (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID);
  5369. struct btrfs_fs_info *fs_info = root->fs_info;
  5370. struct btrfs_path *path;
  5371. struct btrfs_trans_handle *trans;
  5372. struct btrfs_root *tree_root = fs_info->tree_root;
  5373. struct btrfs_root_item *root_item = &root->root_item;
  5374. struct walk_control *wc;
  5375. struct btrfs_key key;
  5376. const u64 rootid = btrfs_root_id(root);
  5377. int ret = 0;
  5378. int level;
  5379. bool root_dropped = false;
  5380. bool unfinished_drop = false;
  5381. btrfs_debug(fs_info, "Drop subvolume %llu", btrfs_root_id(root));
  5382. path = btrfs_alloc_path();
  5383. if (!path) {
  5384. ret = -ENOMEM;
  5385. goto out;
  5386. }
  5387. wc = kzalloc(sizeof(*wc), GFP_NOFS);
  5388. if (!wc) {
  5389. btrfs_free_path(path);
  5390. ret = -ENOMEM;
  5391. goto out;
  5392. }
  5393. /*
  5394. * Use join to avoid potential EINTR from transaction start. See
  5395. * wait_reserve_ticket and the whole reservation callchain.
  5396. */
  5397. if (for_reloc)
  5398. trans = btrfs_join_transaction(tree_root);
  5399. else
  5400. trans = btrfs_start_transaction(tree_root, 0);
  5401. if (IS_ERR(trans)) {
  5402. ret = PTR_ERR(trans);
  5403. goto out_free;
  5404. }
  5405. ret = btrfs_run_delayed_items(trans);
  5406. if (ret)
  5407. goto out_end_trans;
  5408. /*
  5409. * This will help us catch people modifying the fs tree while we're
  5410. * dropping it. It is unsafe to mess with the fs tree while it's being
  5411. * dropped as we unlock the root node and parent nodes as we walk down
  5412. * the tree, assuming nothing will change. If something does change
  5413. * then we'll have stale information and drop references to blocks we've
  5414. * already dropped.
  5415. */
  5416. set_bit(BTRFS_ROOT_DELETING, &root->state);
  5417. unfinished_drop = test_bit(BTRFS_ROOT_UNFINISHED_DROP, &root->state);
  5418. if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
  5419. level = btrfs_header_level(root->node);
  5420. path->nodes[level] = btrfs_lock_root_node(root);
  5421. path->slots[level] = 0;
  5422. path->locks[level] = BTRFS_WRITE_LOCK;
  5423. memset(&wc->update_progress, 0,
  5424. sizeof(wc->update_progress));
  5425. } else {
  5426. btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
  5427. memcpy(&wc->update_progress, &key,
  5428. sizeof(wc->update_progress));
  5429. level = btrfs_root_drop_level(root_item);
  5430. BUG_ON(level == 0);
  5431. path->lowest_level = level;
  5432. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  5433. path->lowest_level = 0;
  5434. if (ret < 0)
  5435. goto out_end_trans;
  5436. WARN_ON(ret > 0);
  5437. ret = 0;
  5438. /*
  5439. * unlock our path, this is safe because only this
  5440. * function is allowed to delete this snapshot
  5441. */
  5442. btrfs_unlock_up_safe(path, 0);
  5443. level = btrfs_header_level(root->node);
  5444. while (1) {
  5445. btrfs_tree_lock(path->nodes[level]);
  5446. path->locks[level] = BTRFS_WRITE_LOCK;
  5447. /*
  5448. * btrfs_lookup_extent_info() returns 0 for success,
  5449. * or < 0 for error.
  5450. */
  5451. ret = btrfs_lookup_extent_info(trans, fs_info,
  5452. path->nodes[level]->start,
  5453. level, 1, &wc->refs[level],
  5454. &wc->flags[level], NULL);
  5455. if (ret < 0)
  5456. goto out_end_trans;
  5457. BUG_ON(wc->refs[level] == 0);
  5458. if (level == btrfs_root_drop_level(root_item))
  5459. break;
  5460. btrfs_tree_unlock(path->nodes[level]);
  5461. path->locks[level] = 0;
  5462. WARN_ON(wc->refs[level] != 1);
  5463. level--;
  5464. }
  5465. }
  5466. wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
  5467. wc->level = level;
  5468. wc->shared_level = -1;
  5469. wc->stage = DROP_REFERENCE;
  5470. wc->update_ref = update_ref;
  5471. wc->keep_locks = 0;
  5472. wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
  5473. while (1) {
  5474. ret = walk_down_tree(trans, root, path, wc);
  5475. if (ret < 0) {
  5476. btrfs_abort_transaction(trans, ret);
  5477. break;
  5478. }
  5479. ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
  5480. if (ret < 0) {
  5481. btrfs_abort_transaction(trans, ret);
  5482. break;
  5483. }
  5484. if (ret > 0) {
  5485. BUG_ON(wc->stage != DROP_REFERENCE);
  5486. ret = 0;
  5487. break;
  5488. }
  5489. if (wc->stage == DROP_REFERENCE) {
  5490. wc->drop_level = wc->level;
  5491. btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
  5492. &wc->drop_progress,
  5493. path->slots[wc->drop_level]);
  5494. }
  5495. btrfs_cpu_key_to_disk(&root_item->drop_progress,
  5496. &wc->drop_progress);
  5497. btrfs_set_root_drop_level(root_item, wc->drop_level);
  5498. BUG_ON(wc->level == 0);
  5499. if (btrfs_should_end_transaction(trans) ||
  5500. (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
  5501. ret = btrfs_update_root(trans, tree_root,
  5502. &root->root_key,
  5503. root_item);
  5504. if (ret) {
  5505. btrfs_abort_transaction(trans, ret);
  5506. goto out_end_trans;
  5507. }
  5508. if (!is_reloc_root)
  5509. btrfs_set_last_root_drop_gen(fs_info, trans->transid);
  5510. btrfs_end_transaction_throttle(trans);
  5511. if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
  5512. btrfs_debug(fs_info,
  5513. "drop snapshot early exit");
  5514. ret = -EAGAIN;
  5515. goto out_free;
  5516. }
  5517. /*
  5518. * Use join to avoid potential EINTR from transaction
  5519. * start. See wait_reserve_ticket and the whole
  5520. * reservation callchain.
  5521. */
  5522. if (for_reloc)
  5523. trans = btrfs_join_transaction(tree_root);
  5524. else
  5525. trans = btrfs_start_transaction(tree_root, 0);
  5526. if (IS_ERR(trans)) {
  5527. ret = PTR_ERR(trans);
  5528. goto out_free;
  5529. }
  5530. }
  5531. }
  5532. btrfs_release_path(path);
  5533. if (ret)
  5534. goto out_end_trans;
  5535. ret = btrfs_del_root(trans, &root->root_key);
  5536. if (ret) {
  5537. btrfs_abort_transaction(trans, ret);
  5538. goto out_end_trans;
  5539. }
  5540. if (!is_reloc_root) {
  5541. ret = btrfs_find_root(tree_root, &root->root_key, path,
  5542. NULL, NULL);
  5543. if (ret < 0) {
  5544. btrfs_abort_transaction(trans, ret);
  5545. goto out_end_trans;
  5546. } else if (ret > 0) {
  5547. ret = 0;
  5548. /*
  5549. * If we fail to delete the orphan item this time
  5550. * around, it'll get picked up the next time.
  5551. *
  5552. * The most common failure here is just -ENOENT.
  5553. */
  5554. btrfs_del_orphan_item(trans, tree_root, btrfs_root_id(root));
  5555. }
  5556. }
  5557. /*
  5558. * This subvolume is going to be completely dropped, and won't be
  5559. * recorded as dirty roots, thus pertrans meta rsv will not be freed at
  5560. * commit transaction time. So free it here manually.
  5561. */
  5562. btrfs_qgroup_convert_reserved_meta(root, INT_MAX);
  5563. btrfs_qgroup_free_meta_all_pertrans(root);
  5564. if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state))
  5565. btrfs_add_dropped_root(trans, root);
  5566. else
  5567. btrfs_put_root(root);
  5568. root_dropped = true;
  5569. out_end_trans:
  5570. if (!is_reloc_root)
  5571. btrfs_set_last_root_drop_gen(fs_info, trans->transid);
  5572. btrfs_end_transaction_throttle(trans);
  5573. out_free:
  5574. kfree(wc);
  5575. btrfs_free_path(path);
  5576. out:
  5577. if (!ret && root_dropped) {
  5578. ret = btrfs_qgroup_cleanup_dropped_subvolume(fs_info, rootid);
  5579. if (ret < 0)
  5580. btrfs_warn_rl(fs_info,
  5581. "failed to cleanup qgroup 0/%llu: %d",
  5582. rootid, ret);
  5583. ret = 0;
  5584. }
  5585. /*
  5586. * We were an unfinished drop root, check to see if there are any
  5587. * pending, and if not clear and wake up any waiters.
  5588. */
  5589. if (!ret && unfinished_drop)
  5590. btrfs_maybe_wake_unfinished_drop(fs_info);
  5591. /*
  5592. * So if we need to stop dropping the snapshot for whatever reason we
  5593. * need to make sure to add it back to the dead root list so that we
  5594. * keep trying to do the work later. This also cleans up roots if we
  5595. * don't have it in the radix (like when we recover after a power fail
  5596. * or unmount) so we don't leak memory.
  5597. */
  5598. if (!for_reloc && !root_dropped)
  5599. btrfs_add_dead_root(root);
  5600. return ret;
  5601. }
  5602. /*
  5603. * drop subtree rooted at tree block 'node'.
  5604. *
  5605. * NOTE: this function will unlock and release tree block 'node'
  5606. * only used by relocation code
  5607. */
  5608. int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
  5609. struct btrfs_root *root,
  5610. struct extent_buffer *node,
  5611. struct extent_buffer *parent)
  5612. {
  5613. struct btrfs_fs_info *fs_info = root->fs_info;
  5614. struct btrfs_path *path;
  5615. struct walk_control *wc;
  5616. int level;
  5617. int parent_level;
  5618. int ret = 0;
  5619. BUG_ON(btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID);
  5620. path = btrfs_alloc_path();
  5621. if (!path)
  5622. return -ENOMEM;
  5623. wc = kzalloc(sizeof(*wc), GFP_NOFS);
  5624. if (!wc) {
  5625. btrfs_free_path(path);
  5626. return -ENOMEM;
  5627. }
  5628. btrfs_assert_tree_write_locked(parent);
  5629. parent_level = btrfs_header_level(parent);
  5630. atomic_inc(&parent->refs);
  5631. path->nodes[parent_level] = parent;
  5632. path->slots[parent_level] = btrfs_header_nritems(parent);
  5633. btrfs_assert_tree_write_locked(node);
  5634. level = btrfs_header_level(node);
  5635. path->nodes[level] = node;
  5636. path->slots[level] = 0;
  5637. path->locks[level] = BTRFS_WRITE_LOCK;
  5638. wc->refs[parent_level] = 1;
  5639. wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  5640. wc->level = level;
  5641. wc->shared_level = -1;
  5642. wc->stage = DROP_REFERENCE;
  5643. wc->update_ref = 0;
  5644. wc->keep_locks = 1;
  5645. wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
  5646. while (1) {
  5647. ret = walk_down_tree(trans, root, path, wc);
  5648. if (ret < 0)
  5649. break;
  5650. ret = walk_up_tree(trans, root, path, wc, parent_level);
  5651. if (ret) {
  5652. if (ret > 0)
  5653. ret = 0;
  5654. break;
  5655. }
  5656. }
  5657. kfree(wc);
  5658. btrfs_free_path(path);
  5659. return ret;
  5660. }
  5661. /*
  5662. * Unpin the extent range in an error context and don't add the space back.
  5663. * Errors are not propagated further.
  5664. */
  5665. void btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info, u64 start, u64 end)
  5666. {
  5667. unpin_extent_range(fs_info, start, end, false);
  5668. }
  5669. /*
  5670. * It used to be that old block groups would be left around forever.
  5671. * Iterating over them would be enough to trim unused space. Since we
  5672. * now automatically remove them, we also need to iterate over unallocated
  5673. * space.
  5674. *
  5675. * We don't want a transaction for this since the discard may take a
  5676. * substantial amount of time. We don't require that a transaction be
  5677. * running, but we do need to take a running transaction into account
  5678. * to ensure that we're not discarding chunks that were released or
  5679. * allocated in the current transaction.
  5680. *
  5681. * Holding the chunks lock will prevent other threads from allocating
  5682. * or releasing chunks, but it won't prevent a running transaction
  5683. * from committing and releasing the memory that the pending chunks
  5684. * list head uses. For that, we need to take a reference to the
  5685. * transaction and hold the commit root sem. We only need to hold
  5686. * it while performing the free space search since we have already
  5687. * held back allocations.
  5688. */
  5689. static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
  5690. {
  5691. u64 start = BTRFS_DEVICE_RANGE_RESERVED, len = 0, end = 0;
  5692. int ret;
  5693. *trimmed = 0;
  5694. /* Discard not supported = nothing to do. */
  5695. if (!bdev_max_discard_sectors(device->bdev))
  5696. return 0;
  5697. /* Not writable = nothing to do. */
  5698. if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
  5699. return 0;
  5700. /* No free space = nothing to do. */
  5701. if (device->total_bytes <= device->bytes_used)
  5702. return 0;
  5703. ret = 0;
  5704. while (1) {
  5705. struct btrfs_fs_info *fs_info = device->fs_info;
  5706. u64 bytes;
  5707. ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
  5708. if (ret)
  5709. break;
  5710. find_first_clear_extent_bit(&device->alloc_state, start,
  5711. &start, &end,
  5712. CHUNK_TRIMMED | CHUNK_ALLOCATED);
  5713. /* Check if there are any CHUNK_* bits left */
  5714. if (start > device->total_bytes) {
  5715. WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
  5716. btrfs_warn_in_rcu(fs_info,
  5717. "ignoring attempt to trim beyond device size: offset %llu length %llu device %s device size %llu",
  5718. start, end - start + 1,
  5719. btrfs_dev_name(device),
  5720. device->total_bytes);
  5721. mutex_unlock(&fs_info->chunk_mutex);
  5722. ret = 0;
  5723. break;
  5724. }
  5725. /* Ensure we skip the reserved space on each device. */
  5726. start = max_t(u64, start, BTRFS_DEVICE_RANGE_RESERVED);
  5727. /*
  5728. * If find_first_clear_extent_bit find a range that spans the
  5729. * end of the device it will set end to -1, in this case it's up
  5730. * to the caller to trim the value to the size of the device.
  5731. */
  5732. end = min(end, device->total_bytes - 1);
  5733. len = end - start + 1;
  5734. /* We didn't find any extents */
  5735. if (!len) {
  5736. mutex_unlock(&fs_info->chunk_mutex);
  5737. ret = 0;
  5738. break;
  5739. }
  5740. ret = btrfs_issue_discard(device->bdev, start, len,
  5741. &bytes);
  5742. if (!ret)
  5743. set_extent_bit(&device->alloc_state, start,
  5744. start + bytes - 1, CHUNK_TRIMMED, NULL);
  5745. mutex_unlock(&fs_info->chunk_mutex);
  5746. if (ret)
  5747. break;
  5748. start += len;
  5749. *trimmed += bytes;
  5750. if (btrfs_trim_interrupted()) {
  5751. ret = -ERESTARTSYS;
  5752. break;
  5753. }
  5754. cond_resched();
  5755. }
  5756. return ret;
  5757. }
  5758. /*
  5759. * Trim the whole filesystem by:
  5760. * 1) trimming the free space in each block group
  5761. * 2) trimming the unallocated space on each device
  5762. *
  5763. * This will also continue trimming even if a block group or device encounters
  5764. * an error. The return value will be the last error, or 0 if nothing bad
  5765. * happens.
  5766. */
  5767. int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
  5768. {
  5769. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  5770. struct btrfs_block_group *cache = NULL;
  5771. struct btrfs_device *device;
  5772. u64 group_trimmed;
  5773. u64 range_end = U64_MAX;
  5774. u64 start;
  5775. u64 end;
  5776. u64 trimmed = 0;
  5777. u64 bg_failed = 0;
  5778. u64 dev_failed = 0;
  5779. int bg_ret = 0;
  5780. int dev_ret = 0;
  5781. int ret = 0;
  5782. if (range->start == U64_MAX)
  5783. return -EINVAL;
  5784. /*
  5785. * Check range overflow if range->len is set.
  5786. * The default range->len is U64_MAX.
  5787. */
  5788. if (range->len != U64_MAX &&
  5789. check_add_overflow(range->start, range->len, &range_end))
  5790. return -EINVAL;
  5791. cache = btrfs_lookup_first_block_group(fs_info, range->start);
  5792. for (; cache; cache = btrfs_next_block_group(cache)) {
  5793. if (cache->start >= range_end) {
  5794. btrfs_put_block_group(cache);
  5795. break;
  5796. }
  5797. start = max(range->start, cache->start);
  5798. end = min(range_end, cache->start + cache->length);
  5799. if (end - start >= range->minlen) {
  5800. if (!btrfs_block_group_done(cache)) {
  5801. ret = btrfs_cache_block_group(cache, true);
  5802. if (ret) {
  5803. bg_failed++;
  5804. bg_ret = ret;
  5805. continue;
  5806. }
  5807. }
  5808. ret = btrfs_trim_block_group(cache,
  5809. &group_trimmed,
  5810. start,
  5811. end,
  5812. range->minlen);
  5813. trimmed += group_trimmed;
  5814. if (ret) {
  5815. bg_failed++;
  5816. bg_ret = ret;
  5817. continue;
  5818. }
  5819. }
  5820. }
  5821. if (bg_failed)
  5822. btrfs_warn(fs_info,
  5823. "failed to trim %llu block group(s), last error %d",
  5824. bg_failed, bg_ret);
  5825. mutex_lock(&fs_devices->device_list_mutex);
  5826. list_for_each_entry(device, &fs_devices->devices, dev_list) {
  5827. if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
  5828. continue;
  5829. ret = btrfs_trim_free_extents(device, &group_trimmed);
  5830. trimmed += group_trimmed;
  5831. if (ret) {
  5832. dev_failed++;
  5833. dev_ret = ret;
  5834. break;
  5835. }
  5836. }
  5837. mutex_unlock(&fs_devices->device_list_mutex);
  5838. if (dev_failed)
  5839. btrfs_warn(fs_info,
  5840. "failed to trim %llu device(s), last error %d",
  5841. dev_failed, dev_ret);
  5842. range->len = trimmed;
  5843. if (bg_ret)
  5844. return bg_ret;
  5845. return dev_ret;
  5846. }