extent-tree.c 301 KB

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