extent-tree.c 300 KB

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