extent-tree.c 299 KB

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