extent-tree.c 299 KB

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