extent-tree.c 169 KB

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