extent-tree.c 299 KB

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