extent-tree.c 300 KB

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