extent-tree.c 302 KB

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