extent-tree.c 299 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017
  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(trans, 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_root *root,
  924. struct btrfs_path *path,
  925. u64 owner, u32 extra_size)
  926. {
  927. struct btrfs_extent_item *item;
  928. struct btrfs_extent_item_v0 *ei0;
  929. struct btrfs_extent_ref_v0 *ref0;
  930. struct btrfs_tree_block_info *bi;
  931. struct extent_buffer *leaf;
  932. struct btrfs_key key;
  933. struct btrfs_key found_key;
  934. u32 new_size = sizeof(*item);
  935. u64 refs;
  936. int ret;
  937. leaf = path->nodes[0];
  938. BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
  939. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  940. ei0 = btrfs_item_ptr(leaf, path->slots[0],
  941. struct btrfs_extent_item_v0);
  942. refs = btrfs_extent_refs_v0(leaf, ei0);
  943. if (owner == (u64)-1) {
  944. while (1) {
  945. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  946. ret = btrfs_next_leaf(root, path);
  947. if (ret < 0)
  948. return ret;
  949. BUG_ON(ret > 0); /* Corruption */
  950. leaf = path->nodes[0];
  951. }
  952. btrfs_item_key_to_cpu(leaf, &found_key,
  953. path->slots[0]);
  954. BUG_ON(key.objectid != found_key.objectid);
  955. if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
  956. path->slots[0]++;
  957. continue;
  958. }
  959. ref0 = btrfs_item_ptr(leaf, path->slots[0],
  960. struct btrfs_extent_ref_v0);
  961. owner = btrfs_ref_objectid_v0(leaf, ref0);
  962. break;
  963. }
  964. }
  965. btrfs_release_path(path);
  966. if (owner < BTRFS_FIRST_FREE_OBJECTID)
  967. new_size += sizeof(*bi);
  968. new_size -= sizeof(*ei0);
  969. ret = btrfs_search_slot(trans, root, &key, path,
  970. new_size + extra_size, 1);
  971. if (ret < 0)
  972. return ret;
  973. BUG_ON(ret); /* Corruption */
  974. btrfs_extend_item(root->fs_info, path, new_size);
  975. leaf = path->nodes[0];
  976. item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  977. btrfs_set_extent_refs(leaf, item, refs);
  978. /* FIXME: get real generation */
  979. btrfs_set_extent_generation(leaf, item, 0);
  980. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  981. btrfs_set_extent_flags(leaf, item,
  982. BTRFS_EXTENT_FLAG_TREE_BLOCK |
  983. BTRFS_BLOCK_FLAG_FULL_BACKREF);
  984. bi = (struct btrfs_tree_block_info *)(item + 1);
  985. /* FIXME: get first key of the block */
  986. memzero_extent_buffer(leaf, (unsigned long)bi, sizeof(*bi));
  987. btrfs_set_tree_block_level(leaf, bi, (int)owner);
  988. } else {
  989. btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
  990. }
  991. btrfs_mark_buffer_dirty(leaf);
  992. return 0;
  993. }
  994. #endif
  995. static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
  996. {
  997. u32 high_crc = ~(u32)0;
  998. u32 low_crc = ~(u32)0;
  999. __le64 lenum;
  1000. lenum = cpu_to_le64(root_objectid);
  1001. high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
  1002. lenum = cpu_to_le64(owner);
  1003. low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
  1004. lenum = cpu_to_le64(offset);
  1005. low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
  1006. return ((u64)high_crc << 31) ^ (u64)low_crc;
  1007. }
  1008. static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
  1009. struct btrfs_extent_data_ref *ref)
  1010. {
  1011. return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
  1012. btrfs_extent_data_ref_objectid(leaf, ref),
  1013. btrfs_extent_data_ref_offset(leaf, ref));
  1014. }
  1015. static int match_extent_data_ref(struct extent_buffer *leaf,
  1016. struct btrfs_extent_data_ref *ref,
  1017. u64 root_objectid, u64 owner, u64 offset)
  1018. {
  1019. if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
  1020. btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
  1021. btrfs_extent_data_ref_offset(leaf, ref) != offset)
  1022. return 0;
  1023. return 1;
  1024. }
  1025. static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
  1026. struct btrfs_root *root,
  1027. struct btrfs_path *path,
  1028. u64 bytenr, u64 parent,
  1029. u64 root_objectid,
  1030. u64 owner, u64 offset)
  1031. {
  1032. struct btrfs_key key;
  1033. struct btrfs_extent_data_ref *ref;
  1034. struct extent_buffer *leaf;
  1035. u32 nritems;
  1036. int ret;
  1037. int recow;
  1038. int err = -ENOENT;
  1039. key.objectid = bytenr;
  1040. if (parent) {
  1041. key.type = BTRFS_SHARED_DATA_REF_KEY;
  1042. key.offset = parent;
  1043. } else {
  1044. key.type = BTRFS_EXTENT_DATA_REF_KEY;
  1045. key.offset = hash_extent_data_ref(root_objectid,
  1046. owner, offset);
  1047. }
  1048. again:
  1049. recow = 0;
  1050. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1051. if (ret < 0) {
  1052. err = ret;
  1053. goto fail;
  1054. }
  1055. if (parent) {
  1056. if (!ret)
  1057. return 0;
  1058. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1059. key.type = BTRFS_EXTENT_REF_V0_KEY;
  1060. btrfs_release_path(path);
  1061. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1062. if (ret < 0) {
  1063. err = ret;
  1064. goto fail;
  1065. }
  1066. if (!ret)
  1067. return 0;
  1068. #endif
  1069. goto fail;
  1070. }
  1071. leaf = path->nodes[0];
  1072. nritems = btrfs_header_nritems(leaf);
  1073. while (1) {
  1074. if (path->slots[0] >= nritems) {
  1075. ret = btrfs_next_leaf(root, path);
  1076. if (ret < 0)
  1077. err = ret;
  1078. if (ret)
  1079. goto fail;
  1080. leaf = path->nodes[0];
  1081. nritems = btrfs_header_nritems(leaf);
  1082. recow = 1;
  1083. }
  1084. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1085. if (key.objectid != bytenr ||
  1086. key.type != BTRFS_EXTENT_DATA_REF_KEY)
  1087. goto fail;
  1088. ref = btrfs_item_ptr(leaf, path->slots[0],
  1089. struct btrfs_extent_data_ref);
  1090. if (match_extent_data_ref(leaf, ref, root_objectid,
  1091. owner, offset)) {
  1092. if (recow) {
  1093. btrfs_release_path(path);
  1094. goto again;
  1095. }
  1096. err = 0;
  1097. break;
  1098. }
  1099. path->slots[0]++;
  1100. }
  1101. fail:
  1102. return err;
  1103. }
  1104. static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
  1105. struct btrfs_root *root,
  1106. struct btrfs_path *path,
  1107. u64 bytenr, u64 parent,
  1108. u64 root_objectid, u64 owner,
  1109. u64 offset, int refs_to_add)
  1110. {
  1111. struct btrfs_key key;
  1112. struct extent_buffer *leaf;
  1113. u32 size;
  1114. u32 num_refs;
  1115. int ret;
  1116. key.objectid = bytenr;
  1117. if (parent) {
  1118. key.type = BTRFS_SHARED_DATA_REF_KEY;
  1119. key.offset = parent;
  1120. size = sizeof(struct btrfs_shared_data_ref);
  1121. } else {
  1122. key.type = BTRFS_EXTENT_DATA_REF_KEY;
  1123. key.offset = hash_extent_data_ref(root_objectid,
  1124. owner, offset);
  1125. size = sizeof(struct btrfs_extent_data_ref);
  1126. }
  1127. ret = btrfs_insert_empty_item(trans, root, path, &key, size);
  1128. if (ret && ret != -EEXIST)
  1129. goto fail;
  1130. leaf = path->nodes[0];
  1131. if (parent) {
  1132. struct btrfs_shared_data_ref *ref;
  1133. ref = btrfs_item_ptr(leaf, path->slots[0],
  1134. struct btrfs_shared_data_ref);
  1135. if (ret == 0) {
  1136. btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
  1137. } else {
  1138. num_refs = btrfs_shared_data_ref_count(leaf, ref);
  1139. num_refs += refs_to_add;
  1140. btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
  1141. }
  1142. } else {
  1143. struct btrfs_extent_data_ref *ref;
  1144. while (ret == -EEXIST) {
  1145. ref = btrfs_item_ptr(leaf, path->slots[0],
  1146. struct btrfs_extent_data_ref);
  1147. if (match_extent_data_ref(leaf, ref, root_objectid,
  1148. owner, offset))
  1149. break;
  1150. btrfs_release_path(path);
  1151. key.offset++;
  1152. ret = btrfs_insert_empty_item(trans, root, path, &key,
  1153. size);
  1154. if (ret && ret != -EEXIST)
  1155. goto fail;
  1156. leaf = path->nodes[0];
  1157. }
  1158. ref = btrfs_item_ptr(leaf, path->slots[0],
  1159. struct btrfs_extent_data_ref);
  1160. if (ret == 0) {
  1161. btrfs_set_extent_data_ref_root(leaf, ref,
  1162. root_objectid);
  1163. btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
  1164. btrfs_set_extent_data_ref_offset(leaf, ref, offset);
  1165. btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
  1166. } else {
  1167. num_refs = btrfs_extent_data_ref_count(leaf, ref);
  1168. num_refs += refs_to_add;
  1169. btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
  1170. }
  1171. }
  1172. btrfs_mark_buffer_dirty(leaf);
  1173. ret = 0;
  1174. fail:
  1175. btrfs_release_path(path);
  1176. return ret;
  1177. }
  1178. static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
  1179. struct btrfs_root *root,
  1180. struct btrfs_path *path,
  1181. int refs_to_drop, int *last_ref)
  1182. {
  1183. struct btrfs_key key;
  1184. struct btrfs_extent_data_ref *ref1 = NULL;
  1185. struct btrfs_shared_data_ref *ref2 = NULL;
  1186. struct extent_buffer *leaf;
  1187. u32 num_refs = 0;
  1188. int ret = 0;
  1189. leaf = path->nodes[0];
  1190. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1191. if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
  1192. ref1 = btrfs_item_ptr(leaf, path->slots[0],
  1193. struct btrfs_extent_data_ref);
  1194. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  1195. } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
  1196. ref2 = btrfs_item_ptr(leaf, path->slots[0],
  1197. struct btrfs_shared_data_ref);
  1198. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  1199. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1200. } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
  1201. struct btrfs_extent_ref_v0 *ref0;
  1202. ref0 = btrfs_item_ptr(leaf, path->slots[0],
  1203. struct btrfs_extent_ref_v0);
  1204. num_refs = btrfs_ref_count_v0(leaf, ref0);
  1205. #endif
  1206. } else {
  1207. BUG();
  1208. }
  1209. BUG_ON(num_refs < refs_to_drop);
  1210. num_refs -= refs_to_drop;
  1211. if (num_refs == 0) {
  1212. ret = btrfs_del_item(trans, root, path);
  1213. *last_ref = 1;
  1214. } else {
  1215. if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
  1216. btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
  1217. else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
  1218. btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
  1219. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1220. else {
  1221. struct btrfs_extent_ref_v0 *ref0;
  1222. ref0 = btrfs_item_ptr(leaf, path->slots[0],
  1223. struct btrfs_extent_ref_v0);
  1224. btrfs_set_ref_count_v0(leaf, ref0, num_refs);
  1225. }
  1226. #endif
  1227. btrfs_mark_buffer_dirty(leaf);
  1228. }
  1229. return ret;
  1230. }
  1231. static noinline u32 extent_data_ref_count(struct btrfs_path *path,
  1232. struct btrfs_extent_inline_ref *iref)
  1233. {
  1234. struct btrfs_key key;
  1235. struct extent_buffer *leaf;
  1236. struct btrfs_extent_data_ref *ref1;
  1237. struct btrfs_shared_data_ref *ref2;
  1238. u32 num_refs = 0;
  1239. leaf = path->nodes[0];
  1240. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1241. if (iref) {
  1242. if (btrfs_extent_inline_ref_type(leaf, iref) ==
  1243. BTRFS_EXTENT_DATA_REF_KEY) {
  1244. ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
  1245. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  1246. } else {
  1247. ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
  1248. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  1249. }
  1250. } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
  1251. ref1 = btrfs_item_ptr(leaf, path->slots[0],
  1252. struct btrfs_extent_data_ref);
  1253. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  1254. } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
  1255. ref2 = btrfs_item_ptr(leaf, path->slots[0],
  1256. struct btrfs_shared_data_ref);
  1257. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  1258. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1259. } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
  1260. struct btrfs_extent_ref_v0 *ref0;
  1261. ref0 = btrfs_item_ptr(leaf, path->slots[0],
  1262. struct btrfs_extent_ref_v0);
  1263. num_refs = btrfs_ref_count_v0(leaf, ref0);
  1264. #endif
  1265. } else {
  1266. WARN_ON(1);
  1267. }
  1268. return num_refs;
  1269. }
  1270. static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
  1271. struct btrfs_root *root,
  1272. struct btrfs_path *path,
  1273. u64 bytenr, u64 parent,
  1274. u64 root_objectid)
  1275. {
  1276. struct btrfs_key key;
  1277. int ret;
  1278. key.objectid = bytenr;
  1279. if (parent) {
  1280. key.type = BTRFS_SHARED_BLOCK_REF_KEY;
  1281. key.offset = parent;
  1282. } else {
  1283. key.type = BTRFS_TREE_BLOCK_REF_KEY;
  1284. key.offset = root_objectid;
  1285. }
  1286. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1287. if (ret > 0)
  1288. ret = -ENOENT;
  1289. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1290. if (ret == -ENOENT && parent) {
  1291. btrfs_release_path(path);
  1292. key.type = BTRFS_EXTENT_REF_V0_KEY;
  1293. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1294. if (ret > 0)
  1295. ret = -ENOENT;
  1296. }
  1297. #endif
  1298. return ret;
  1299. }
  1300. static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
  1301. struct btrfs_root *root,
  1302. struct btrfs_path *path,
  1303. u64 bytenr, u64 parent,
  1304. u64 root_objectid)
  1305. {
  1306. struct btrfs_key key;
  1307. int ret;
  1308. key.objectid = bytenr;
  1309. if (parent) {
  1310. key.type = BTRFS_SHARED_BLOCK_REF_KEY;
  1311. key.offset = parent;
  1312. } else {
  1313. key.type = BTRFS_TREE_BLOCK_REF_KEY;
  1314. key.offset = root_objectid;
  1315. }
  1316. ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
  1317. btrfs_release_path(path);
  1318. return ret;
  1319. }
  1320. static inline int extent_ref_type(u64 parent, u64 owner)
  1321. {
  1322. int type;
  1323. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1324. if (parent > 0)
  1325. type = BTRFS_SHARED_BLOCK_REF_KEY;
  1326. else
  1327. type = BTRFS_TREE_BLOCK_REF_KEY;
  1328. } else {
  1329. if (parent > 0)
  1330. type = BTRFS_SHARED_DATA_REF_KEY;
  1331. else
  1332. type = BTRFS_EXTENT_DATA_REF_KEY;
  1333. }
  1334. return type;
  1335. }
  1336. static int find_next_key(struct btrfs_path *path, int level,
  1337. struct btrfs_key *key)
  1338. {
  1339. for (; level < BTRFS_MAX_LEVEL; level++) {
  1340. if (!path->nodes[level])
  1341. break;
  1342. if (path->slots[level] + 1 >=
  1343. btrfs_header_nritems(path->nodes[level]))
  1344. continue;
  1345. if (level == 0)
  1346. btrfs_item_key_to_cpu(path->nodes[level], key,
  1347. path->slots[level] + 1);
  1348. else
  1349. btrfs_node_key_to_cpu(path->nodes[level], key,
  1350. path->slots[level] + 1);
  1351. return 0;
  1352. }
  1353. return 1;
  1354. }
  1355. /*
  1356. * look for inline back ref. if back ref is found, *ref_ret is set
  1357. * to the address of inline back ref, and 0 is returned.
  1358. *
  1359. * if back ref isn't found, *ref_ret is set to the address where it
  1360. * should be inserted, and -ENOENT is returned.
  1361. *
  1362. * if insert is true and there are too many inline back refs, the path
  1363. * points to the extent item, and -EAGAIN is returned.
  1364. *
  1365. * NOTE: inline back refs are ordered in the same way that back ref
  1366. * items in the tree are ordered.
  1367. */
  1368. static noinline_for_stack
  1369. int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
  1370. struct btrfs_root *root,
  1371. struct btrfs_path *path,
  1372. struct btrfs_extent_inline_ref **ref_ret,
  1373. u64 bytenr, u64 num_bytes,
  1374. u64 parent, u64 root_objectid,
  1375. u64 owner, u64 offset, int insert)
  1376. {
  1377. struct btrfs_fs_info *fs_info = root->fs_info;
  1378. struct btrfs_key key;
  1379. struct extent_buffer *leaf;
  1380. struct btrfs_extent_item *ei;
  1381. struct btrfs_extent_inline_ref *iref;
  1382. u64 flags;
  1383. u64 item_size;
  1384. unsigned long ptr;
  1385. unsigned long end;
  1386. int extra_size;
  1387. int type;
  1388. int want;
  1389. int ret;
  1390. int err = 0;
  1391. bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
  1392. key.objectid = bytenr;
  1393. key.type = BTRFS_EXTENT_ITEM_KEY;
  1394. key.offset = num_bytes;
  1395. want = extent_ref_type(parent, owner);
  1396. if (insert) {
  1397. extra_size = btrfs_extent_inline_ref_size(want);
  1398. path->keep_locks = 1;
  1399. } else
  1400. extra_size = -1;
  1401. /*
  1402. * Owner is our parent level, so we can just add one to get the level
  1403. * for the block we are interested in.
  1404. */
  1405. if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
  1406. key.type = BTRFS_METADATA_ITEM_KEY;
  1407. key.offset = owner;
  1408. }
  1409. again:
  1410. ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
  1411. if (ret < 0) {
  1412. err = ret;
  1413. goto out;
  1414. }
  1415. /*
  1416. * We may be a newly converted file system which still has the old fat
  1417. * extent entries for metadata, so try and see if we have one of those.
  1418. */
  1419. if (ret > 0 && skinny_metadata) {
  1420. skinny_metadata = false;
  1421. if (path->slots[0]) {
  1422. path->slots[0]--;
  1423. btrfs_item_key_to_cpu(path->nodes[0], &key,
  1424. path->slots[0]);
  1425. if (key.objectid == bytenr &&
  1426. key.type == BTRFS_EXTENT_ITEM_KEY &&
  1427. key.offset == num_bytes)
  1428. ret = 0;
  1429. }
  1430. if (ret) {
  1431. key.objectid = bytenr;
  1432. key.type = BTRFS_EXTENT_ITEM_KEY;
  1433. key.offset = num_bytes;
  1434. btrfs_release_path(path);
  1435. goto again;
  1436. }
  1437. }
  1438. if (ret && !insert) {
  1439. err = -ENOENT;
  1440. goto out;
  1441. } else if (WARN_ON(ret)) {
  1442. err = -EIO;
  1443. goto out;
  1444. }
  1445. leaf = path->nodes[0];
  1446. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1447. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1448. if (item_size < sizeof(*ei)) {
  1449. if (!insert) {
  1450. err = -ENOENT;
  1451. goto out;
  1452. }
  1453. ret = convert_extent_item_v0(trans, root, path, owner,
  1454. extra_size);
  1455. if (ret < 0) {
  1456. err = ret;
  1457. goto out;
  1458. }
  1459. leaf = path->nodes[0];
  1460. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1461. }
  1462. #endif
  1463. BUG_ON(item_size < sizeof(*ei));
  1464. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1465. flags = btrfs_extent_flags(leaf, ei);
  1466. ptr = (unsigned long)(ei + 1);
  1467. end = (unsigned long)ei + item_size;
  1468. if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
  1469. ptr += sizeof(struct btrfs_tree_block_info);
  1470. BUG_ON(ptr > end);
  1471. }
  1472. err = -ENOENT;
  1473. while (1) {
  1474. if (ptr >= end) {
  1475. WARN_ON(ptr > end);
  1476. break;
  1477. }
  1478. iref = (struct btrfs_extent_inline_ref *)ptr;
  1479. type = btrfs_extent_inline_ref_type(leaf, iref);
  1480. if (want < type)
  1481. break;
  1482. if (want > type) {
  1483. ptr += btrfs_extent_inline_ref_size(type);
  1484. continue;
  1485. }
  1486. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1487. struct btrfs_extent_data_ref *dref;
  1488. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  1489. if (match_extent_data_ref(leaf, dref, root_objectid,
  1490. owner, offset)) {
  1491. err = 0;
  1492. break;
  1493. }
  1494. if (hash_extent_data_ref_item(leaf, dref) <
  1495. hash_extent_data_ref(root_objectid, owner, offset))
  1496. break;
  1497. } else {
  1498. u64 ref_offset;
  1499. ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
  1500. if (parent > 0) {
  1501. if (parent == ref_offset) {
  1502. err = 0;
  1503. break;
  1504. }
  1505. if (ref_offset < parent)
  1506. break;
  1507. } else {
  1508. if (root_objectid == ref_offset) {
  1509. err = 0;
  1510. break;
  1511. }
  1512. if (ref_offset < root_objectid)
  1513. break;
  1514. }
  1515. }
  1516. ptr += btrfs_extent_inline_ref_size(type);
  1517. }
  1518. if (err == -ENOENT && insert) {
  1519. if (item_size + extra_size >=
  1520. BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
  1521. err = -EAGAIN;
  1522. goto out;
  1523. }
  1524. /*
  1525. * To add new inline back ref, we have to make sure
  1526. * there is no corresponding back ref item.
  1527. * For simplicity, we just do not add new inline back
  1528. * ref if there is any kind of item for this block
  1529. */
  1530. if (find_next_key(path, 0, &key) == 0 &&
  1531. key.objectid == bytenr &&
  1532. key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
  1533. err = -EAGAIN;
  1534. goto out;
  1535. }
  1536. }
  1537. *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
  1538. out:
  1539. if (insert) {
  1540. path->keep_locks = 0;
  1541. btrfs_unlock_up_safe(path, 1);
  1542. }
  1543. return err;
  1544. }
  1545. /*
  1546. * helper to add new inline back ref
  1547. */
  1548. static noinline_for_stack
  1549. void setup_inline_extent_backref(struct btrfs_root *root,
  1550. struct btrfs_path *path,
  1551. struct btrfs_extent_inline_ref *iref,
  1552. u64 parent, u64 root_objectid,
  1553. u64 owner, u64 offset, int refs_to_add,
  1554. struct btrfs_delayed_extent_op *extent_op)
  1555. {
  1556. struct extent_buffer *leaf;
  1557. struct btrfs_extent_item *ei;
  1558. unsigned long ptr;
  1559. unsigned long end;
  1560. unsigned long item_offset;
  1561. u64 refs;
  1562. int size;
  1563. int type;
  1564. leaf = path->nodes[0];
  1565. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1566. item_offset = (unsigned long)iref - (unsigned long)ei;
  1567. type = extent_ref_type(parent, owner);
  1568. size = btrfs_extent_inline_ref_size(type);
  1569. btrfs_extend_item(root->fs_info, path, size);
  1570. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1571. refs = btrfs_extent_refs(leaf, ei);
  1572. refs += refs_to_add;
  1573. btrfs_set_extent_refs(leaf, ei, refs);
  1574. if (extent_op)
  1575. __run_delayed_extent_op(extent_op, leaf, ei);
  1576. ptr = (unsigned long)ei + item_offset;
  1577. end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
  1578. if (ptr < end - size)
  1579. memmove_extent_buffer(leaf, ptr + size, ptr,
  1580. end - size - ptr);
  1581. iref = (struct btrfs_extent_inline_ref *)ptr;
  1582. btrfs_set_extent_inline_ref_type(leaf, iref, type);
  1583. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1584. struct btrfs_extent_data_ref *dref;
  1585. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  1586. btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
  1587. btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
  1588. btrfs_set_extent_data_ref_offset(leaf, dref, offset);
  1589. btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
  1590. } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
  1591. struct btrfs_shared_data_ref *sref;
  1592. sref = (struct btrfs_shared_data_ref *)(iref + 1);
  1593. btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
  1594. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  1595. } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
  1596. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  1597. } else {
  1598. btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
  1599. }
  1600. btrfs_mark_buffer_dirty(leaf);
  1601. }
  1602. static int lookup_extent_backref(struct btrfs_trans_handle *trans,
  1603. struct btrfs_root *root,
  1604. struct btrfs_path *path,
  1605. struct btrfs_extent_inline_ref **ref_ret,
  1606. u64 bytenr, u64 num_bytes, u64 parent,
  1607. u64 root_objectid, u64 owner, u64 offset)
  1608. {
  1609. int ret;
  1610. ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
  1611. bytenr, num_bytes, parent,
  1612. root_objectid, owner, offset, 0);
  1613. if (ret != -ENOENT)
  1614. return ret;
  1615. btrfs_release_path(path);
  1616. *ref_ret = NULL;
  1617. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1618. ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
  1619. root_objectid);
  1620. } else {
  1621. ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
  1622. root_objectid, owner, offset);
  1623. }
  1624. return ret;
  1625. }
  1626. /*
  1627. * helper to update/remove inline back ref
  1628. */
  1629. static noinline_for_stack
  1630. void update_inline_extent_backref(struct btrfs_root *root,
  1631. struct btrfs_path *path,
  1632. struct btrfs_extent_inline_ref *iref,
  1633. int refs_to_mod,
  1634. struct btrfs_delayed_extent_op *extent_op,
  1635. int *last_ref)
  1636. {
  1637. struct extent_buffer *leaf;
  1638. struct btrfs_extent_item *ei;
  1639. struct btrfs_extent_data_ref *dref = NULL;
  1640. struct btrfs_shared_data_ref *sref = NULL;
  1641. unsigned long ptr;
  1642. unsigned long end;
  1643. u32 item_size;
  1644. int size;
  1645. int type;
  1646. u64 refs;
  1647. leaf = path->nodes[0];
  1648. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1649. refs = btrfs_extent_refs(leaf, ei);
  1650. WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
  1651. refs += refs_to_mod;
  1652. btrfs_set_extent_refs(leaf, ei, refs);
  1653. if (extent_op)
  1654. __run_delayed_extent_op(extent_op, leaf, ei);
  1655. type = btrfs_extent_inline_ref_type(leaf, iref);
  1656. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1657. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  1658. refs = btrfs_extent_data_ref_count(leaf, dref);
  1659. } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
  1660. sref = (struct btrfs_shared_data_ref *)(iref + 1);
  1661. refs = btrfs_shared_data_ref_count(leaf, sref);
  1662. } else {
  1663. refs = 1;
  1664. BUG_ON(refs_to_mod != -1);
  1665. }
  1666. BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
  1667. refs += refs_to_mod;
  1668. if (refs > 0) {
  1669. if (type == BTRFS_EXTENT_DATA_REF_KEY)
  1670. btrfs_set_extent_data_ref_count(leaf, dref, refs);
  1671. else
  1672. btrfs_set_shared_data_ref_count(leaf, sref, refs);
  1673. } else {
  1674. *last_ref = 1;
  1675. size = btrfs_extent_inline_ref_size(type);
  1676. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1677. ptr = (unsigned long)iref;
  1678. end = (unsigned long)ei + item_size;
  1679. if (ptr + size < end)
  1680. memmove_extent_buffer(leaf, ptr, ptr + size,
  1681. end - ptr - size);
  1682. item_size -= size;
  1683. btrfs_truncate_item(root->fs_info, path, item_size, 1);
  1684. }
  1685. btrfs_mark_buffer_dirty(leaf);
  1686. }
  1687. static noinline_for_stack
  1688. int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
  1689. struct btrfs_root *root,
  1690. struct btrfs_path *path,
  1691. u64 bytenr, u64 num_bytes, u64 parent,
  1692. u64 root_objectid, u64 owner,
  1693. u64 offset, int refs_to_add,
  1694. struct btrfs_delayed_extent_op *extent_op)
  1695. {
  1696. struct btrfs_extent_inline_ref *iref;
  1697. int ret;
  1698. ret = lookup_inline_extent_backref(trans, root, path, &iref,
  1699. bytenr, num_bytes, parent,
  1700. root_objectid, owner, offset, 1);
  1701. if (ret == 0) {
  1702. BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
  1703. update_inline_extent_backref(root, path, iref,
  1704. refs_to_add, extent_op, NULL);
  1705. } else if (ret == -ENOENT) {
  1706. setup_inline_extent_backref(root, path, iref, parent,
  1707. root_objectid, owner, offset,
  1708. refs_to_add, extent_op);
  1709. ret = 0;
  1710. }
  1711. return ret;
  1712. }
  1713. static int insert_extent_backref(struct btrfs_trans_handle *trans,
  1714. struct btrfs_root *root,
  1715. struct btrfs_path *path,
  1716. u64 bytenr, u64 parent, u64 root_objectid,
  1717. u64 owner, u64 offset, int refs_to_add)
  1718. {
  1719. int ret;
  1720. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1721. BUG_ON(refs_to_add != 1);
  1722. ret = insert_tree_block_ref(trans, root, path, bytenr,
  1723. parent, root_objectid);
  1724. } else {
  1725. ret = insert_extent_data_ref(trans, root, path, bytenr,
  1726. parent, root_objectid,
  1727. owner, offset, refs_to_add);
  1728. }
  1729. return ret;
  1730. }
  1731. static int remove_extent_backref(struct btrfs_trans_handle *trans,
  1732. struct btrfs_root *root,
  1733. struct btrfs_path *path,
  1734. struct btrfs_extent_inline_ref *iref,
  1735. int refs_to_drop, int is_data, int *last_ref)
  1736. {
  1737. int ret = 0;
  1738. BUG_ON(!is_data && refs_to_drop != 1);
  1739. if (iref) {
  1740. update_inline_extent_backref(root, path, iref,
  1741. -refs_to_drop, NULL, last_ref);
  1742. } else if (is_data) {
  1743. ret = remove_extent_data_ref(trans, root, path, refs_to_drop,
  1744. last_ref);
  1745. } else {
  1746. *last_ref = 1;
  1747. ret = btrfs_del_item(trans, root, path);
  1748. }
  1749. return ret;
  1750. }
  1751. #define in_range(b, first, len) ((b) >= (first) && (b) < (first) + (len))
  1752. static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
  1753. u64 *discarded_bytes)
  1754. {
  1755. int j, ret = 0;
  1756. u64 bytes_left, end;
  1757. u64 aligned_start = ALIGN(start, 1 << 9);
  1758. if (WARN_ON(start != aligned_start)) {
  1759. len -= aligned_start - start;
  1760. len = round_down(len, 1 << 9);
  1761. start = aligned_start;
  1762. }
  1763. *discarded_bytes = 0;
  1764. if (!len)
  1765. return 0;
  1766. end = start + len;
  1767. bytes_left = len;
  1768. /* Skip any superblocks on this device. */
  1769. for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
  1770. u64 sb_start = btrfs_sb_offset(j);
  1771. u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
  1772. u64 size = sb_start - start;
  1773. if (!in_range(sb_start, start, bytes_left) &&
  1774. !in_range(sb_end, start, bytes_left) &&
  1775. !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
  1776. continue;
  1777. /*
  1778. * Superblock spans beginning of range. Adjust start and
  1779. * try again.
  1780. */
  1781. if (sb_start <= start) {
  1782. start += sb_end - start;
  1783. if (start > end) {
  1784. bytes_left = 0;
  1785. break;
  1786. }
  1787. bytes_left = end - start;
  1788. continue;
  1789. }
  1790. if (size) {
  1791. ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
  1792. GFP_NOFS, 0);
  1793. if (!ret)
  1794. *discarded_bytes += size;
  1795. else if (ret != -EOPNOTSUPP)
  1796. return ret;
  1797. }
  1798. start = sb_end;
  1799. if (start > end) {
  1800. bytes_left = 0;
  1801. break;
  1802. }
  1803. bytes_left = end - start;
  1804. }
  1805. if (bytes_left) {
  1806. ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
  1807. GFP_NOFS, 0);
  1808. if (!ret)
  1809. *discarded_bytes += bytes_left;
  1810. }
  1811. return ret;
  1812. }
  1813. int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
  1814. u64 num_bytes, u64 *actual_bytes)
  1815. {
  1816. int ret;
  1817. u64 discarded_bytes = 0;
  1818. struct btrfs_bio *bbio = NULL;
  1819. /*
  1820. * Avoid races with device replace and make sure our bbio has devices
  1821. * associated to its stripes that don't go away while we are discarding.
  1822. */
  1823. btrfs_bio_counter_inc_blocked(fs_info);
  1824. /* Tell the block device(s) that the sectors can be discarded */
  1825. ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
  1826. &bbio, 0);
  1827. /* Error condition is -ENOMEM */
  1828. if (!ret) {
  1829. struct btrfs_bio_stripe *stripe = bbio->stripes;
  1830. int i;
  1831. for (i = 0; i < bbio->num_stripes; i++, stripe++) {
  1832. u64 bytes;
  1833. if (!stripe->dev->can_discard)
  1834. continue;
  1835. ret = btrfs_issue_discard(stripe->dev->bdev,
  1836. stripe->physical,
  1837. stripe->length,
  1838. &bytes);
  1839. if (!ret)
  1840. discarded_bytes += bytes;
  1841. else if (ret != -EOPNOTSUPP)
  1842. break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
  1843. /*
  1844. * Just in case we get back EOPNOTSUPP for some reason,
  1845. * just ignore the return value so we don't screw up
  1846. * people calling discard_extent.
  1847. */
  1848. ret = 0;
  1849. }
  1850. btrfs_put_bbio(bbio);
  1851. }
  1852. btrfs_bio_counter_dec(fs_info);
  1853. if (actual_bytes)
  1854. *actual_bytes = discarded_bytes;
  1855. if (ret == -EOPNOTSUPP)
  1856. ret = 0;
  1857. return ret;
  1858. }
  1859. /* Can return -ENOMEM */
  1860. int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
  1861. struct btrfs_fs_info *fs_info,
  1862. u64 bytenr, u64 num_bytes, u64 parent,
  1863. u64 root_objectid, u64 owner, u64 offset)
  1864. {
  1865. int ret;
  1866. BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
  1867. root_objectid == BTRFS_TREE_LOG_OBJECTID);
  1868. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1869. ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
  1870. num_bytes,
  1871. parent, root_objectid, (int)owner,
  1872. BTRFS_ADD_DELAYED_REF, NULL);
  1873. } else {
  1874. ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
  1875. num_bytes, parent, root_objectid,
  1876. owner, offset, 0,
  1877. BTRFS_ADD_DELAYED_REF);
  1878. }
  1879. return ret;
  1880. }
  1881. static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
  1882. struct btrfs_fs_info *fs_info,
  1883. struct btrfs_delayed_ref_node *node,
  1884. u64 parent, u64 root_objectid,
  1885. u64 owner, u64 offset, int refs_to_add,
  1886. struct btrfs_delayed_extent_op *extent_op)
  1887. {
  1888. struct btrfs_path *path;
  1889. struct extent_buffer *leaf;
  1890. struct btrfs_extent_item *item;
  1891. struct btrfs_key key;
  1892. u64 bytenr = node->bytenr;
  1893. u64 num_bytes = node->num_bytes;
  1894. u64 refs;
  1895. int ret;
  1896. path = btrfs_alloc_path();
  1897. if (!path)
  1898. return -ENOMEM;
  1899. path->reada = READA_FORWARD;
  1900. path->leave_spinning = 1;
  1901. /* this will setup the path even if it fails to insert the back ref */
  1902. ret = insert_inline_extent_backref(trans, fs_info->extent_root, path,
  1903. bytenr, num_bytes, parent,
  1904. root_objectid, owner, offset,
  1905. refs_to_add, extent_op);
  1906. if ((ret < 0 && ret != -EAGAIN) || !ret)
  1907. goto out;
  1908. /*
  1909. * Ok we had -EAGAIN which means we didn't have space to insert and
  1910. * inline extent ref, so just update the reference count and add a
  1911. * normal backref.
  1912. */
  1913. leaf = path->nodes[0];
  1914. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1915. item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1916. refs = btrfs_extent_refs(leaf, item);
  1917. btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
  1918. if (extent_op)
  1919. __run_delayed_extent_op(extent_op, leaf, item);
  1920. btrfs_mark_buffer_dirty(leaf);
  1921. btrfs_release_path(path);
  1922. path->reada = READA_FORWARD;
  1923. path->leave_spinning = 1;
  1924. /* now insert the actual backref */
  1925. ret = insert_extent_backref(trans, fs_info->extent_root,
  1926. path, bytenr, parent, root_objectid,
  1927. owner, offset, refs_to_add);
  1928. if (ret)
  1929. btrfs_abort_transaction(trans, ret);
  1930. out:
  1931. btrfs_free_path(path);
  1932. return ret;
  1933. }
  1934. static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
  1935. struct btrfs_fs_info *fs_info,
  1936. struct btrfs_delayed_ref_node *node,
  1937. struct btrfs_delayed_extent_op *extent_op,
  1938. int insert_reserved)
  1939. {
  1940. int ret = 0;
  1941. struct btrfs_delayed_data_ref *ref;
  1942. struct btrfs_key ins;
  1943. u64 parent = 0;
  1944. u64 ref_root = 0;
  1945. u64 flags = 0;
  1946. ins.objectid = node->bytenr;
  1947. ins.offset = node->num_bytes;
  1948. ins.type = BTRFS_EXTENT_ITEM_KEY;
  1949. ref = btrfs_delayed_node_to_data_ref(node);
  1950. trace_run_delayed_data_ref(fs_info, node, ref, node->action);
  1951. if (node->type == BTRFS_SHARED_DATA_REF_KEY)
  1952. parent = ref->parent;
  1953. ref_root = ref->root;
  1954. if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
  1955. if (extent_op)
  1956. flags |= extent_op->flags_to_set;
  1957. ret = alloc_reserved_file_extent(trans, fs_info,
  1958. parent, ref_root, flags,
  1959. ref->objectid, ref->offset,
  1960. &ins, node->ref_mod);
  1961. } else if (node->action == BTRFS_ADD_DELAYED_REF) {
  1962. ret = __btrfs_inc_extent_ref(trans, fs_info, node, parent,
  1963. ref_root, ref->objectid,
  1964. ref->offset, node->ref_mod,
  1965. extent_op);
  1966. } else if (node->action == BTRFS_DROP_DELAYED_REF) {
  1967. ret = __btrfs_free_extent(trans, fs_info, node, parent,
  1968. ref_root, ref->objectid,
  1969. ref->offset, node->ref_mod,
  1970. extent_op);
  1971. } else {
  1972. BUG();
  1973. }
  1974. return ret;
  1975. }
  1976. static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
  1977. struct extent_buffer *leaf,
  1978. struct btrfs_extent_item *ei)
  1979. {
  1980. u64 flags = btrfs_extent_flags(leaf, ei);
  1981. if (extent_op->update_flags) {
  1982. flags |= extent_op->flags_to_set;
  1983. btrfs_set_extent_flags(leaf, ei, flags);
  1984. }
  1985. if (extent_op->update_key) {
  1986. struct btrfs_tree_block_info *bi;
  1987. BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
  1988. bi = (struct btrfs_tree_block_info *)(ei + 1);
  1989. btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
  1990. }
  1991. }
  1992. static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
  1993. struct btrfs_fs_info *fs_info,
  1994. struct btrfs_delayed_ref_node *node,
  1995. struct btrfs_delayed_extent_op *extent_op)
  1996. {
  1997. struct btrfs_key key;
  1998. struct btrfs_path *path;
  1999. struct btrfs_extent_item *ei;
  2000. struct extent_buffer *leaf;
  2001. u32 item_size;
  2002. int ret;
  2003. int err = 0;
  2004. int metadata = !extent_op->is_data;
  2005. if (trans->aborted)
  2006. return 0;
  2007. if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
  2008. metadata = 0;
  2009. path = btrfs_alloc_path();
  2010. if (!path)
  2011. return -ENOMEM;
  2012. key.objectid = node->bytenr;
  2013. if (metadata) {
  2014. key.type = BTRFS_METADATA_ITEM_KEY;
  2015. key.offset = extent_op->level;
  2016. } else {
  2017. key.type = BTRFS_EXTENT_ITEM_KEY;
  2018. key.offset = node->num_bytes;
  2019. }
  2020. again:
  2021. path->reada = READA_FORWARD;
  2022. path->leave_spinning = 1;
  2023. ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
  2024. if (ret < 0) {
  2025. err = ret;
  2026. goto out;
  2027. }
  2028. if (ret > 0) {
  2029. if (metadata) {
  2030. if (path->slots[0] > 0) {
  2031. path->slots[0]--;
  2032. btrfs_item_key_to_cpu(path->nodes[0], &key,
  2033. path->slots[0]);
  2034. if (key.objectid == node->bytenr &&
  2035. key.type == BTRFS_EXTENT_ITEM_KEY &&
  2036. key.offset == node->num_bytes)
  2037. ret = 0;
  2038. }
  2039. if (ret > 0) {
  2040. btrfs_release_path(path);
  2041. metadata = 0;
  2042. key.objectid = node->bytenr;
  2043. key.offset = node->num_bytes;
  2044. key.type = BTRFS_EXTENT_ITEM_KEY;
  2045. goto again;
  2046. }
  2047. } else {
  2048. err = -EIO;
  2049. goto out;
  2050. }
  2051. }
  2052. leaf = path->nodes[0];
  2053. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  2054. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  2055. if (item_size < sizeof(*ei)) {
  2056. ret = convert_extent_item_v0(trans, fs_info->extent_root,
  2057. path, (u64)-1, 0);
  2058. if (ret < 0) {
  2059. err = ret;
  2060. goto out;
  2061. }
  2062. leaf = path->nodes[0];
  2063. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  2064. }
  2065. #endif
  2066. BUG_ON(item_size < sizeof(*ei));
  2067. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  2068. __run_delayed_extent_op(extent_op, leaf, ei);
  2069. btrfs_mark_buffer_dirty(leaf);
  2070. out:
  2071. btrfs_free_path(path);
  2072. return err;
  2073. }
  2074. static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
  2075. struct btrfs_fs_info *fs_info,
  2076. struct btrfs_delayed_ref_node *node,
  2077. struct btrfs_delayed_extent_op *extent_op,
  2078. int insert_reserved)
  2079. {
  2080. int ret = 0;
  2081. struct btrfs_delayed_tree_ref *ref;
  2082. struct btrfs_key ins;
  2083. u64 parent = 0;
  2084. u64 ref_root = 0;
  2085. bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
  2086. ref = btrfs_delayed_node_to_tree_ref(node);
  2087. trace_run_delayed_tree_ref(fs_info, node, ref, node->action);
  2088. if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
  2089. parent = ref->parent;
  2090. ref_root = ref->root;
  2091. ins.objectid = node->bytenr;
  2092. if (skinny_metadata) {
  2093. ins.offset = ref->level;
  2094. ins.type = BTRFS_METADATA_ITEM_KEY;
  2095. } else {
  2096. ins.offset = node->num_bytes;
  2097. ins.type = BTRFS_EXTENT_ITEM_KEY;
  2098. }
  2099. if (node->ref_mod != 1) {
  2100. btrfs_err(fs_info,
  2101. "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
  2102. node->bytenr, node->ref_mod, node->action, ref_root,
  2103. parent);
  2104. return -EIO;
  2105. }
  2106. if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
  2107. BUG_ON(!extent_op || !extent_op->update_flags);
  2108. ret = alloc_reserved_tree_block(trans, fs_info,
  2109. parent, ref_root,
  2110. extent_op->flags_to_set,
  2111. &extent_op->key,
  2112. ref->level, &ins);
  2113. } else if (node->action == BTRFS_ADD_DELAYED_REF) {
  2114. ret = __btrfs_inc_extent_ref(trans, fs_info, node,
  2115. parent, ref_root,
  2116. ref->level, 0, 1,
  2117. extent_op);
  2118. } else if (node->action == BTRFS_DROP_DELAYED_REF) {
  2119. ret = __btrfs_free_extent(trans, fs_info, node,
  2120. parent, ref_root,
  2121. ref->level, 0, 1, extent_op);
  2122. } else {
  2123. BUG();
  2124. }
  2125. return ret;
  2126. }
  2127. /* helper function to actually process a single delayed ref entry */
  2128. static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
  2129. struct btrfs_fs_info *fs_info,
  2130. struct btrfs_delayed_ref_node *node,
  2131. struct btrfs_delayed_extent_op *extent_op,
  2132. int insert_reserved)
  2133. {
  2134. int ret = 0;
  2135. if (trans->aborted) {
  2136. if (insert_reserved)
  2137. btrfs_pin_extent(fs_info, node->bytenr,
  2138. node->num_bytes, 1);
  2139. return 0;
  2140. }
  2141. if (btrfs_delayed_ref_is_head(node)) {
  2142. struct btrfs_delayed_ref_head *head;
  2143. /*
  2144. * we've hit the end of the chain and we were supposed
  2145. * to insert this extent into the tree. But, it got
  2146. * deleted before we ever needed to insert it, so all
  2147. * we have to do is clean up the accounting
  2148. */
  2149. BUG_ON(extent_op);
  2150. head = btrfs_delayed_node_to_head(node);
  2151. trace_run_delayed_ref_head(fs_info, node, head, node->action);
  2152. if (insert_reserved) {
  2153. btrfs_pin_extent(fs_info, node->bytenr,
  2154. node->num_bytes, 1);
  2155. if (head->is_data) {
  2156. ret = btrfs_del_csums(trans, fs_info,
  2157. node->bytenr,
  2158. node->num_bytes);
  2159. }
  2160. }
  2161. /* Also free its reserved qgroup space */
  2162. btrfs_qgroup_free_delayed_ref(fs_info, head->qgroup_ref_root,
  2163. head->qgroup_reserved);
  2164. return ret;
  2165. }
  2166. if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
  2167. node->type == BTRFS_SHARED_BLOCK_REF_KEY)
  2168. ret = run_delayed_tree_ref(trans, fs_info, node, extent_op,
  2169. insert_reserved);
  2170. else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
  2171. node->type == BTRFS_SHARED_DATA_REF_KEY)
  2172. ret = run_delayed_data_ref(trans, fs_info, node, extent_op,
  2173. insert_reserved);
  2174. else
  2175. BUG();
  2176. return ret;
  2177. }
  2178. static inline struct btrfs_delayed_ref_node *
  2179. select_delayed_ref(struct btrfs_delayed_ref_head *head)
  2180. {
  2181. struct btrfs_delayed_ref_node *ref;
  2182. if (list_empty(&head->ref_list))
  2183. return NULL;
  2184. /*
  2185. * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
  2186. * This is to prevent a ref count from going down to zero, which deletes
  2187. * the extent item from the extent tree, when there still are references
  2188. * to add, which would fail because they would not find the extent item.
  2189. */
  2190. if (!list_empty(&head->ref_add_list))
  2191. return list_first_entry(&head->ref_add_list,
  2192. struct btrfs_delayed_ref_node, add_list);
  2193. ref = list_first_entry(&head->ref_list, struct btrfs_delayed_ref_node,
  2194. list);
  2195. ASSERT(list_empty(&ref->add_list));
  2196. return ref;
  2197. }
  2198. /*
  2199. * Returns 0 on success or if called with an already aborted transaction.
  2200. * Returns -ENOMEM or -EIO on failure and will abort the transaction.
  2201. */
  2202. static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
  2203. struct btrfs_fs_info *fs_info,
  2204. unsigned long nr)
  2205. {
  2206. struct btrfs_delayed_ref_root *delayed_refs;
  2207. struct btrfs_delayed_ref_node *ref;
  2208. struct btrfs_delayed_ref_head *locked_ref = NULL;
  2209. struct btrfs_delayed_extent_op *extent_op;
  2210. ktime_t start = ktime_get();
  2211. int ret;
  2212. unsigned long count = 0;
  2213. unsigned long actual_count = 0;
  2214. int must_insert_reserved = 0;
  2215. delayed_refs = &trans->transaction->delayed_refs;
  2216. while (1) {
  2217. if (!locked_ref) {
  2218. if (count >= nr)
  2219. break;
  2220. spin_lock(&delayed_refs->lock);
  2221. locked_ref = btrfs_select_ref_head(trans);
  2222. if (!locked_ref) {
  2223. spin_unlock(&delayed_refs->lock);
  2224. break;
  2225. }
  2226. /* grab the lock that says we are going to process
  2227. * all the refs for this head */
  2228. ret = btrfs_delayed_ref_lock(trans, locked_ref);
  2229. spin_unlock(&delayed_refs->lock);
  2230. /*
  2231. * we may have dropped the spin lock to get the head
  2232. * mutex lock, and that might have given someone else
  2233. * time to free the head. If that's true, it has been
  2234. * removed from our list and we can move on.
  2235. */
  2236. if (ret == -EAGAIN) {
  2237. locked_ref = NULL;
  2238. count++;
  2239. continue;
  2240. }
  2241. }
  2242. /*
  2243. * We need to try and merge add/drops of the same ref since we
  2244. * can run into issues with relocate dropping the implicit ref
  2245. * and then it being added back again before the drop can
  2246. * finish. If we merged anything we need to re-loop so we can
  2247. * get a good ref.
  2248. * Or we can get node references of the same type that weren't
  2249. * merged when created due to bumps in the tree mod seq, and
  2250. * we need to merge them to prevent adding an inline extent
  2251. * backref before dropping it (triggering a BUG_ON at
  2252. * insert_inline_extent_backref()).
  2253. */
  2254. spin_lock(&locked_ref->lock);
  2255. btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
  2256. locked_ref);
  2257. /*
  2258. * locked_ref is the head node, so we have to go one
  2259. * node back for any delayed ref updates
  2260. */
  2261. ref = select_delayed_ref(locked_ref);
  2262. if (ref && ref->seq &&
  2263. btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
  2264. spin_unlock(&locked_ref->lock);
  2265. spin_lock(&delayed_refs->lock);
  2266. locked_ref->processing = 0;
  2267. delayed_refs->num_heads_ready++;
  2268. spin_unlock(&delayed_refs->lock);
  2269. btrfs_delayed_ref_unlock(locked_ref);
  2270. locked_ref = NULL;
  2271. cond_resched();
  2272. count++;
  2273. continue;
  2274. }
  2275. /*
  2276. * record the must insert reserved flag before we
  2277. * drop the spin lock.
  2278. */
  2279. must_insert_reserved = locked_ref->must_insert_reserved;
  2280. locked_ref->must_insert_reserved = 0;
  2281. extent_op = locked_ref->extent_op;
  2282. locked_ref->extent_op = NULL;
  2283. if (!ref) {
  2284. /* All delayed refs have been processed, Go ahead
  2285. * and send the head node to run_one_delayed_ref,
  2286. * so that any accounting fixes can happen
  2287. */
  2288. ref = &locked_ref->node;
  2289. if (extent_op && must_insert_reserved) {
  2290. btrfs_free_delayed_extent_op(extent_op);
  2291. extent_op = NULL;
  2292. }
  2293. if (extent_op) {
  2294. spin_unlock(&locked_ref->lock);
  2295. ret = run_delayed_extent_op(trans, fs_info,
  2296. ref, extent_op);
  2297. btrfs_free_delayed_extent_op(extent_op);
  2298. if (ret) {
  2299. /*
  2300. * Need to reset must_insert_reserved if
  2301. * there was an error so the abort stuff
  2302. * can cleanup the reserved space
  2303. * properly.
  2304. */
  2305. if (must_insert_reserved)
  2306. locked_ref->must_insert_reserved = 1;
  2307. spin_lock(&delayed_refs->lock);
  2308. locked_ref->processing = 0;
  2309. delayed_refs->num_heads_ready++;
  2310. spin_unlock(&delayed_refs->lock);
  2311. btrfs_debug(fs_info,
  2312. "run_delayed_extent_op returned %d",
  2313. ret);
  2314. btrfs_delayed_ref_unlock(locked_ref);
  2315. return ret;
  2316. }
  2317. continue;
  2318. }
  2319. /*
  2320. * Need to drop our head ref lock and re-acquire the
  2321. * delayed ref lock and then re-check to make sure
  2322. * nobody got added.
  2323. */
  2324. spin_unlock(&locked_ref->lock);
  2325. spin_lock(&delayed_refs->lock);
  2326. spin_lock(&locked_ref->lock);
  2327. if (!list_empty(&locked_ref->ref_list) ||
  2328. locked_ref->extent_op) {
  2329. spin_unlock(&locked_ref->lock);
  2330. spin_unlock(&delayed_refs->lock);
  2331. continue;
  2332. }
  2333. ref->in_tree = 0;
  2334. delayed_refs->num_heads--;
  2335. rb_erase(&locked_ref->href_node,
  2336. &delayed_refs->href_root);
  2337. spin_unlock(&delayed_refs->lock);
  2338. } else {
  2339. actual_count++;
  2340. ref->in_tree = 0;
  2341. list_del(&ref->list);
  2342. if (!list_empty(&ref->add_list))
  2343. list_del(&ref->add_list);
  2344. }
  2345. atomic_dec(&delayed_refs->num_entries);
  2346. if (!btrfs_delayed_ref_is_head(ref)) {
  2347. /*
  2348. * when we play the delayed ref, also correct the
  2349. * ref_mod on head
  2350. */
  2351. switch (ref->action) {
  2352. case BTRFS_ADD_DELAYED_REF:
  2353. case BTRFS_ADD_DELAYED_EXTENT:
  2354. locked_ref->node.ref_mod -= ref->ref_mod;
  2355. break;
  2356. case BTRFS_DROP_DELAYED_REF:
  2357. locked_ref->node.ref_mod += ref->ref_mod;
  2358. break;
  2359. default:
  2360. WARN_ON(1);
  2361. }
  2362. }
  2363. spin_unlock(&locked_ref->lock);
  2364. ret = run_one_delayed_ref(trans, fs_info, ref, extent_op,
  2365. must_insert_reserved);
  2366. btrfs_free_delayed_extent_op(extent_op);
  2367. if (ret) {
  2368. spin_lock(&delayed_refs->lock);
  2369. locked_ref->processing = 0;
  2370. delayed_refs->num_heads_ready++;
  2371. spin_unlock(&delayed_refs->lock);
  2372. btrfs_delayed_ref_unlock(locked_ref);
  2373. btrfs_put_delayed_ref(ref);
  2374. btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
  2375. ret);
  2376. return ret;
  2377. }
  2378. /*
  2379. * If this node is a head, that means all the refs in this head
  2380. * have been dealt with, and we will pick the next head to deal
  2381. * with, so we must unlock the head and drop it from the cluster
  2382. * list before we release it.
  2383. */
  2384. if (btrfs_delayed_ref_is_head(ref)) {
  2385. if (locked_ref->is_data &&
  2386. locked_ref->total_ref_mod < 0) {
  2387. spin_lock(&delayed_refs->lock);
  2388. delayed_refs->pending_csums -= ref->num_bytes;
  2389. spin_unlock(&delayed_refs->lock);
  2390. }
  2391. btrfs_delayed_ref_unlock(locked_ref);
  2392. locked_ref = NULL;
  2393. }
  2394. btrfs_put_delayed_ref(ref);
  2395. count++;
  2396. cond_resched();
  2397. }
  2398. /*
  2399. * We don't want to include ref heads since we can have empty ref heads
  2400. * and those will drastically skew our runtime down since we just do
  2401. * accounting, no actual extent tree updates.
  2402. */
  2403. if (actual_count > 0) {
  2404. u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
  2405. u64 avg;
  2406. /*
  2407. * We weigh the current average higher than our current runtime
  2408. * to avoid large swings in the average.
  2409. */
  2410. spin_lock(&delayed_refs->lock);
  2411. avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
  2412. fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
  2413. spin_unlock(&delayed_refs->lock);
  2414. }
  2415. return 0;
  2416. }
  2417. #ifdef SCRAMBLE_DELAYED_REFS
  2418. /*
  2419. * Normally delayed refs get processed in ascending bytenr order. This
  2420. * correlates in most cases to the order added. To expose dependencies on this
  2421. * order, we start to process the tree in the middle instead of the beginning
  2422. */
  2423. static u64 find_middle(struct rb_root *root)
  2424. {
  2425. struct rb_node *n = root->rb_node;
  2426. struct btrfs_delayed_ref_node *entry;
  2427. int alt = 1;
  2428. u64 middle;
  2429. u64 first = 0, last = 0;
  2430. n = rb_first(root);
  2431. if (n) {
  2432. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  2433. first = entry->bytenr;
  2434. }
  2435. n = rb_last(root);
  2436. if (n) {
  2437. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  2438. last = entry->bytenr;
  2439. }
  2440. n = root->rb_node;
  2441. while (n) {
  2442. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  2443. WARN_ON(!entry->in_tree);
  2444. middle = entry->bytenr;
  2445. if (alt)
  2446. n = n->rb_left;
  2447. else
  2448. n = n->rb_right;
  2449. alt = 1 - alt;
  2450. }
  2451. return middle;
  2452. }
  2453. #endif
  2454. static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
  2455. {
  2456. u64 num_bytes;
  2457. num_bytes = heads * (sizeof(struct btrfs_extent_item) +
  2458. sizeof(struct btrfs_extent_inline_ref));
  2459. if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
  2460. num_bytes += heads * sizeof(struct btrfs_tree_block_info);
  2461. /*
  2462. * We don't ever fill up leaves all the way so multiply by 2 just to be
  2463. * closer to what we're really going to want to use.
  2464. */
  2465. return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
  2466. }
  2467. /*
  2468. * Takes the number of bytes to be csumm'ed and figures out how many leaves it
  2469. * would require to store the csums for that many bytes.
  2470. */
  2471. u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
  2472. {
  2473. u64 csum_size;
  2474. u64 num_csums_per_leaf;
  2475. u64 num_csums;
  2476. csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
  2477. num_csums_per_leaf = div64_u64(csum_size,
  2478. (u64)btrfs_super_csum_size(fs_info->super_copy));
  2479. num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
  2480. num_csums += num_csums_per_leaf - 1;
  2481. num_csums = div64_u64(num_csums, num_csums_per_leaf);
  2482. return num_csums;
  2483. }
  2484. int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
  2485. struct btrfs_fs_info *fs_info)
  2486. {
  2487. struct btrfs_block_rsv *global_rsv;
  2488. u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
  2489. u64 csum_bytes = trans->transaction->delayed_refs.pending_csums;
  2490. u64 num_dirty_bgs = trans->transaction->num_dirty_bgs;
  2491. u64 num_bytes, num_dirty_bgs_bytes;
  2492. int ret = 0;
  2493. num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
  2494. num_heads = heads_to_leaves(fs_info, num_heads);
  2495. if (num_heads > 1)
  2496. num_bytes += (num_heads - 1) * fs_info->nodesize;
  2497. num_bytes <<= 1;
  2498. num_bytes += btrfs_csum_bytes_to_leaves(fs_info, csum_bytes) *
  2499. fs_info->nodesize;
  2500. num_dirty_bgs_bytes = btrfs_calc_trans_metadata_size(fs_info,
  2501. num_dirty_bgs);
  2502. global_rsv = &fs_info->global_block_rsv;
  2503. /*
  2504. * If we can't allocate any more chunks lets make sure we have _lots_ of
  2505. * wiggle room since running delayed refs can create more delayed refs.
  2506. */
  2507. if (global_rsv->space_info->full) {
  2508. num_dirty_bgs_bytes <<= 1;
  2509. num_bytes <<= 1;
  2510. }
  2511. spin_lock(&global_rsv->lock);
  2512. if (global_rsv->reserved <= num_bytes + num_dirty_bgs_bytes)
  2513. ret = 1;
  2514. spin_unlock(&global_rsv->lock);
  2515. return ret;
  2516. }
  2517. int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
  2518. struct btrfs_fs_info *fs_info)
  2519. {
  2520. u64 num_entries =
  2521. atomic_read(&trans->transaction->delayed_refs.num_entries);
  2522. u64 avg_runtime;
  2523. u64 val;
  2524. smp_mb();
  2525. avg_runtime = fs_info->avg_delayed_ref_runtime;
  2526. val = num_entries * avg_runtime;
  2527. if (val >= NSEC_PER_SEC)
  2528. return 1;
  2529. if (val >= NSEC_PER_SEC / 2)
  2530. return 2;
  2531. return btrfs_check_space_for_delayed_refs(trans, fs_info);
  2532. }
  2533. struct async_delayed_refs {
  2534. struct btrfs_root *root;
  2535. u64 transid;
  2536. int count;
  2537. int error;
  2538. int sync;
  2539. struct completion wait;
  2540. struct btrfs_work work;
  2541. };
  2542. static inline struct async_delayed_refs *
  2543. to_async_delayed_refs(struct btrfs_work *work)
  2544. {
  2545. return container_of(work, struct async_delayed_refs, work);
  2546. }
  2547. static void delayed_ref_async_start(struct btrfs_work *work)
  2548. {
  2549. struct async_delayed_refs *async = to_async_delayed_refs(work);
  2550. struct btrfs_trans_handle *trans;
  2551. struct btrfs_fs_info *fs_info = async->root->fs_info;
  2552. int ret;
  2553. /* if the commit is already started, we don't need to wait here */
  2554. if (btrfs_transaction_blocked(fs_info))
  2555. goto done;
  2556. trans = btrfs_join_transaction(async->root);
  2557. if (IS_ERR(trans)) {
  2558. async->error = PTR_ERR(trans);
  2559. goto done;
  2560. }
  2561. /*
  2562. * trans->sync means that when we call end_transaction, we won't
  2563. * wait on delayed refs
  2564. */
  2565. trans->sync = true;
  2566. /* Don't bother flushing if we got into a different transaction */
  2567. if (trans->transid > async->transid)
  2568. goto end;
  2569. ret = btrfs_run_delayed_refs(trans, fs_info, async->count);
  2570. if (ret)
  2571. async->error = ret;
  2572. end:
  2573. ret = btrfs_end_transaction(trans);
  2574. if (ret && !async->error)
  2575. async->error = ret;
  2576. done:
  2577. if (async->sync)
  2578. complete(&async->wait);
  2579. else
  2580. kfree(async);
  2581. }
  2582. int btrfs_async_run_delayed_refs(struct btrfs_fs_info *fs_info,
  2583. unsigned long count, u64 transid, int wait)
  2584. {
  2585. struct async_delayed_refs *async;
  2586. int ret;
  2587. async = kmalloc(sizeof(*async), GFP_NOFS);
  2588. if (!async)
  2589. return -ENOMEM;
  2590. async->root = fs_info->tree_root;
  2591. async->count = count;
  2592. async->error = 0;
  2593. async->transid = transid;
  2594. if (wait)
  2595. async->sync = 1;
  2596. else
  2597. async->sync = 0;
  2598. init_completion(&async->wait);
  2599. btrfs_init_work(&async->work, btrfs_extent_refs_helper,
  2600. delayed_ref_async_start, NULL, NULL);
  2601. btrfs_queue_work(fs_info->extent_workers, &async->work);
  2602. if (wait) {
  2603. wait_for_completion(&async->wait);
  2604. ret = async->error;
  2605. kfree(async);
  2606. return ret;
  2607. }
  2608. return 0;
  2609. }
  2610. /*
  2611. * this starts processing the delayed reference count updates and
  2612. * extent insertions we have queued up so far. count can be
  2613. * 0, which means to process everything in the tree at the start
  2614. * of the run (but not newly added entries), or it can be some target
  2615. * number you'd like to process.
  2616. *
  2617. * Returns 0 on success or if called with an aborted transaction
  2618. * Returns <0 on error and aborts the transaction
  2619. */
  2620. int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
  2621. struct btrfs_fs_info *fs_info, unsigned long count)
  2622. {
  2623. struct rb_node *node;
  2624. struct btrfs_delayed_ref_root *delayed_refs;
  2625. struct btrfs_delayed_ref_head *head;
  2626. int ret;
  2627. int run_all = count == (unsigned long)-1;
  2628. bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
  2629. /* We'll clean this up in btrfs_cleanup_transaction */
  2630. if (trans->aborted)
  2631. return 0;
  2632. if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
  2633. return 0;
  2634. delayed_refs = &trans->transaction->delayed_refs;
  2635. if (count == 0)
  2636. count = atomic_read(&delayed_refs->num_entries) * 2;
  2637. again:
  2638. #ifdef SCRAMBLE_DELAYED_REFS
  2639. delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
  2640. #endif
  2641. trans->can_flush_pending_bgs = false;
  2642. ret = __btrfs_run_delayed_refs(trans, fs_info, count);
  2643. if (ret < 0) {
  2644. btrfs_abort_transaction(trans, ret);
  2645. return ret;
  2646. }
  2647. if (run_all) {
  2648. if (!list_empty(&trans->new_bgs))
  2649. btrfs_create_pending_block_groups(trans, fs_info);
  2650. spin_lock(&delayed_refs->lock);
  2651. node = rb_first(&delayed_refs->href_root);
  2652. if (!node) {
  2653. spin_unlock(&delayed_refs->lock);
  2654. goto out;
  2655. }
  2656. while (node) {
  2657. head = rb_entry(node, struct btrfs_delayed_ref_head,
  2658. href_node);
  2659. if (btrfs_delayed_ref_is_head(&head->node)) {
  2660. struct btrfs_delayed_ref_node *ref;
  2661. ref = &head->node;
  2662. atomic_inc(&ref->refs);
  2663. spin_unlock(&delayed_refs->lock);
  2664. /*
  2665. * Mutex was contended, block until it's
  2666. * released and try again
  2667. */
  2668. mutex_lock(&head->mutex);
  2669. mutex_unlock(&head->mutex);
  2670. btrfs_put_delayed_ref(ref);
  2671. cond_resched();
  2672. goto again;
  2673. } else {
  2674. WARN_ON(1);
  2675. }
  2676. node = rb_next(node);
  2677. }
  2678. spin_unlock(&delayed_refs->lock);
  2679. cond_resched();
  2680. goto again;
  2681. }
  2682. out:
  2683. assert_qgroups_uptodate(trans);
  2684. trans->can_flush_pending_bgs = can_flush_pending_bgs;
  2685. return 0;
  2686. }
  2687. int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
  2688. struct btrfs_fs_info *fs_info,
  2689. u64 bytenr, u64 num_bytes, u64 flags,
  2690. int level, int is_data)
  2691. {
  2692. struct btrfs_delayed_extent_op *extent_op;
  2693. int ret;
  2694. extent_op = btrfs_alloc_delayed_extent_op();
  2695. if (!extent_op)
  2696. return -ENOMEM;
  2697. extent_op->flags_to_set = flags;
  2698. extent_op->update_flags = true;
  2699. extent_op->update_key = false;
  2700. extent_op->is_data = is_data ? true : false;
  2701. extent_op->level = level;
  2702. ret = btrfs_add_delayed_extent_op(fs_info, trans, bytenr,
  2703. num_bytes, extent_op);
  2704. if (ret)
  2705. btrfs_free_delayed_extent_op(extent_op);
  2706. return ret;
  2707. }
  2708. static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
  2709. struct btrfs_root *root,
  2710. struct btrfs_path *path,
  2711. u64 objectid, u64 offset, u64 bytenr)
  2712. {
  2713. struct btrfs_delayed_ref_head *head;
  2714. struct btrfs_delayed_ref_node *ref;
  2715. struct btrfs_delayed_data_ref *data_ref;
  2716. struct btrfs_delayed_ref_root *delayed_refs;
  2717. int ret = 0;
  2718. delayed_refs = &trans->transaction->delayed_refs;
  2719. spin_lock(&delayed_refs->lock);
  2720. head = btrfs_find_delayed_ref_head(trans, bytenr);
  2721. if (!head) {
  2722. spin_unlock(&delayed_refs->lock);
  2723. return 0;
  2724. }
  2725. if (!mutex_trylock(&head->mutex)) {
  2726. atomic_inc(&head->node.refs);
  2727. spin_unlock(&delayed_refs->lock);
  2728. btrfs_release_path(path);
  2729. /*
  2730. * Mutex was contended, block until it's released and let
  2731. * caller try again
  2732. */
  2733. mutex_lock(&head->mutex);
  2734. mutex_unlock(&head->mutex);
  2735. btrfs_put_delayed_ref(&head->node);
  2736. return -EAGAIN;
  2737. }
  2738. spin_unlock(&delayed_refs->lock);
  2739. spin_lock(&head->lock);
  2740. list_for_each_entry(ref, &head->ref_list, list) {
  2741. /* If it's a shared ref we know a cross reference exists */
  2742. if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
  2743. ret = 1;
  2744. break;
  2745. }
  2746. data_ref = btrfs_delayed_node_to_data_ref(ref);
  2747. /*
  2748. * If our ref doesn't match the one we're currently looking at
  2749. * then we have a cross reference.
  2750. */
  2751. if (data_ref->root != root->root_key.objectid ||
  2752. data_ref->objectid != objectid ||
  2753. data_ref->offset != offset) {
  2754. ret = 1;
  2755. break;
  2756. }
  2757. }
  2758. spin_unlock(&head->lock);
  2759. mutex_unlock(&head->mutex);
  2760. return ret;
  2761. }
  2762. static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
  2763. struct btrfs_root *root,
  2764. struct btrfs_path *path,
  2765. u64 objectid, u64 offset, u64 bytenr)
  2766. {
  2767. struct btrfs_fs_info *fs_info = root->fs_info;
  2768. struct btrfs_root *extent_root = fs_info->extent_root;
  2769. struct extent_buffer *leaf;
  2770. struct btrfs_extent_data_ref *ref;
  2771. struct btrfs_extent_inline_ref *iref;
  2772. struct btrfs_extent_item *ei;
  2773. struct btrfs_key key;
  2774. u32 item_size;
  2775. int ret;
  2776. key.objectid = bytenr;
  2777. key.offset = (u64)-1;
  2778. key.type = BTRFS_EXTENT_ITEM_KEY;
  2779. ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
  2780. if (ret < 0)
  2781. goto out;
  2782. BUG_ON(ret == 0); /* Corruption */
  2783. ret = -ENOENT;
  2784. if (path->slots[0] == 0)
  2785. goto out;
  2786. path->slots[0]--;
  2787. leaf = path->nodes[0];
  2788. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  2789. if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
  2790. goto out;
  2791. ret = 1;
  2792. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  2793. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  2794. if (item_size < sizeof(*ei)) {
  2795. WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
  2796. goto out;
  2797. }
  2798. #endif
  2799. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  2800. if (item_size != sizeof(*ei) +
  2801. btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
  2802. goto out;
  2803. if (btrfs_extent_generation(leaf, ei) <=
  2804. btrfs_root_last_snapshot(&root->root_item))
  2805. goto out;
  2806. iref = (struct btrfs_extent_inline_ref *)(ei + 1);
  2807. if (btrfs_extent_inline_ref_type(leaf, iref) !=
  2808. BTRFS_EXTENT_DATA_REF_KEY)
  2809. goto out;
  2810. ref = (struct btrfs_extent_data_ref *)(&iref->offset);
  2811. if (btrfs_extent_refs(leaf, ei) !=
  2812. btrfs_extent_data_ref_count(leaf, ref) ||
  2813. btrfs_extent_data_ref_root(leaf, ref) !=
  2814. root->root_key.objectid ||
  2815. btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
  2816. btrfs_extent_data_ref_offset(leaf, ref) != offset)
  2817. goto out;
  2818. ret = 0;
  2819. out:
  2820. return ret;
  2821. }
  2822. int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
  2823. struct btrfs_root *root,
  2824. u64 objectid, u64 offset, u64 bytenr)
  2825. {
  2826. struct btrfs_path *path;
  2827. int ret;
  2828. int ret2;
  2829. path = btrfs_alloc_path();
  2830. if (!path)
  2831. return -ENOENT;
  2832. do {
  2833. ret = check_committed_ref(trans, root, path, objectid,
  2834. offset, bytenr);
  2835. if (ret && ret != -ENOENT)
  2836. goto out;
  2837. ret2 = check_delayed_ref(trans, root, path, objectid,
  2838. offset, bytenr);
  2839. } while (ret2 == -EAGAIN);
  2840. if (ret2 && ret2 != -ENOENT) {
  2841. ret = ret2;
  2842. goto out;
  2843. }
  2844. if (ret != -ENOENT || ret2 != -ENOENT)
  2845. ret = 0;
  2846. out:
  2847. btrfs_free_path(path);
  2848. if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
  2849. WARN_ON(ret > 0);
  2850. return ret;
  2851. }
  2852. static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
  2853. struct btrfs_root *root,
  2854. struct extent_buffer *buf,
  2855. int full_backref, int inc)
  2856. {
  2857. struct btrfs_fs_info *fs_info = root->fs_info;
  2858. u64 bytenr;
  2859. u64 num_bytes;
  2860. u64 parent;
  2861. u64 ref_root;
  2862. u32 nritems;
  2863. struct btrfs_key key;
  2864. struct btrfs_file_extent_item *fi;
  2865. int i;
  2866. int level;
  2867. int ret = 0;
  2868. int (*process_func)(struct btrfs_trans_handle *,
  2869. struct btrfs_fs_info *,
  2870. u64, u64, u64, u64, u64, u64);
  2871. if (btrfs_is_testing(fs_info))
  2872. return 0;
  2873. ref_root = btrfs_header_owner(buf);
  2874. nritems = btrfs_header_nritems(buf);
  2875. level = btrfs_header_level(buf);
  2876. if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
  2877. return 0;
  2878. if (inc)
  2879. process_func = btrfs_inc_extent_ref;
  2880. else
  2881. process_func = btrfs_free_extent;
  2882. if (full_backref)
  2883. parent = buf->start;
  2884. else
  2885. parent = 0;
  2886. for (i = 0; i < nritems; i++) {
  2887. if (level == 0) {
  2888. btrfs_item_key_to_cpu(buf, &key, i);
  2889. if (key.type != BTRFS_EXTENT_DATA_KEY)
  2890. continue;
  2891. fi = btrfs_item_ptr(buf, i,
  2892. struct btrfs_file_extent_item);
  2893. if (btrfs_file_extent_type(buf, fi) ==
  2894. BTRFS_FILE_EXTENT_INLINE)
  2895. continue;
  2896. bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
  2897. if (bytenr == 0)
  2898. continue;
  2899. num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
  2900. key.offset -= btrfs_file_extent_offset(buf, fi);
  2901. ret = process_func(trans, fs_info, bytenr, num_bytes,
  2902. parent, ref_root, key.objectid,
  2903. key.offset);
  2904. if (ret)
  2905. goto fail;
  2906. } else {
  2907. bytenr = btrfs_node_blockptr(buf, i);
  2908. num_bytes = fs_info->nodesize;
  2909. ret = process_func(trans, fs_info, bytenr, num_bytes,
  2910. parent, ref_root, level - 1, 0);
  2911. if (ret)
  2912. goto fail;
  2913. }
  2914. }
  2915. return 0;
  2916. fail:
  2917. return ret;
  2918. }
  2919. int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  2920. struct extent_buffer *buf, int full_backref)
  2921. {
  2922. return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
  2923. }
  2924. int btrfs_dec_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, 0);
  2928. }
  2929. static int write_one_cache_group(struct btrfs_trans_handle *trans,
  2930. struct btrfs_fs_info *fs_info,
  2931. struct btrfs_path *path,
  2932. struct btrfs_block_group_cache *cache)
  2933. {
  2934. int ret;
  2935. struct btrfs_root *extent_root = fs_info->extent_root;
  2936. unsigned long bi;
  2937. struct extent_buffer *leaf;
  2938. ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
  2939. if (ret) {
  2940. if (ret > 0)
  2941. ret = -ENOENT;
  2942. goto fail;
  2943. }
  2944. leaf = path->nodes[0];
  2945. bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
  2946. write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
  2947. btrfs_mark_buffer_dirty(leaf);
  2948. fail:
  2949. btrfs_release_path(path);
  2950. return ret;
  2951. }
  2952. static struct btrfs_block_group_cache *
  2953. next_block_group(struct btrfs_fs_info *fs_info,
  2954. struct btrfs_block_group_cache *cache)
  2955. {
  2956. struct rb_node *node;
  2957. spin_lock(&fs_info->block_group_cache_lock);
  2958. /* If our block group was removed, we need a full search. */
  2959. if (RB_EMPTY_NODE(&cache->cache_node)) {
  2960. const u64 next_bytenr = cache->key.objectid + cache->key.offset;
  2961. spin_unlock(&fs_info->block_group_cache_lock);
  2962. btrfs_put_block_group(cache);
  2963. cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
  2964. }
  2965. node = rb_next(&cache->cache_node);
  2966. btrfs_put_block_group(cache);
  2967. if (node) {
  2968. cache = rb_entry(node, struct btrfs_block_group_cache,
  2969. cache_node);
  2970. btrfs_get_block_group(cache);
  2971. } else
  2972. cache = NULL;
  2973. spin_unlock(&fs_info->block_group_cache_lock);
  2974. return cache;
  2975. }
  2976. static int cache_save_setup(struct btrfs_block_group_cache *block_group,
  2977. struct btrfs_trans_handle *trans,
  2978. struct btrfs_path *path)
  2979. {
  2980. struct btrfs_fs_info *fs_info = block_group->fs_info;
  2981. struct btrfs_root *root = fs_info->tree_root;
  2982. struct inode *inode = NULL;
  2983. u64 alloc_hint = 0;
  2984. int dcs = BTRFS_DC_ERROR;
  2985. u64 num_pages = 0;
  2986. int retries = 0;
  2987. int ret = 0;
  2988. /*
  2989. * If this block group is smaller than 100 megs don't bother caching the
  2990. * block group.
  2991. */
  2992. if (block_group->key.offset < (100 * SZ_1M)) {
  2993. spin_lock(&block_group->lock);
  2994. block_group->disk_cache_state = BTRFS_DC_WRITTEN;
  2995. spin_unlock(&block_group->lock);
  2996. return 0;
  2997. }
  2998. if (trans->aborted)
  2999. return 0;
  3000. again:
  3001. inode = lookup_free_space_inode(root, block_group, path);
  3002. if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
  3003. ret = PTR_ERR(inode);
  3004. btrfs_release_path(path);
  3005. goto out;
  3006. }
  3007. if (IS_ERR(inode)) {
  3008. BUG_ON(retries);
  3009. retries++;
  3010. if (block_group->ro)
  3011. goto out_free;
  3012. ret = create_free_space_inode(root, trans, block_group, path);
  3013. if (ret)
  3014. goto out_free;
  3015. goto again;
  3016. }
  3017. /* We've already setup this transaction, go ahead and exit */
  3018. if (block_group->cache_generation == trans->transid &&
  3019. i_size_read(inode)) {
  3020. dcs = BTRFS_DC_SETUP;
  3021. goto out_put;
  3022. }
  3023. /*
  3024. * We want to set the generation to 0, that way if anything goes wrong
  3025. * from here on out we know not to trust this cache when we load up next
  3026. * time.
  3027. */
  3028. BTRFS_I(inode)->generation = 0;
  3029. ret = btrfs_update_inode(trans, root, inode);
  3030. if (ret) {
  3031. /*
  3032. * So theoretically we could recover from this, simply set the
  3033. * super cache generation to 0 so we know to invalidate the
  3034. * cache, but then we'd have to keep track of the block groups
  3035. * that fail this way so we know we _have_ to reset this cache
  3036. * before the next commit or risk reading stale cache. So to
  3037. * limit our exposure to horrible edge cases lets just abort the
  3038. * transaction, this only happens in really bad situations
  3039. * anyway.
  3040. */
  3041. btrfs_abort_transaction(trans, ret);
  3042. goto out_put;
  3043. }
  3044. WARN_ON(ret);
  3045. if (i_size_read(inode) > 0) {
  3046. ret = btrfs_check_trunc_cache_free_space(fs_info,
  3047. &fs_info->global_block_rsv);
  3048. if (ret)
  3049. goto out_put;
  3050. ret = btrfs_truncate_free_space_cache(root, trans, NULL, inode);
  3051. if (ret)
  3052. goto out_put;
  3053. }
  3054. spin_lock(&block_group->lock);
  3055. if (block_group->cached != BTRFS_CACHE_FINISHED ||
  3056. !btrfs_test_opt(fs_info, SPACE_CACHE)) {
  3057. /*
  3058. * don't bother trying to write stuff out _if_
  3059. * a) we're not cached,
  3060. * b) we're with nospace_cache mount option.
  3061. */
  3062. dcs = BTRFS_DC_WRITTEN;
  3063. spin_unlock(&block_group->lock);
  3064. goto out_put;
  3065. }
  3066. spin_unlock(&block_group->lock);
  3067. /*
  3068. * We hit an ENOSPC when setting up the cache in this transaction, just
  3069. * skip doing the setup, we've already cleared the cache so we're safe.
  3070. */
  3071. if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
  3072. ret = -ENOSPC;
  3073. goto out_put;
  3074. }
  3075. /*
  3076. * Try to preallocate enough space based on how big the block group is.
  3077. * Keep in mind this has to include any pinned space which could end up
  3078. * taking up quite a bit since it's not folded into the other space
  3079. * cache.
  3080. */
  3081. num_pages = div_u64(block_group->key.offset, SZ_256M);
  3082. if (!num_pages)
  3083. num_pages = 1;
  3084. num_pages *= 16;
  3085. num_pages *= PAGE_SIZE;
  3086. ret = btrfs_check_data_free_space(inode, 0, num_pages);
  3087. if (ret)
  3088. goto out_put;
  3089. ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
  3090. num_pages, num_pages,
  3091. &alloc_hint);
  3092. /*
  3093. * Our cache requires contiguous chunks so that we don't modify a bunch
  3094. * of metadata or split extents when writing the cache out, which means
  3095. * we can enospc if we are heavily fragmented in addition to just normal
  3096. * out of space conditions. So if we hit this just skip setting up any
  3097. * other block groups for this transaction, maybe we'll unpin enough
  3098. * space the next time around.
  3099. */
  3100. if (!ret)
  3101. dcs = BTRFS_DC_SETUP;
  3102. else if (ret == -ENOSPC)
  3103. set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
  3104. out_put:
  3105. iput(inode);
  3106. out_free:
  3107. btrfs_release_path(path);
  3108. out:
  3109. spin_lock(&block_group->lock);
  3110. if (!ret && dcs == BTRFS_DC_SETUP)
  3111. block_group->cache_generation = trans->transid;
  3112. block_group->disk_cache_state = dcs;
  3113. spin_unlock(&block_group->lock);
  3114. return ret;
  3115. }
  3116. int btrfs_setup_space_cache(struct btrfs_trans_handle *trans,
  3117. struct btrfs_fs_info *fs_info)
  3118. {
  3119. struct btrfs_block_group_cache *cache, *tmp;
  3120. struct btrfs_transaction *cur_trans = trans->transaction;
  3121. struct btrfs_path *path;
  3122. if (list_empty(&cur_trans->dirty_bgs) ||
  3123. !btrfs_test_opt(fs_info, SPACE_CACHE))
  3124. return 0;
  3125. path = btrfs_alloc_path();
  3126. if (!path)
  3127. return -ENOMEM;
  3128. /* Could add new block groups, use _safe just in case */
  3129. list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
  3130. dirty_list) {
  3131. if (cache->disk_cache_state == BTRFS_DC_CLEAR)
  3132. cache_save_setup(cache, trans, path);
  3133. }
  3134. btrfs_free_path(path);
  3135. return 0;
  3136. }
  3137. /*
  3138. * transaction commit does final block group cache writeback during a
  3139. * critical section where nothing is allowed to change the FS. This is
  3140. * required in order for the cache to actually match the block group,
  3141. * but can introduce a lot of latency into the commit.
  3142. *
  3143. * So, btrfs_start_dirty_block_groups is here to kick off block group
  3144. * cache IO. There's a chance we'll have to redo some of it if the
  3145. * block group changes again during the commit, but it greatly reduces
  3146. * the commit latency by getting rid of the easy block groups while
  3147. * we're still allowing others to join the commit.
  3148. */
  3149. int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans,
  3150. struct btrfs_fs_info *fs_info)
  3151. {
  3152. struct btrfs_block_group_cache *cache;
  3153. struct btrfs_transaction *cur_trans = trans->transaction;
  3154. int ret = 0;
  3155. int should_put;
  3156. struct btrfs_path *path = NULL;
  3157. LIST_HEAD(dirty);
  3158. struct list_head *io = &cur_trans->io_bgs;
  3159. int num_started = 0;
  3160. int loops = 0;
  3161. spin_lock(&cur_trans->dirty_bgs_lock);
  3162. if (list_empty(&cur_trans->dirty_bgs)) {
  3163. spin_unlock(&cur_trans->dirty_bgs_lock);
  3164. return 0;
  3165. }
  3166. list_splice_init(&cur_trans->dirty_bgs, &dirty);
  3167. spin_unlock(&cur_trans->dirty_bgs_lock);
  3168. again:
  3169. /*
  3170. * make sure all the block groups on our dirty list actually
  3171. * exist
  3172. */
  3173. btrfs_create_pending_block_groups(trans, fs_info);
  3174. if (!path) {
  3175. path = btrfs_alloc_path();
  3176. if (!path)
  3177. return -ENOMEM;
  3178. }
  3179. /*
  3180. * cache_write_mutex is here only to save us from balance or automatic
  3181. * removal of empty block groups deleting this block group while we are
  3182. * writing out the cache
  3183. */
  3184. mutex_lock(&trans->transaction->cache_write_mutex);
  3185. while (!list_empty(&dirty)) {
  3186. cache = list_first_entry(&dirty,
  3187. struct btrfs_block_group_cache,
  3188. dirty_list);
  3189. /*
  3190. * this can happen if something re-dirties a block
  3191. * group that is already under IO. Just wait for it to
  3192. * finish and then do it all again
  3193. */
  3194. if (!list_empty(&cache->io_list)) {
  3195. list_del_init(&cache->io_list);
  3196. btrfs_wait_cache_io(trans, cache, path);
  3197. btrfs_put_block_group(cache);
  3198. }
  3199. /*
  3200. * btrfs_wait_cache_io uses the cache->dirty_list to decide
  3201. * if it should update the cache_state. Don't delete
  3202. * until after we wait.
  3203. *
  3204. * Since we're not running in the commit critical section
  3205. * we need the dirty_bgs_lock to protect from update_block_group
  3206. */
  3207. spin_lock(&cur_trans->dirty_bgs_lock);
  3208. list_del_init(&cache->dirty_list);
  3209. spin_unlock(&cur_trans->dirty_bgs_lock);
  3210. should_put = 1;
  3211. cache_save_setup(cache, trans, path);
  3212. if (cache->disk_cache_state == BTRFS_DC_SETUP) {
  3213. cache->io_ctl.inode = NULL;
  3214. ret = btrfs_write_out_cache(fs_info, trans,
  3215. cache, path);
  3216. if (ret == 0 && cache->io_ctl.inode) {
  3217. num_started++;
  3218. should_put = 0;
  3219. /*
  3220. * the cache_write_mutex is protecting
  3221. * the io_list
  3222. */
  3223. list_add_tail(&cache->io_list, io);
  3224. } else {
  3225. /*
  3226. * if we failed to write the cache, the
  3227. * generation will be bad and life goes on
  3228. */
  3229. ret = 0;
  3230. }
  3231. }
  3232. if (!ret) {
  3233. ret = write_one_cache_group(trans, fs_info,
  3234. path, cache);
  3235. /*
  3236. * Our block group might still be attached to the list
  3237. * of new block groups in the transaction handle of some
  3238. * other task (struct btrfs_trans_handle->new_bgs). This
  3239. * means its block group item isn't yet in the extent
  3240. * tree. If this happens ignore the error, as we will
  3241. * try again later in the critical section of the
  3242. * transaction commit.
  3243. */
  3244. if (ret == -ENOENT) {
  3245. ret = 0;
  3246. spin_lock(&cur_trans->dirty_bgs_lock);
  3247. if (list_empty(&cache->dirty_list)) {
  3248. list_add_tail(&cache->dirty_list,
  3249. &cur_trans->dirty_bgs);
  3250. btrfs_get_block_group(cache);
  3251. }
  3252. spin_unlock(&cur_trans->dirty_bgs_lock);
  3253. } else if (ret) {
  3254. btrfs_abort_transaction(trans, ret);
  3255. }
  3256. }
  3257. /* if its not on the io list, we need to put the block group */
  3258. if (should_put)
  3259. btrfs_put_block_group(cache);
  3260. if (ret)
  3261. break;
  3262. /*
  3263. * Avoid blocking other tasks for too long. It might even save
  3264. * us from writing caches for block groups that are going to be
  3265. * removed.
  3266. */
  3267. mutex_unlock(&trans->transaction->cache_write_mutex);
  3268. mutex_lock(&trans->transaction->cache_write_mutex);
  3269. }
  3270. mutex_unlock(&trans->transaction->cache_write_mutex);
  3271. /*
  3272. * go through delayed refs for all the stuff we've just kicked off
  3273. * and then loop back (just once)
  3274. */
  3275. ret = btrfs_run_delayed_refs(trans, fs_info, 0);
  3276. if (!ret && loops == 0) {
  3277. loops++;
  3278. spin_lock(&cur_trans->dirty_bgs_lock);
  3279. list_splice_init(&cur_trans->dirty_bgs, &dirty);
  3280. /*
  3281. * dirty_bgs_lock protects us from concurrent block group
  3282. * deletes too (not just cache_write_mutex).
  3283. */
  3284. if (!list_empty(&dirty)) {
  3285. spin_unlock(&cur_trans->dirty_bgs_lock);
  3286. goto again;
  3287. }
  3288. spin_unlock(&cur_trans->dirty_bgs_lock);
  3289. } else if (ret < 0) {
  3290. btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
  3291. }
  3292. btrfs_free_path(path);
  3293. return ret;
  3294. }
  3295. int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
  3296. struct btrfs_fs_info *fs_info)
  3297. {
  3298. struct btrfs_block_group_cache *cache;
  3299. struct btrfs_transaction *cur_trans = trans->transaction;
  3300. int ret = 0;
  3301. int should_put;
  3302. struct btrfs_path *path;
  3303. struct list_head *io = &cur_trans->io_bgs;
  3304. int num_started = 0;
  3305. path = btrfs_alloc_path();
  3306. if (!path)
  3307. return -ENOMEM;
  3308. /*
  3309. * Even though we are in the critical section of the transaction commit,
  3310. * we can still have concurrent tasks adding elements to this
  3311. * transaction's list of dirty block groups. These tasks correspond to
  3312. * endio free space workers started when writeback finishes for a
  3313. * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
  3314. * allocate new block groups as a result of COWing nodes of the root
  3315. * tree when updating the free space inode. The writeback for the space
  3316. * caches is triggered by an earlier call to
  3317. * btrfs_start_dirty_block_groups() and iterations of the following
  3318. * loop.
  3319. * Also we want to do the cache_save_setup first and then run the
  3320. * delayed refs to make sure we have the best chance at doing this all
  3321. * in one shot.
  3322. */
  3323. spin_lock(&cur_trans->dirty_bgs_lock);
  3324. while (!list_empty(&cur_trans->dirty_bgs)) {
  3325. cache = list_first_entry(&cur_trans->dirty_bgs,
  3326. struct btrfs_block_group_cache,
  3327. dirty_list);
  3328. /*
  3329. * this can happen if cache_save_setup re-dirties a block
  3330. * group that is already under IO. Just wait for it to
  3331. * finish and then do it all again
  3332. */
  3333. if (!list_empty(&cache->io_list)) {
  3334. spin_unlock(&cur_trans->dirty_bgs_lock);
  3335. list_del_init(&cache->io_list);
  3336. btrfs_wait_cache_io(trans, cache, path);
  3337. btrfs_put_block_group(cache);
  3338. spin_lock(&cur_trans->dirty_bgs_lock);
  3339. }
  3340. /*
  3341. * don't remove from the dirty list until after we've waited
  3342. * on any pending IO
  3343. */
  3344. list_del_init(&cache->dirty_list);
  3345. spin_unlock(&cur_trans->dirty_bgs_lock);
  3346. should_put = 1;
  3347. cache_save_setup(cache, trans, path);
  3348. if (!ret)
  3349. ret = btrfs_run_delayed_refs(trans, fs_info,
  3350. (unsigned long) -1);
  3351. if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
  3352. cache->io_ctl.inode = NULL;
  3353. ret = btrfs_write_out_cache(fs_info, trans,
  3354. cache, path);
  3355. if (ret == 0 && cache->io_ctl.inode) {
  3356. num_started++;
  3357. should_put = 0;
  3358. list_add_tail(&cache->io_list, io);
  3359. } else {
  3360. /*
  3361. * if we failed to write the cache, the
  3362. * generation will be bad and life goes on
  3363. */
  3364. ret = 0;
  3365. }
  3366. }
  3367. if (!ret) {
  3368. ret = write_one_cache_group(trans, fs_info,
  3369. path, cache);
  3370. /*
  3371. * One of the free space endio workers might have
  3372. * created a new block group while updating a free space
  3373. * cache's inode (at inode.c:btrfs_finish_ordered_io())
  3374. * and hasn't released its transaction handle yet, in
  3375. * which case the new block group is still attached to
  3376. * its transaction handle and its creation has not
  3377. * finished yet (no block group item in the extent tree
  3378. * yet, etc). If this is the case, wait for all free
  3379. * space endio workers to finish and retry. This is a
  3380. * a very rare case so no need for a more efficient and
  3381. * complex approach.
  3382. */
  3383. if (ret == -ENOENT) {
  3384. wait_event(cur_trans->writer_wait,
  3385. atomic_read(&cur_trans->num_writers) == 1);
  3386. ret = write_one_cache_group(trans, fs_info,
  3387. path, cache);
  3388. }
  3389. if (ret)
  3390. btrfs_abort_transaction(trans, ret);
  3391. }
  3392. /* if its not on the io list, we need to put the block group */
  3393. if (should_put)
  3394. btrfs_put_block_group(cache);
  3395. spin_lock(&cur_trans->dirty_bgs_lock);
  3396. }
  3397. spin_unlock(&cur_trans->dirty_bgs_lock);
  3398. while (!list_empty(io)) {
  3399. cache = list_first_entry(io, struct btrfs_block_group_cache,
  3400. io_list);
  3401. list_del_init(&cache->io_list);
  3402. btrfs_wait_cache_io(trans, cache, path);
  3403. btrfs_put_block_group(cache);
  3404. }
  3405. btrfs_free_path(path);
  3406. return ret;
  3407. }
  3408. int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
  3409. {
  3410. struct btrfs_block_group_cache *block_group;
  3411. int readonly = 0;
  3412. block_group = btrfs_lookup_block_group(fs_info, bytenr);
  3413. if (!block_group || block_group->ro)
  3414. readonly = 1;
  3415. if (block_group)
  3416. btrfs_put_block_group(block_group);
  3417. return readonly;
  3418. }
  3419. bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
  3420. {
  3421. struct btrfs_block_group_cache *bg;
  3422. bool ret = true;
  3423. bg = btrfs_lookup_block_group(fs_info, bytenr);
  3424. if (!bg)
  3425. return false;
  3426. spin_lock(&bg->lock);
  3427. if (bg->ro)
  3428. ret = false;
  3429. else
  3430. atomic_inc(&bg->nocow_writers);
  3431. spin_unlock(&bg->lock);
  3432. /* no put on block group, done by btrfs_dec_nocow_writers */
  3433. if (!ret)
  3434. btrfs_put_block_group(bg);
  3435. return ret;
  3436. }
  3437. void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
  3438. {
  3439. struct btrfs_block_group_cache *bg;
  3440. bg = btrfs_lookup_block_group(fs_info, bytenr);
  3441. ASSERT(bg);
  3442. if (atomic_dec_and_test(&bg->nocow_writers))
  3443. wake_up_atomic_t(&bg->nocow_writers);
  3444. /*
  3445. * Once for our lookup and once for the lookup done by a previous call
  3446. * to btrfs_inc_nocow_writers()
  3447. */
  3448. btrfs_put_block_group(bg);
  3449. btrfs_put_block_group(bg);
  3450. }
  3451. static int btrfs_wait_nocow_writers_atomic_t(atomic_t *a)
  3452. {
  3453. schedule();
  3454. return 0;
  3455. }
  3456. void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
  3457. {
  3458. wait_on_atomic_t(&bg->nocow_writers,
  3459. btrfs_wait_nocow_writers_atomic_t,
  3460. TASK_UNINTERRUPTIBLE);
  3461. }
  3462. static const char *alloc_name(u64 flags)
  3463. {
  3464. switch (flags) {
  3465. case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
  3466. return "mixed";
  3467. case BTRFS_BLOCK_GROUP_METADATA:
  3468. return "metadata";
  3469. case BTRFS_BLOCK_GROUP_DATA:
  3470. return "data";
  3471. case BTRFS_BLOCK_GROUP_SYSTEM:
  3472. return "system";
  3473. default:
  3474. WARN_ON(1);
  3475. return "invalid-combination";
  3476. };
  3477. }
  3478. static int update_space_info(struct btrfs_fs_info *info, u64 flags,
  3479. u64 total_bytes, u64 bytes_used,
  3480. u64 bytes_readonly,
  3481. struct btrfs_space_info **space_info)
  3482. {
  3483. struct btrfs_space_info *found;
  3484. int i;
  3485. int factor;
  3486. int ret;
  3487. if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
  3488. BTRFS_BLOCK_GROUP_RAID10))
  3489. factor = 2;
  3490. else
  3491. factor = 1;
  3492. found = __find_space_info(info, flags);
  3493. if (found) {
  3494. spin_lock(&found->lock);
  3495. found->total_bytes += total_bytes;
  3496. found->disk_total += total_bytes * factor;
  3497. found->bytes_used += bytes_used;
  3498. found->disk_used += bytes_used * factor;
  3499. found->bytes_readonly += bytes_readonly;
  3500. if (total_bytes > 0)
  3501. found->full = 0;
  3502. space_info_add_new_bytes(info, found, total_bytes -
  3503. bytes_used - bytes_readonly);
  3504. spin_unlock(&found->lock);
  3505. *space_info = found;
  3506. return 0;
  3507. }
  3508. found = kzalloc(sizeof(*found), GFP_NOFS);
  3509. if (!found)
  3510. return -ENOMEM;
  3511. ret = percpu_counter_init(&found->total_bytes_pinned, 0, GFP_KERNEL);
  3512. if (ret) {
  3513. kfree(found);
  3514. return ret;
  3515. }
  3516. for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
  3517. INIT_LIST_HEAD(&found->block_groups[i]);
  3518. init_rwsem(&found->groups_sem);
  3519. spin_lock_init(&found->lock);
  3520. found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
  3521. found->total_bytes = total_bytes;
  3522. found->disk_total = total_bytes * factor;
  3523. found->bytes_used = bytes_used;
  3524. found->disk_used = bytes_used * factor;
  3525. found->bytes_pinned = 0;
  3526. found->bytes_reserved = 0;
  3527. found->bytes_readonly = bytes_readonly;
  3528. found->bytes_may_use = 0;
  3529. found->full = 0;
  3530. found->max_extent_size = 0;
  3531. found->force_alloc = CHUNK_ALLOC_NO_FORCE;
  3532. found->chunk_alloc = 0;
  3533. found->flush = 0;
  3534. init_waitqueue_head(&found->wait);
  3535. INIT_LIST_HEAD(&found->ro_bgs);
  3536. INIT_LIST_HEAD(&found->tickets);
  3537. INIT_LIST_HEAD(&found->priority_tickets);
  3538. ret = kobject_init_and_add(&found->kobj, &space_info_ktype,
  3539. info->space_info_kobj, "%s",
  3540. alloc_name(found->flags));
  3541. if (ret) {
  3542. kfree(found);
  3543. return ret;
  3544. }
  3545. *space_info = found;
  3546. list_add_rcu(&found->list, &info->space_info);
  3547. if (flags & BTRFS_BLOCK_GROUP_DATA)
  3548. info->data_sinfo = found;
  3549. return ret;
  3550. }
  3551. static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
  3552. {
  3553. u64 extra_flags = chunk_to_extended(flags) &
  3554. BTRFS_EXTENDED_PROFILE_MASK;
  3555. write_seqlock(&fs_info->profiles_lock);
  3556. if (flags & BTRFS_BLOCK_GROUP_DATA)
  3557. fs_info->avail_data_alloc_bits |= extra_flags;
  3558. if (flags & BTRFS_BLOCK_GROUP_METADATA)
  3559. fs_info->avail_metadata_alloc_bits |= extra_flags;
  3560. if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
  3561. fs_info->avail_system_alloc_bits |= extra_flags;
  3562. write_sequnlock(&fs_info->profiles_lock);
  3563. }
  3564. /*
  3565. * returns target flags in extended format or 0 if restripe for this
  3566. * chunk_type is not in progress
  3567. *
  3568. * should be called with either volume_mutex or balance_lock held
  3569. */
  3570. static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
  3571. {
  3572. struct btrfs_balance_control *bctl = fs_info->balance_ctl;
  3573. u64 target = 0;
  3574. if (!bctl)
  3575. return 0;
  3576. if (flags & BTRFS_BLOCK_GROUP_DATA &&
  3577. bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
  3578. target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
  3579. } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
  3580. bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
  3581. target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
  3582. } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
  3583. bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
  3584. target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
  3585. }
  3586. return target;
  3587. }
  3588. /*
  3589. * @flags: available profiles in extended format (see ctree.h)
  3590. *
  3591. * Returns reduced profile in chunk format. If profile changing is in
  3592. * progress (either running or paused) picks the target profile (if it's
  3593. * already available), otherwise falls back to plain reducing.
  3594. */
  3595. static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
  3596. {
  3597. u64 num_devices = fs_info->fs_devices->rw_devices;
  3598. u64 target;
  3599. u64 raid_type;
  3600. u64 allowed = 0;
  3601. /*
  3602. * see if restripe for this chunk_type is in progress, if so
  3603. * try to reduce to the target profile
  3604. */
  3605. spin_lock(&fs_info->balance_lock);
  3606. target = get_restripe_target(fs_info, flags);
  3607. if (target) {
  3608. /* pick target profile only if it's already available */
  3609. if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
  3610. spin_unlock(&fs_info->balance_lock);
  3611. return extended_to_chunk(target);
  3612. }
  3613. }
  3614. spin_unlock(&fs_info->balance_lock);
  3615. /* First, mask out the RAID levels which aren't possible */
  3616. for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
  3617. if (num_devices >= btrfs_raid_array[raid_type].devs_min)
  3618. allowed |= btrfs_raid_group[raid_type];
  3619. }
  3620. allowed &= flags;
  3621. if (allowed & BTRFS_BLOCK_GROUP_RAID6)
  3622. allowed = BTRFS_BLOCK_GROUP_RAID6;
  3623. else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
  3624. allowed = BTRFS_BLOCK_GROUP_RAID5;
  3625. else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
  3626. allowed = BTRFS_BLOCK_GROUP_RAID10;
  3627. else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
  3628. allowed = BTRFS_BLOCK_GROUP_RAID1;
  3629. else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
  3630. allowed = BTRFS_BLOCK_GROUP_RAID0;
  3631. flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
  3632. return extended_to_chunk(flags | allowed);
  3633. }
  3634. static u64 get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
  3635. {
  3636. unsigned seq;
  3637. u64 flags;
  3638. do {
  3639. flags = orig_flags;
  3640. seq = read_seqbegin(&fs_info->profiles_lock);
  3641. if (flags & BTRFS_BLOCK_GROUP_DATA)
  3642. flags |= fs_info->avail_data_alloc_bits;
  3643. else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
  3644. flags |= fs_info->avail_system_alloc_bits;
  3645. else if (flags & BTRFS_BLOCK_GROUP_METADATA)
  3646. flags |= fs_info->avail_metadata_alloc_bits;
  3647. } while (read_seqretry(&fs_info->profiles_lock, seq));
  3648. return btrfs_reduce_alloc_profile(fs_info, flags);
  3649. }
  3650. u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
  3651. {
  3652. struct btrfs_fs_info *fs_info = root->fs_info;
  3653. u64 flags;
  3654. u64 ret;
  3655. if (data)
  3656. flags = BTRFS_BLOCK_GROUP_DATA;
  3657. else if (root == fs_info->chunk_root)
  3658. flags = BTRFS_BLOCK_GROUP_SYSTEM;
  3659. else
  3660. flags = BTRFS_BLOCK_GROUP_METADATA;
  3661. ret = get_alloc_profile(fs_info, flags);
  3662. return ret;
  3663. }
  3664. int btrfs_alloc_data_chunk_ondemand(struct inode *inode, u64 bytes)
  3665. {
  3666. struct btrfs_space_info *data_sinfo;
  3667. struct btrfs_root *root = BTRFS_I(inode)->root;
  3668. struct btrfs_fs_info *fs_info = root->fs_info;
  3669. u64 used;
  3670. int ret = 0;
  3671. int need_commit = 2;
  3672. int have_pinned_space;
  3673. /* make sure bytes are sectorsize aligned */
  3674. bytes = ALIGN(bytes, fs_info->sectorsize);
  3675. if (btrfs_is_free_space_inode(inode)) {
  3676. need_commit = 0;
  3677. ASSERT(current->journal_info);
  3678. }
  3679. data_sinfo = fs_info->data_sinfo;
  3680. if (!data_sinfo)
  3681. goto alloc;
  3682. again:
  3683. /* make sure we have enough space to handle the data first */
  3684. spin_lock(&data_sinfo->lock);
  3685. used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
  3686. data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
  3687. data_sinfo->bytes_may_use;
  3688. if (used + bytes > data_sinfo->total_bytes) {
  3689. struct btrfs_trans_handle *trans;
  3690. /*
  3691. * if we don't have enough free bytes in this space then we need
  3692. * to alloc a new chunk.
  3693. */
  3694. if (!data_sinfo->full) {
  3695. u64 alloc_target;
  3696. data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
  3697. spin_unlock(&data_sinfo->lock);
  3698. alloc:
  3699. alloc_target = btrfs_get_alloc_profile(root, 1);
  3700. /*
  3701. * It is ugly that we don't call nolock join
  3702. * transaction for the free space inode case here.
  3703. * But it is safe because we only do the data space
  3704. * reservation for the free space cache in the
  3705. * transaction context, the common join transaction
  3706. * just increase the counter of the current transaction
  3707. * handler, doesn't try to acquire the trans_lock of
  3708. * the fs.
  3709. */
  3710. trans = btrfs_join_transaction(root);
  3711. if (IS_ERR(trans))
  3712. return PTR_ERR(trans);
  3713. ret = do_chunk_alloc(trans, fs_info, alloc_target,
  3714. CHUNK_ALLOC_NO_FORCE);
  3715. btrfs_end_transaction(trans);
  3716. if (ret < 0) {
  3717. if (ret != -ENOSPC)
  3718. return ret;
  3719. else {
  3720. have_pinned_space = 1;
  3721. goto commit_trans;
  3722. }
  3723. }
  3724. if (!data_sinfo)
  3725. data_sinfo = fs_info->data_sinfo;
  3726. goto again;
  3727. }
  3728. /*
  3729. * If we don't have enough pinned space to deal with this
  3730. * allocation, and no removed chunk in current transaction,
  3731. * don't bother committing the transaction.
  3732. */
  3733. have_pinned_space = percpu_counter_compare(
  3734. &data_sinfo->total_bytes_pinned,
  3735. used + bytes - data_sinfo->total_bytes);
  3736. spin_unlock(&data_sinfo->lock);
  3737. /* commit the current transaction and try again */
  3738. commit_trans:
  3739. if (need_commit &&
  3740. !atomic_read(&fs_info->open_ioctl_trans)) {
  3741. need_commit--;
  3742. if (need_commit > 0) {
  3743. btrfs_start_delalloc_roots(fs_info, 0, -1);
  3744. btrfs_wait_ordered_roots(fs_info, -1, 0,
  3745. (u64)-1);
  3746. }
  3747. trans = btrfs_join_transaction(root);
  3748. if (IS_ERR(trans))
  3749. return PTR_ERR(trans);
  3750. if (have_pinned_space >= 0 ||
  3751. test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
  3752. &trans->transaction->flags) ||
  3753. need_commit > 0) {
  3754. ret = btrfs_commit_transaction(trans);
  3755. if (ret)
  3756. return ret;
  3757. /*
  3758. * The cleaner kthread might still be doing iput
  3759. * operations. Wait for it to finish so that
  3760. * more space is released.
  3761. */
  3762. mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
  3763. mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
  3764. goto again;
  3765. } else {
  3766. btrfs_end_transaction(trans);
  3767. }
  3768. }
  3769. trace_btrfs_space_reservation(fs_info,
  3770. "space_info:enospc",
  3771. data_sinfo->flags, bytes, 1);
  3772. return -ENOSPC;
  3773. }
  3774. data_sinfo->bytes_may_use += bytes;
  3775. trace_btrfs_space_reservation(fs_info, "space_info",
  3776. data_sinfo->flags, bytes, 1);
  3777. spin_unlock(&data_sinfo->lock);
  3778. return ret;
  3779. }
  3780. /*
  3781. * New check_data_free_space() with ability for precious data reservation
  3782. * Will replace old btrfs_check_data_free_space(), but for patch split,
  3783. * add a new function first and then replace it.
  3784. */
  3785. int btrfs_check_data_free_space(struct inode *inode, u64 start, u64 len)
  3786. {
  3787. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  3788. int ret;
  3789. /* align the range */
  3790. len = round_up(start + len, fs_info->sectorsize) -
  3791. round_down(start, fs_info->sectorsize);
  3792. start = round_down(start, fs_info->sectorsize);
  3793. ret = btrfs_alloc_data_chunk_ondemand(inode, len);
  3794. if (ret < 0)
  3795. return ret;
  3796. /* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
  3797. ret = btrfs_qgroup_reserve_data(inode, start, len);
  3798. if (ret)
  3799. btrfs_free_reserved_data_space_noquota(inode, start, len);
  3800. return ret;
  3801. }
  3802. /*
  3803. * Called if we need to clear a data reservation for this inode
  3804. * Normally in a error case.
  3805. *
  3806. * This one will *NOT* use accurate qgroup reserved space API, just for case
  3807. * which we can't sleep and is sure it won't affect qgroup reserved space.
  3808. * Like clear_bit_hook().
  3809. */
  3810. void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
  3811. u64 len)
  3812. {
  3813. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  3814. struct btrfs_space_info *data_sinfo;
  3815. /* Make sure the range is aligned to sectorsize */
  3816. len = round_up(start + len, fs_info->sectorsize) -
  3817. round_down(start, fs_info->sectorsize);
  3818. start = round_down(start, fs_info->sectorsize);
  3819. data_sinfo = fs_info->data_sinfo;
  3820. spin_lock(&data_sinfo->lock);
  3821. if (WARN_ON(data_sinfo->bytes_may_use < len))
  3822. data_sinfo->bytes_may_use = 0;
  3823. else
  3824. data_sinfo->bytes_may_use -= len;
  3825. trace_btrfs_space_reservation(fs_info, "space_info",
  3826. data_sinfo->flags, len, 0);
  3827. spin_unlock(&data_sinfo->lock);
  3828. }
  3829. /*
  3830. * Called if we need to clear a data reservation for this inode
  3831. * Normally in a error case.
  3832. *
  3833. * This one will handle the per-inode data rsv map for accurate reserved
  3834. * space framework.
  3835. */
  3836. void btrfs_free_reserved_data_space(struct inode *inode, u64 start, u64 len)
  3837. {
  3838. struct btrfs_root *root = BTRFS_I(inode)->root;
  3839. /* Make sure the range is aligned to sectorsize */
  3840. len = round_up(start + len, root->fs_info->sectorsize) -
  3841. round_down(start, root->fs_info->sectorsize);
  3842. start = round_down(start, root->fs_info->sectorsize);
  3843. btrfs_free_reserved_data_space_noquota(inode, start, len);
  3844. btrfs_qgroup_free_data(inode, start, len);
  3845. }
  3846. static void force_metadata_allocation(struct btrfs_fs_info *info)
  3847. {
  3848. struct list_head *head = &info->space_info;
  3849. struct btrfs_space_info *found;
  3850. rcu_read_lock();
  3851. list_for_each_entry_rcu(found, head, list) {
  3852. if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
  3853. found->force_alloc = CHUNK_ALLOC_FORCE;
  3854. }
  3855. rcu_read_unlock();
  3856. }
  3857. static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
  3858. {
  3859. return (global->size << 1);
  3860. }
  3861. static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
  3862. struct btrfs_space_info *sinfo, int force)
  3863. {
  3864. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  3865. u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
  3866. u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
  3867. u64 thresh;
  3868. if (force == CHUNK_ALLOC_FORCE)
  3869. return 1;
  3870. /*
  3871. * We need to take into account the global rsv because for all intents
  3872. * and purposes it's used space. Don't worry about locking the
  3873. * global_rsv, it doesn't change except when the transaction commits.
  3874. */
  3875. if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
  3876. num_allocated += calc_global_rsv_need_space(global_rsv);
  3877. /*
  3878. * in limited mode, we want to have some free space up to
  3879. * about 1% of the FS size.
  3880. */
  3881. if (force == CHUNK_ALLOC_LIMITED) {
  3882. thresh = btrfs_super_total_bytes(fs_info->super_copy);
  3883. thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
  3884. if (num_bytes - num_allocated < thresh)
  3885. return 1;
  3886. }
  3887. if (num_allocated + SZ_2M < div_factor(num_bytes, 8))
  3888. return 0;
  3889. return 1;
  3890. }
  3891. static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
  3892. {
  3893. u64 num_dev;
  3894. if (type & (BTRFS_BLOCK_GROUP_RAID10 |
  3895. BTRFS_BLOCK_GROUP_RAID0 |
  3896. BTRFS_BLOCK_GROUP_RAID5 |
  3897. BTRFS_BLOCK_GROUP_RAID6))
  3898. num_dev = fs_info->fs_devices->rw_devices;
  3899. else if (type & BTRFS_BLOCK_GROUP_RAID1)
  3900. num_dev = 2;
  3901. else
  3902. num_dev = 1; /* DUP or single */
  3903. return num_dev;
  3904. }
  3905. /*
  3906. * If @is_allocation is true, reserve space in the system space info necessary
  3907. * for allocating a chunk, otherwise if it's false, reserve space necessary for
  3908. * removing a chunk.
  3909. */
  3910. void check_system_chunk(struct btrfs_trans_handle *trans,
  3911. struct btrfs_fs_info *fs_info, u64 type)
  3912. {
  3913. struct btrfs_space_info *info;
  3914. u64 left;
  3915. u64 thresh;
  3916. int ret = 0;
  3917. u64 num_devs;
  3918. /*
  3919. * Needed because we can end up allocating a system chunk and for an
  3920. * atomic and race free space reservation in the chunk block reserve.
  3921. */
  3922. ASSERT(mutex_is_locked(&fs_info->chunk_mutex));
  3923. info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
  3924. spin_lock(&info->lock);
  3925. left = info->total_bytes - info->bytes_used - info->bytes_pinned -
  3926. info->bytes_reserved - info->bytes_readonly -
  3927. info->bytes_may_use;
  3928. spin_unlock(&info->lock);
  3929. num_devs = get_profile_num_devs(fs_info, type);
  3930. /* num_devs device items to update and 1 chunk item to add or remove */
  3931. thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
  3932. btrfs_calc_trans_metadata_size(fs_info, 1);
  3933. if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
  3934. btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
  3935. left, thresh, type);
  3936. dump_space_info(fs_info, info, 0, 0);
  3937. }
  3938. if (left < thresh) {
  3939. u64 flags;
  3940. flags = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
  3941. /*
  3942. * Ignore failure to create system chunk. We might end up not
  3943. * needing it, as we might not need to COW all nodes/leafs from
  3944. * the paths we visit in the chunk tree (they were already COWed
  3945. * or created in the current transaction for example).
  3946. */
  3947. ret = btrfs_alloc_chunk(trans, fs_info, flags);
  3948. }
  3949. if (!ret) {
  3950. ret = btrfs_block_rsv_add(fs_info->chunk_root,
  3951. &fs_info->chunk_block_rsv,
  3952. thresh, BTRFS_RESERVE_NO_FLUSH);
  3953. if (!ret)
  3954. trans->chunk_bytes_reserved += thresh;
  3955. }
  3956. }
  3957. /*
  3958. * If force is CHUNK_ALLOC_FORCE:
  3959. * - return 1 if it successfully allocates a chunk,
  3960. * - return errors including -ENOSPC otherwise.
  3961. * If force is NOT CHUNK_ALLOC_FORCE:
  3962. * - return 0 if it doesn't need to allocate a new chunk,
  3963. * - return 1 if it successfully allocates a chunk,
  3964. * - return errors including -ENOSPC otherwise.
  3965. */
  3966. static int do_chunk_alloc(struct btrfs_trans_handle *trans,
  3967. struct btrfs_fs_info *fs_info, u64 flags, int force)
  3968. {
  3969. struct btrfs_space_info *space_info;
  3970. int wait_for_alloc = 0;
  3971. int ret = 0;
  3972. /* Don't re-enter if we're already allocating a chunk */
  3973. if (trans->allocating_chunk)
  3974. return -ENOSPC;
  3975. space_info = __find_space_info(fs_info, flags);
  3976. if (!space_info) {
  3977. ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
  3978. BUG_ON(ret); /* -ENOMEM */
  3979. }
  3980. BUG_ON(!space_info); /* Logic error */
  3981. again:
  3982. spin_lock(&space_info->lock);
  3983. if (force < space_info->force_alloc)
  3984. force = space_info->force_alloc;
  3985. if (space_info->full) {
  3986. if (should_alloc_chunk(fs_info, space_info, force))
  3987. ret = -ENOSPC;
  3988. else
  3989. ret = 0;
  3990. spin_unlock(&space_info->lock);
  3991. return ret;
  3992. }
  3993. if (!should_alloc_chunk(fs_info, space_info, force)) {
  3994. spin_unlock(&space_info->lock);
  3995. return 0;
  3996. } else if (space_info->chunk_alloc) {
  3997. wait_for_alloc = 1;
  3998. } else {
  3999. space_info->chunk_alloc = 1;
  4000. }
  4001. spin_unlock(&space_info->lock);
  4002. mutex_lock(&fs_info->chunk_mutex);
  4003. /*
  4004. * The chunk_mutex is held throughout the entirety of a chunk
  4005. * allocation, so once we've acquired the chunk_mutex we know that the
  4006. * other guy is done and we need to recheck and see if we should
  4007. * allocate.
  4008. */
  4009. if (wait_for_alloc) {
  4010. mutex_unlock(&fs_info->chunk_mutex);
  4011. wait_for_alloc = 0;
  4012. goto again;
  4013. }
  4014. trans->allocating_chunk = true;
  4015. /*
  4016. * If we have mixed data/metadata chunks we want to make sure we keep
  4017. * allocating mixed chunks instead of individual chunks.
  4018. */
  4019. if (btrfs_mixed_space_info(space_info))
  4020. flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
  4021. /*
  4022. * if we're doing a data chunk, go ahead and make sure that
  4023. * we keep a reasonable number of metadata chunks allocated in the
  4024. * FS as well.
  4025. */
  4026. if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
  4027. fs_info->data_chunk_allocations++;
  4028. if (!(fs_info->data_chunk_allocations %
  4029. fs_info->metadata_ratio))
  4030. force_metadata_allocation(fs_info);
  4031. }
  4032. /*
  4033. * Check if we have enough space in SYSTEM chunk because we may need
  4034. * to update devices.
  4035. */
  4036. check_system_chunk(trans, fs_info, flags);
  4037. ret = btrfs_alloc_chunk(trans, fs_info, flags);
  4038. trans->allocating_chunk = false;
  4039. spin_lock(&space_info->lock);
  4040. if (ret < 0 && ret != -ENOSPC)
  4041. goto out;
  4042. if (ret)
  4043. space_info->full = 1;
  4044. else
  4045. ret = 1;
  4046. space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
  4047. out:
  4048. space_info->chunk_alloc = 0;
  4049. spin_unlock(&space_info->lock);
  4050. mutex_unlock(&fs_info->chunk_mutex);
  4051. /*
  4052. * When we allocate a new chunk we reserve space in the chunk block
  4053. * reserve to make sure we can COW nodes/leafs in the chunk tree or
  4054. * add new nodes/leafs to it if we end up needing to do it when
  4055. * inserting the chunk item and updating device items as part of the
  4056. * second phase of chunk allocation, performed by
  4057. * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
  4058. * large number of new block groups to create in our transaction
  4059. * handle's new_bgs list to avoid exhausting the chunk block reserve
  4060. * in extreme cases - like having a single transaction create many new
  4061. * block groups when starting to write out the free space caches of all
  4062. * the block groups that were made dirty during the lifetime of the
  4063. * transaction.
  4064. */
  4065. if (trans->can_flush_pending_bgs &&
  4066. trans->chunk_bytes_reserved >= (u64)SZ_2M) {
  4067. btrfs_create_pending_block_groups(trans, fs_info);
  4068. btrfs_trans_release_chunk_metadata(trans);
  4069. }
  4070. return ret;
  4071. }
  4072. static int can_overcommit(struct btrfs_root *root,
  4073. struct btrfs_space_info *space_info, u64 bytes,
  4074. enum btrfs_reserve_flush_enum flush)
  4075. {
  4076. struct btrfs_fs_info *fs_info = root->fs_info;
  4077. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  4078. u64 profile;
  4079. u64 space_size;
  4080. u64 avail;
  4081. u64 used;
  4082. /* Don't overcommit when in mixed mode. */
  4083. if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
  4084. return 0;
  4085. profile = btrfs_get_alloc_profile(root, 0);
  4086. used = space_info->bytes_used + space_info->bytes_reserved +
  4087. space_info->bytes_pinned + space_info->bytes_readonly;
  4088. /*
  4089. * We only want to allow over committing if we have lots of actual space
  4090. * free, but if we don't have enough space to handle the global reserve
  4091. * space then we could end up having a real enospc problem when trying
  4092. * to allocate a chunk or some other such important allocation.
  4093. */
  4094. spin_lock(&global_rsv->lock);
  4095. space_size = calc_global_rsv_need_space(global_rsv);
  4096. spin_unlock(&global_rsv->lock);
  4097. if (used + space_size >= space_info->total_bytes)
  4098. return 0;
  4099. used += space_info->bytes_may_use;
  4100. spin_lock(&fs_info->free_chunk_lock);
  4101. avail = fs_info->free_chunk_space;
  4102. spin_unlock(&fs_info->free_chunk_lock);
  4103. /*
  4104. * If we have dup, raid1 or raid10 then only half of the free
  4105. * space is actually useable. For raid56, the space info used
  4106. * doesn't include the parity drive, so we don't have to
  4107. * change the math
  4108. */
  4109. if (profile & (BTRFS_BLOCK_GROUP_DUP |
  4110. BTRFS_BLOCK_GROUP_RAID1 |
  4111. BTRFS_BLOCK_GROUP_RAID10))
  4112. avail >>= 1;
  4113. /*
  4114. * If we aren't flushing all things, let us overcommit up to
  4115. * 1/2th of the space. If we can flush, don't let us overcommit
  4116. * too much, let it overcommit up to 1/8 of the space.
  4117. */
  4118. if (flush == BTRFS_RESERVE_FLUSH_ALL)
  4119. avail >>= 3;
  4120. else
  4121. avail >>= 1;
  4122. if (used + bytes < space_info->total_bytes + avail)
  4123. return 1;
  4124. return 0;
  4125. }
  4126. static void btrfs_writeback_inodes_sb_nr(struct btrfs_fs_info *fs_info,
  4127. unsigned long nr_pages, int nr_items)
  4128. {
  4129. struct super_block *sb = fs_info->sb;
  4130. if (down_read_trylock(&sb->s_umount)) {
  4131. writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
  4132. up_read(&sb->s_umount);
  4133. } else {
  4134. /*
  4135. * We needn't worry the filesystem going from r/w to r/o though
  4136. * we don't acquire ->s_umount mutex, because the filesystem
  4137. * should guarantee the delalloc inodes list be empty after
  4138. * the filesystem is readonly(all dirty pages are written to
  4139. * the disk).
  4140. */
  4141. btrfs_start_delalloc_roots(fs_info, 0, nr_items);
  4142. if (!current->journal_info)
  4143. btrfs_wait_ordered_roots(fs_info, nr_items, 0, (u64)-1);
  4144. }
  4145. }
  4146. static inline int calc_reclaim_items_nr(struct btrfs_fs_info *fs_info,
  4147. u64 to_reclaim)
  4148. {
  4149. u64 bytes;
  4150. int nr;
  4151. bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
  4152. nr = (int)div64_u64(to_reclaim, bytes);
  4153. if (!nr)
  4154. nr = 1;
  4155. return nr;
  4156. }
  4157. #define EXTENT_SIZE_PER_ITEM SZ_256K
  4158. /*
  4159. * shrink metadata reservation for delalloc
  4160. */
  4161. static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
  4162. bool wait_ordered)
  4163. {
  4164. struct btrfs_fs_info *fs_info = root->fs_info;
  4165. struct btrfs_block_rsv *block_rsv;
  4166. struct btrfs_space_info *space_info;
  4167. struct btrfs_trans_handle *trans;
  4168. u64 delalloc_bytes;
  4169. u64 max_reclaim;
  4170. long time_left;
  4171. unsigned long nr_pages;
  4172. int loops;
  4173. int items;
  4174. enum btrfs_reserve_flush_enum flush;
  4175. /* Calc the number of the pages we need flush for space reservation */
  4176. items = calc_reclaim_items_nr(fs_info, to_reclaim);
  4177. to_reclaim = (u64)items * EXTENT_SIZE_PER_ITEM;
  4178. trans = (struct btrfs_trans_handle *)current->journal_info;
  4179. block_rsv = &fs_info->delalloc_block_rsv;
  4180. space_info = block_rsv->space_info;
  4181. delalloc_bytes = percpu_counter_sum_positive(
  4182. &fs_info->delalloc_bytes);
  4183. if (delalloc_bytes == 0) {
  4184. if (trans)
  4185. return;
  4186. if (wait_ordered)
  4187. btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
  4188. return;
  4189. }
  4190. loops = 0;
  4191. while (delalloc_bytes && loops < 3) {
  4192. max_reclaim = min(delalloc_bytes, to_reclaim);
  4193. nr_pages = max_reclaim >> PAGE_SHIFT;
  4194. btrfs_writeback_inodes_sb_nr(fs_info, nr_pages, items);
  4195. /*
  4196. * We need to wait for the async pages to actually start before
  4197. * we do anything.
  4198. */
  4199. max_reclaim = atomic_read(&fs_info->async_delalloc_pages);
  4200. if (!max_reclaim)
  4201. goto skip_async;
  4202. if (max_reclaim <= nr_pages)
  4203. max_reclaim = 0;
  4204. else
  4205. max_reclaim -= nr_pages;
  4206. wait_event(fs_info->async_submit_wait,
  4207. atomic_read(&fs_info->async_delalloc_pages) <=
  4208. (int)max_reclaim);
  4209. skip_async:
  4210. if (!trans)
  4211. flush = BTRFS_RESERVE_FLUSH_ALL;
  4212. else
  4213. flush = BTRFS_RESERVE_NO_FLUSH;
  4214. spin_lock(&space_info->lock);
  4215. if (can_overcommit(root, space_info, orig, flush)) {
  4216. spin_unlock(&space_info->lock);
  4217. break;
  4218. }
  4219. if (list_empty(&space_info->tickets) &&
  4220. list_empty(&space_info->priority_tickets)) {
  4221. spin_unlock(&space_info->lock);
  4222. break;
  4223. }
  4224. spin_unlock(&space_info->lock);
  4225. loops++;
  4226. if (wait_ordered && !trans) {
  4227. btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
  4228. } else {
  4229. time_left = schedule_timeout_killable(1);
  4230. if (time_left)
  4231. break;
  4232. }
  4233. delalloc_bytes = percpu_counter_sum_positive(
  4234. &fs_info->delalloc_bytes);
  4235. }
  4236. }
  4237. /**
  4238. * maybe_commit_transaction - possibly commit the transaction if its ok to
  4239. * @root - the root we're allocating for
  4240. * @bytes - the number of bytes we want to reserve
  4241. * @force - force the commit
  4242. *
  4243. * This will check to make sure that committing the transaction will actually
  4244. * get us somewhere and then commit the transaction if it does. Otherwise it
  4245. * will return -ENOSPC.
  4246. */
  4247. static int may_commit_transaction(struct btrfs_root *root,
  4248. struct btrfs_space_info *space_info,
  4249. u64 bytes, int force)
  4250. {
  4251. struct btrfs_fs_info *fs_info = root->fs_info;
  4252. struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_block_rsv;
  4253. struct btrfs_trans_handle *trans;
  4254. trans = (struct btrfs_trans_handle *)current->journal_info;
  4255. if (trans)
  4256. return -EAGAIN;
  4257. if (force)
  4258. goto commit;
  4259. /* See if there is enough pinned space to make this reservation */
  4260. if (percpu_counter_compare(&space_info->total_bytes_pinned,
  4261. bytes) >= 0)
  4262. goto commit;
  4263. /*
  4264. * See if there is some space in the delayed insertion reservation for
  4265. * this reservation.
  4266. */
  4267. if (space_info != delayed_rsv->space_info)
  4268. return -ENOSPC;
  4269. spin_lock(&delayed_rsv->lock);
  4270. if (percpu_counter_compare(&space_info->total_bytes_pinned,
  4271. bytes - delayed_rsv->size) >= 0) {
  4272. spin_unlock(&delayed_rsv->lock);
  4273. return -ENOSPC;
  4274. }
  4275. spin_unlock(&delayed_rsv->lock);
  4276. commit:
  4277. trans = btrfs_join_transaction(root);
  4278. if (IS_ERR(trans))
  4279. return -ENOSPC;
  4280. return btrfs_commit_transaction(trans);
  4281. }
  4282. struct reserve_ticket {
  4283. u64 bytes;
  4284. int error;
  4285. struct list_head list;
  4286. wait_queue_head_t wait;
  4287. };
  4288. static int flush_space(struct btrfs_root *root,
  4289. struct btrfs_space_info *space_info, u64 num_bytes,
  4290. u64 orig_bytes, int state)
  4291. {
  4292. struct btrfs_fs_info *fs_info = root->fs_info;
  4293. struct btrfs_trans_handle *trans;
  4294. int nr;
  4295. int ret = 0;
  4296. switch (state) {
  4297. case FLUSH_DELAYED_ITEMS_NR:
  4298. case FLUSH_DELAYED_ITEMS:
  4299. if (state == FLUSH_DELAYED_ITEMS_NR)
  4300. nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2;
  4301. else
  4302. nr = -1;
  4303. trans = btrfs_join_transaction(root);
  4304. if (IS_ERR(trans)) {
  4305. ret = PTR_ERR(trans);
  4306. break;
  4307. }
  4308. ret = btrfs_run_delayed_items_nr(trans, fs_info, nr);
  4309. btrfs_end_transaction(trans);
  4310. break;
  4311. case FLUSH_DELALLOC:
  4312. case FLUSH_DELALLOC_WAIT:
  4313. shrink_delalloc(root, num_bytes * 2, orig_bytes,
  4314. state == FLUSH_DELALLOC_WAIT);
  4315. break;
  4316. case ALLOC_CHUNK:
  4317. trans = btrfs_join_transaction(root);
  4318. if (IS_ERR(trans)) {
  4319. ret = PTR_ERR(trans);
  4320. break;
  4321. }
  4322. ret = do_chunk_alloc(trans, fs_info,
  4323. btrfs_get_alloc_profile(root, 0),
  4324. CHUNK_ALLOC_NO_FORCE);
  4325. btrfs_end_transaction(trans);
  4326. if (ret > 0 || ret == -ENOSPC)
  4327. ret = 0;
  4328. break;
  4329. case COMMIT_TRANS:
  4330. ret = may_commit_transaction(root, space_info, orig_bytes, 0);
  4331. break;
  4332. default:
  4333. ret = -ENOSPC;
  4334. break;
  4335. }
  4336. trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes,
  4337. orig_bytes, state, ret);
  4338. return ret;
  4339. }
  4340. static inline u64
  4341. btrfs_calc_reclaim_metadata_size(struct btrfs_root *root,
  4342. struct btrfs_space_info *space_info)
  4343. {
  4344. struct reserve_ticket *ticket;
  4345. u64 used;
  4346. u64 expected;
  4347. u64 to_reclaim = 0;
  4348. list_for_each_entry(ticket, &space_info->tickets, list)
  4349. to_reclaim += ticket->bytes;
  4350. list_for_each_entry(ticket, &space_info->priority_tickets, list)
  4351. to_reclaim += ticket->bytes;
  4352. if (to_reclaim)
  4353. return to_reclaim;
  4354. to_reclaim = min_t(u64, num_online_cpus() * SZ_1M, SZ_16M);
  4355. if (can_overcommit(root, space_info, to_reclaim,
  4356. BTRFS_RESERVE_FLUSH_ALL))
  4357. return 0;
  4358. used = space_info->bytes_used + space_info->bytes_reserved +
  4359. space_info->bytes_pinned + space_info->bytes_readonly +
  4360. space_info->bytes_may_use;
  4361. if (can_overcommit(root, space_info, SZ_1M, BTRFS_RESERVE_FLUSH_ALL))
  4362. expected = div_factor_fine(space_info->total_bytes, 95);
  4363. else
  4364. expected = div_factor_fine(space_info->total_bytes, 90);
  4365. if (used > expected)
  4366. to_reclaim = used - expected;
  4367. else
  4368. to_reclaim = 0;
  4369. to_reclaim = min(to_reclaim, space_info->bytes_may_use +
  4370. space_info->bytes_reserved);
  4371. return to_reclaim;
  4372. }
  4373. static inline int need_do_async_reclaim(struct btrfs_space_info *space_info,
  4374. struct btrfs_root *root, u64 used)
  4375. {
  4376. struct btrfs_fs_info *fs_info = root->fs_info;
  4377. u64 thresh = div_factor_fine(space_info->total_bytes, 98);
  4378. /* If we're just plain full then async reclaim just slows us down. */
  4379. if ((space_info->bytes_used + space_info->bytes_reserved) >= thresh)
  4380. return 0;
  4381. if (!btrfs_calc_reclaim_metadata_size(root, space_info))
  4382. return 0;
  4383. return (used >= thresh && !btrfs_fs_closing(fs_info) &&
  4384. !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
  4385. }
  4386. static void wake_all_tickets(struct list_head *head)
  4387. {
  4388. struct reserve_ticket *ticket;
  4389. while (!list_empty(head)) {
  4390. ticket = list_first_entry(head, struct reserve_ticket, list);
  4391. list_del_init(&ticket->list);
  4392. ticket->error = -ENOSPC;
  4393. wake_up(&ticket->wait);
  4394. }
  4395. }
  4396. /*
  4397. * This is for normal flushers, we can wait all goddamned day if we want to. We
  4398. * will loop and continuously try to flush as long as we are making progress.
  4399. * We count progress as clearing off tickets each time we have to loop.
  4400. */
  4401. static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
  4402. {
  4403. struct btrfs_fs_info *fs_info;
  4404. struct btrfs_space_info *space_info;
  4405. u64 to_reclaim;
  4406. int flush_state;
  4407. int commit_cycles = 0;
  4408. u64 last_tickets_id;
  4409. fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
  4410. space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
  4411. spin_lock(&space_info->lock);
  4412. to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
  4413. space_info);
  4414. if (!to_reclaim) {
  4415. space_info->flush = 0;
  4416. spin_unlock(&space_info->lock);
  4417. return;
  4418. }
  4419. last_tickets_id = space_info->tickets_id;
  4420. spin_unlock(&space_info->lock);
  4421. flush_state = FLUSH_DELAYED_ITEMS_NR;
  4422. do {
  4423. struct reserve_ticket *ticket;
  4424. int ret;
  4425. ret = flush_space(fs_info->fs_root, space_info, to_reclaim,
  4426. to_reclaim, flush_state);
  4427. spin_lock(&space_info->lock);
  4428. if (list_empty(&space_info->tickets)) {
  4429. space_info->flush = 0;
  4430. spin_unlock(&space_info->lock);
  4431. return;
  4432. }
  4433. to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
  4434. space_info);
  4435. ticket = list_first_entry(&space_info->tickets,
  4436. struct reserve_ticket, list);
  4437. if (last_tickets_id == space_info->tickets_id) {
  4438. flush_state++;
  4439. } else {
  4440. last_tickets_id = space_info->tickets_id;
  4441. flush_state = FLUSH_DELAYED_ITEMS_NR;
  4442. if (commit_cycles)
  4443. commit_cycles--;
  4444. }
  4445. if (flush_state > COMMIT_TRANS) {
  4446. commit_cycles++;
  4447. if (commit_cycles > 2) {
  4448. wake_all_tickets(&space_info->tickets);
  4449. space_info->flush = 0;
  4450. } else {
  4451. flush_state = FLUSH_DELAYED_ITEMS_NR;
  4452. }
  4453. }
  4454. spin_unlock(&space_info->lock);
  4455. } while (flush_state <= COMMIT_TRANS);
  4456. }
  4457. void btrfs_init_async_reclaim_work(struct work_struct *work)
  4458. {
  4459. INIT_WORK(work, btrfs_async_reclaim_metadata_space);
  4460. }
  4461. static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
  4462. struct btrfs_space_info *space_info,
  4463. struct reserve_ticket *ticket)
  4464. {
  4465. u64 to_reclaim;
  4466. int flush_state = FLUSH_DELAYED_ITEMS_NR;
  4467. spin_lock(&space_info->lock);
  4468. to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
  4469. space_info);
  4470. if (!to_reclaim) {
  4471. spin_unlock(&space_info->lock);
  4472. return;
  4473. }
  4474. spin_unlock(&space_info->lock);
  4475. do {
  4476. flush_space(fs_info->fs_root, space_info, to_reclaim,
  4477. to_reclaim, flush_state);
  4478. flush_state++;
  4479. spin_lock(&space_info->lock);
  4480. if (ticket->bytes == 0) {
  4481. spin_unlock(&space_info->lock);
  4482. return;
  4483. }
  4484. spin_unlock(&space_info->lock);
  4485. /*
  4486. * Priority flushers can't wait on delalloc without
  4487. * deadlocking.
  4488. */
  4489. if (flush_state == FLUSH_DELALLOC ||
  4490. flush_state == FLUSH_DELALLOC_WAIT)
  4491. flush_state = ALLOC_CHUNK;
  4492. } while (flush_state < COMMIT_TRANS);
  4493. }
  4494. static int wait_reserve_ticket(struct btrfs_fs_info *fs_info,
  4495. struct btrfs_space_info *space_info,
  4496. struct reserve_ticket *ticket, u64 orig_bytes)
  4497. {
  4498. DEFINE_WAIT(wait);
  4499. int ret = 0;
  4500. spin_lock(&space_info->lock);
  4501. while (ticket->bytes > 0 && ticket->error == 0) {
  4502. ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
  4503. if (ret) {
  4504. ret = -EINTR;
  4505. break;
  4506. }
  4507. spin_unlock(&space_info->lock);
  4508. schedule();
  4509. finish_wait(&ticket->wait, &wait);
  4510. spin_lock(&space_info->lock);
  4511. }
  4512. if (!ret)
  4513. ret = ticket->error;
  4514. if (!list_empty(&ticket->list))
  4515. list_del_init(&ticket->list);
  4516. if (ticket->bytes && ticket->bytes < orig_bytes) {
  4517. u64 num_bytes = orig_bytes - ticket->bytes;
  4518. space_info->bytes_may_use -= num_bytes;
  4519. trace_btrfs_space_reservation(fs_info, "space_info",
  4520. space_info->flags, num_bytes, 0);
  4521. }
  4522. spin_unlock(&space_info->lock);
  4523. return ret;
  4524. }
  4525. /**
  4526. * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
  4527. * @root - the root we're allocating for
  4528. * @space_info - the space info we want to allocate from
  4529. * @orig_bytes - the number of bytes we want
  4530. * @flush - whether or not we can flush to make our reservation
  4531. *
  4532. * This will reserve orig_bytes number of bytes from the space info associated
  4533. * with the block_rsv. If there is not enough space it will make an attempt to
  4534. * flush out space to make room. It will do this by flushing delalloc if
  4535. * possible or committing the transaction. If flush is 0 then no attempts to
  4536. * regain reservations will be made and this will fail if there is not enough
  4537. * space already.
  4538. */
  4539. static int __reserve_metadata_bytes(struct btrfs_root *root,
  4540. struct btrfs_space_info *space_info,
  4541. u64 orig_bytes,
  4542. enum btrfs_reserve_flush_enum flush)
  4543. {
  4544. struct btrfs_fs_info *fs_info = root->fs_info;
  4545. struct reserve_ticket ticket;
  4546. u64 used;
  4547. int ret = 0;
  4548. ASSERT(orig_bytes);
  4549. ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
  4550. spin_lock(&space_info->lock);
  4551. ret = -ENOSPC;
  4552. used = space_info->bytes_used + space_info->bytes_reserved +
  4553. space_info->bytes_pinned + space_info->bytes_readonly +
  4554. space_info->bytes_may_use;
  4555. /*
  4556. * If we have enough space then hooray, make our reservation and carry
  4557. * on. If not see if we can overcommit, and if we can, hooray carry on.
  4558. * If not things get more complicated.
  4559. */
  4560. if (used + orig_bytes <= space_info->total_bytes) {
  4561. space_info->bytes_may_use += orig_bytes;
  4562. trace_btrfs_space_reservation(fs_info, "space_info",
  4563. space_info->flags, orig_bytes, 1);
  4564. ret = 0;
  4565. } else if (can_overcommit(root, space_info, orig_bytes, flush)) {
  4566. space_info->bytes_may_use += orig_bytes;
  4567. trace_btrfs_space_reservation(fs_info, "space_info",
  4568. space_info->flags, orig_bytes, 1);
  4569. ret = 0;
  4570. }
  4571. /*
  4572. * If we couldn't make a reservation then setup our reservation ticket
  4573. * and kick the async worker if it's not already running.
  4574. *
  4575. * If we are a priority flusher then we just need to add our ticket to
  4576. * the list and we will do our own flushing further down.
  4577. */
  4578. if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
  4579. ticket.bytes = orig_bytes;
  4580. ticket.error = 0;
  4581. init_waitqueue_head(&ticket.wait);
  4582. if (flush == BTRFS_RESERVE_FLUSH_ALL) {
  4583. list_add_tail(&ticket.list, &space_info->tickets);
  4584. if (!space_info->flush) {
  4585. space_info->flush = 1;
  4586. trace_btrfs_trigger_flush(fs_info,
  4587. space_info->flags,
  4588. orig_bytes, flush,
  4589. "enospc");
  4590. queue_work(system_unbound_wq,
  4591. &root->fs_info->async_reclaim_work);
  4592. }
  4593. } else {
  4594. list_add_tail(&ticket.list,
  4595. &space_info->priority_tickets);
  4596. }
  4597. } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
  4598. used += orig_bytes;
  4599. /*
  4600. * We will do the space reservation dance during log replay,
  4601. * which means we won't have fs_info->fs_root set, so don't do
  4602. * the async reclaim as we will panic.
  4603. */
  4604. if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
  4605. need_do_async_reclaim(space_info, root, used) &&
  4606. !work_busy(&fs_info->async_reclaim_work)) {
  4607. trace_btrfs_trigger_flush(fs_info, space_info->flags,
  4608. orig_bytes, flush, "preempt");
  4609. queue_work(system_unbound_wq,
  4610. &fs_info->async_reclaim_work);
  4611. }
  4612. }
  4613. spin_unlock(&space_info->lock);
  4614. if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
  4615. return ret;
  4616. if (flush == BTRFS_RESERVE_FLUSH_ALL)
  4617. return wait_reserve_ticket(fs_info, space_info, &ticket,
  4618. orig_bytes);
  4619. ret = 0;
  4620. priority_reclaim_metadata_space(fs_info, space_info, &ticket);
  4621. spin_lock(&space_info->lock);
  4622. if (ticket.bytes) {
  4623. if (ticket.bytes < orig_bytes) {
  4624. u64 num_bytes = orig_bytes - ticket.bytes;
  4625. space_info->bytes_may_use -= num_bytes;
  4626. trace_btrfs_space_reservation(fs_info, "space_info",
  4627. space_info->flags,
  4628. num_bytes, 0);
  4629. }
  4630. list_del_init(&ticket.list);
  4631. ret = -ENOSPC;
  4632. }
  4633. spin_unlock(&space_info->lock);
  4634. ASSERT(list_empty(&ticket.list));
  4635. return ret;
  4636. }
  4637. /**
  4638. * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
  4639. * @root - the root we're allocating for
  4640. * @block_rsv - the block_rsv we're allocating for
  4641. * @orig_bytes - the number of bytes we want
  4642. * @flush - whether or not we can flush to make our reservation
  4643. *
  4644. * This will reserve orgi_bytes number of bytes from the space info associated
  4645. * with the block_rsv. If there is not enough space it will make an attempt to
  4646. * flush out space to make room. It will do this by flushing delalloc if
  4647. * possible or committing the transaction. If flush is 0 then no attempts to
  4648. * regain reservations will be made and this will fail if there is not enough
  4649. * space already.
  4650. */
  4651. static int reserve_metadata_bytes(struct btrfs_root *root,
  4652. struct btrfs_block_rsv *block_rsv,
  4653. u64 orig_bytes,
  4654. enum btrfs_reserve_flush_enum flush)
  4655. {
  4656. struct btrfs_fs_info *fs_info = root->fs_info;
  4657. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  4658. int ret;
  4659. ret = __reserve_metadata_bytes(root, block_rsv->space_info, orig_bytes,
  4660. flush);
  4661. if (ret == -ENOSPC &&
  4662. unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
  4663. if (block_rsv != global_rsv &&
  4664. !block_rsv_use_bytes(global_rsv, orig_bytes))
  4665. ret = 0;
  4666. }
  4667. if (ret == -ENOSPC)
  4668. trace_btrfs_space_reservation(fs_info, "space_info:enospc",
  4669. block_rsv->space_info->flags,
  4670. orig_bytes, 1);
  4671. return ret;
  4672. }
  4673. static struct btrfs_block_rsv *get_block_rsv(
  4674. const struct btrfs_trans_handle *trans,
  4675. const struct btrfs_root *root)
  4676. {
  4677. struct btrfs_fs_info *fs_info = root->fs_info;
  4678. struct btrfs_block_rsv *block_rsv = NULL;
  4679. if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
  4680. (root == fs_info->csum_root && trans->adding_csums) ||
  4681. (root == fs_info->uuid_root))
  4682. block_rsv = trans->block_rsv;
  4683. if (!block_rsv)
  4684. block_rsv = root->block_rsv;
  4685. if (!block_rsv)
  4686. block_rsv = &fs_info->empty_block_rsv;
  4687. return block_rsv;
  4688. }
  4689. static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
  4690. u64 num_bytes)
  4691. {
  4692. int ret = -ENOSPC;
  4693. spin_lock(&block_rsv->lock);
  4694. if (block_rsv->reserved >= num_bytes) {
  4695. block_rsv->reserved -= num_bytes;
  4696. if (block_rsv->reserved < block_rsv->size)
  4697. block_rsv->full = 0;
  4698. ret = 0;
  4699. }
  4700. spin_unlock(&block_rsv->lock);
  4701. return ret;
  4702. }
  4703. static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
  4704. u64 num_bytes, int update_size)
  4705. {
  4706. spin_lock(&block_rsv->lock);
  4707. block_rsv->reserved += num_bytes;
  4708. if (update_size)
  4709. block_rsv->size += num_bytes;
  4710. else if (block_rsv->reserved >= block_rsv->size)
  4711. block_rsv->full = 1;
  4712. spin_unlock(&block_rsv->lock);
  4713. }
  4714. int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
  4715. struct btrfs_block_rsv *dest, u64 num_bytes,
  4716. int min_factor)
  4717. {
  4718. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  4719. u64 min_bytes;
  4720. if (global_rsv->space_info != dest->space_info)
  4721. return -ENOSPC;
  4722. spin_lock(&global_rsv->lock);
  4723. min_bytes = div_factor(global_rsv->size, min_factor);
  4724. if (global_rsv->reserved < min_bytes + num_bytes) {
  4725. spin_unlock(&global_rsv->lock);
  4726. return -ENOSPC;
  4727. }
  4728. global_rsv->reserved -= num_bytes;
  4729. if (global_rsv->reserved < global_rsv->size)
  4730. global_rsv->full = 0;
  4731. spin_unlock(&global_rsv->lock);
  4732. block_rsv_add_bytes(dest, num_bytes, 1);
  4733. return 0;
  4734. }
  4735. /*
  4736. * This is for space we already have accounted in space_info->bytes_may_use, so
  4737. * basically when we're returning space from block_rsv's.
  4738. */
  4739. static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
  4740. struct btrfs_space_info *space_info,
  4741. u64 num_bytes)
  4742. {
  4743. struct reserve_ticket *ticket;
  4744. struct list_head *head;
  4745. u64 used;
  4746. enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
  4747. bool check_overcommit = false;
  4748. spin_lock(&space_info->lock);
  4749. head = &space_info->priority_tickets;
  4750. /*
  4751. * If we are over our limit then we need to check and see if we can
  4752. * overcommit, and if we can't then we just need to free up our space
  4753. * and not satisfy any requests.
  4754. */
  4755. used = space_info->bytes_used + space_info->bytes_reserved +
  4756. space_info->bytes_pinned + space_info->bytes_readonly +
  4757. space_info->bytes_may_use;
  4758. if (used - num_bytes >= space_info->total_bytes)
  4759. check_overcommit = true;
  4760. again:
  4761. while (!list_empty(head) && num_bytes) {
  4762. ticket = list_first_entry(head, struct reserve_ticket,
  4763. list);
  4764. /*
  4765. * We use 0 bytes because this space is already reserved, so
  4766. * adding the ticket space would be a double count.
  4767. */
  4768. if (check_overcommit &&
  4769. !can_overcommit(fs_info->extent_root, space_info, 0,
  4770. flush))
  4771. break;
  4772. if (num_bytes >= ticket->bytes) {
  4773. list_del_init(&ticket->list);
  4774. num_bytes -= ticket->bytes;
  4775. ticket->bytes = 0;
  4776. space_info->tickets_id++;
  4777. wake_up(&ticket->wait);
  4778. } else {
  4779. ticket->bytes -= num_bytes;
  4780. num_bytes = 0;
  4781. }
  4782. }
  4783. if (num_bytes && head == &space_info->priority_tickets) {
  4784. head = &space_info->tickets;
  4785. flush = BTRFS_RESERVE_FLUSH_ALL;
  4786. goto again;
  4787. }
  4788. space_info->bytes_may_use -= num_bytes;
  4789. trace_btrfs_space_reservation(fs_info, "space_info",
  4790. space_info->flags, num_bytes, 0);
  4791. spin_unlock(&space_info->lock);
  4792. }
  4793. /*
  4794. * This is for newly allocated space that isn't accounted in
  4795. * space_info->bytes_may_use yet. So if we allocate a chunk or unpin an extent
  4796. * we use this helper.
  4797. */
  4798. static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
  4799. struct btrfs_space_info *space_info,
  4800. u64 num_bytes)
  4801. {
  4802. struct reserve_ticket *ticket;
  4803. struct list_head *head = &space_info->priority_tickets;
  4804. again:
  4805. while (!list_empty(head) && num_bytes) {
  4806. ticket = list_first_entry(head, struct reserve_ticket,
  4807. list);
  4808. if (num_bytes >= ticket->bytes) {
  4809. trace_btrfs_space_reservation(fs_info, "space_info",
  4810. space_info->flags,
  4811. ticket->bytes, 1);
  4812. list_del_init(&ticket->list);
  4813. num_bytes -= ticket->bytes;
  4814. space_info->bytes_may_use += ticket->bytes;
  4815. ticket->bytes = 0;
  4816. space_info->tickets_id++;
  4817. wake_up(&ticket->wait);
  4818. } else {
  4819. trace_btrfs_space_reservation(fs_info, "space_info",
  4820. space_info->flags,
  4821. num_bytes, 1);
  4822. space_info->bytes_may_use += num_bytes;
  4823. ticket->bytes -= num_bytes;
  4824. num_bytes = 0;
  4825. }
  4826. }
  4827. if (num_bytes && head == &space_info->priority_tickets) {
  4828. head = &space_info->tickets;
  4829. goto again;
  4830. }
  4831. }
  4832. static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
  4833. struct btrfs_block_rsv *block_rsv,
  4834. struct btrfs_block_rsv *dest, u64 num_bytes)
  4835. {
  4836. struct btrfs_space_info *space_info = block_rsv->space_info;
  4837. spin_lock(&block_rsv->lock);
  4838. if (num_bytes == (u64)-1)
  4839. num_bytes = block_rsv->size;
  4840. block_rsv->size -= num_bytes;
  4841. if (block_rsv->reserved >= block_rsv->size) {
  4842. num_bytes = block_rsv->reserved - block_rsv->size;
  4843. block_rsv->reserved = block_rsv->size;
  4844. block_rsv->full = 1;
  4845. } else {
  4846. num_bytes = 0;
  4847. }
  4848. spin_unlock(&block_rsv->lock);
  4849. if (num_bytes > 0) {
  4850. if (dest) {
  4851. spin_lock(&dest->lock);
  4852. if (!dest->full) {
  4853. u64 bytes_to_add;
  4854. bytes_to_add = dest->size - dest->reserved;
  4855. bytes_to_add = min(num_bytes, bytes_to_add);
  4856. dest->reserved += bytes_to_add;
  4857. if (dest->reserved >= dest->size)
  4858. dest->full = 1;
  4859. num_bytes -= bytes_to_add;
  4860. }
  4861. spin_unlock(&dest->lock);
  4862. }
  4863. if (num_bytes)
  4864. space_info_add_old_bytes(fs_info, space_info,
  4865. num_bytes);
  4866. }
  4867. }
  4868. int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
  4869. struct btrfs_block_rsv *dst, u64 num_bytes,
  4870. int update_size)
  4871. {
  4872. int ret;
  4873. ret = block_rsv_use_bytes(src, num_bytes);
  4874. if (ret)
  4875. return ret;
  4876. block_rsv_add_bytes(dst, num_bytes, update_size);
  4877. return 0;
  4878. }
  4879. void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
  4880. {
  4881. memset(rsv, 0, sizeof(*rsv));
  4882. spin_lock_init(&rsv->lock);
  4883. rsv->type = type;
  4884. }
  4885. struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_fs_info *fs_info,
  4886. unsigned short type)
  4887. {
  4888. struct btrfs_block_rsv *block_rsv;
  4889. block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
  4890. if (!block_rsv)
  4891. return NULL;
  4892. btrfs_init_block_rsv(block_rsv, type);
  4893. block_rsv->space_info = __find_space_info(fs_info,
  4894. BTRFS_BLOCK_GROUP_METADATA);
  4895. return block_rsv;
  4896. }
  4897. void btrfs_free_block_rsv(struct btrfs_fs_info *fs_info,
  4898. struct btrfs_block_rsv *rsv)
  4899. {
  4900. if (!rsv)
  4901. return;
  4902. btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
  4903. kfree(rsv);
  4904. }
  4905. void __btrfs_free_block_rsv(struct btrfs_block_rsv *rsv)
  4906. {
  4907. kfree(rsv);
  4908. }
  4909. int btrfs_block_rsv_add(struct btrfs_root *root,
  4910. struct btrfs_block_rsv *block_rsv, u64 num_bytes,
  4911. enum btrfs_reserve_flush_enum flush)
  4912. {
  4913. int ret;
  4914. if (num_bytes == 0)
  4915. return 0;
  4916. ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
  4917. if (!ret) {
  4918. block_rsv_add_bytes(block_rsv, num_bytes, 1);
  4919. return 0;
  4920. }
  4921. return ret;
  4922. }
  4923. int btrfs_block_rsv_check(struct btrfs_block_rsv *block_rsv, int min_factor)
  4924. {
  4925. u64 num_bytes = 0;
  4926. int ret = -ENOSPC;
  4927. if (!block_rsv)
  4928. return 0;
  4929. spin_lock(&block_rsv->lock);
  4930. num_bytes = div_factor(block_rsv->size, min_factor);
  4931. if (block_rsv->reserved >= num_bytes)
  4932. ret = 0;
  4933. spin_unlock(&block_rsv->lock);
  4934. return ret;
  4935. }
  4936. int btrfs_block_rsv_refill(struct btrfs_root *root,
  4937. struct btrfs_block_rsv *block_rsv, u64 min_reserved,
  4938. enum btrfs_reserve_flush_enum flush)
  4939. {
  4940. u64 num_bytes = 0;
  4941. int ret = -ENOSPC;
  4942. if (!block_rsv)
  4943. return 0;
  4944. spin_lock(&block_rsv->lock);
  4945. num_bytes = min_reserved;
  4946. if (block_rsv->reserved >= num_bytes)
  4947. ret = 0;
  4948. else
  4949. num_bytes -= block_rsv->reserved;
  4950. spin_unlock(&block_rsv->lock);
  4951. if (!ret)
  4952. return 0;
  4953. ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
  4954. if (!ret) {
  4955. block_rsv_add_bytes(block_rsv, num_bytes, 0);
  4956. return 0;
  4957. }
  4958. return ret;
  4959. }
  4960. void btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
  4961. struct btrfs_block_rsv *block_rsv,
  4962. u64 num_bytes)
  4963. {
  4964. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  4965. if (global_rsv == block_rsv ||
  4966. block_rsv->space_info != global_rsv->space_info)
  4967. global_rsv = NULL;
  4968. block_rsv_release_bytes(fs_info, block_rsv, global_rsv, num_bytes);
  4969. }
  4970. static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
  4971. {
  4972. struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
  4973. struct btrfs_space_info *sinfo = block_rsv->space_info;
  4974. u64 num_bytes;
  4975. /*
  4976. * The global block rsv is based on the size of the extent tree, the
  4977. * checksum tree and the root tree. If the fs is empty we want to set
  4978. * it to a minimal amount for safety.
  4979. */
  4980. num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
  4981. btrfs_root_used(&fs_info->csum_root->root_item) +
  4982. btrfs_root_used(&fs_info->tree_root->root_item);
  4983. num_bytes = max_t(u64, num_bytes, SZ_16M);
  4984. spin_lock(&sinfo->lock);
  4985. spin_lock(&block_rsv->lock);
  4986. block_rsv->size = min_t(u64, num_bytes, SZ_512M);
  4987. if (block_rsv->reserved < block_rsv->size) {
  4988. num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
  4989. sinfo->bytes_reserved + sinfo->bytes_readonly +
  4990. sinfo->bytes_may_use;
  4991. if (sinfo->total_bytes > num_bytes) {
  4992. num_bytes = sinfo->total_bytes - num_bytes;
  4993. num_bytes = min(num_bytes,
  4994. block_rsv->size - block_rsv->reserved);
  4995. block_rsv->reserved += num_bytes;
  4996. sinfo->bytes_may_use += num_bytes;
  4997. trace_btrfs_space_reservation(fs_info, "space_info",
  4998. sinfo->flags, num_bytes,
  4999. 1);
  5000. }
  5001. } else if (block_rsv->reserved > block_rsv->size) {
  5002. num_bytes = block_rsv->reserved - block_rsv->size;
  5003. sinfo->bytes_may_use -= num_bytes;
  5004. trace_btrfs_space_reservation(fs_info, "space_info",
  5005. sinfo->flags, num_bytes, 0);
  5006. block_rsv->reserved = block_rsv->size;
  5007. }
  5008. if (block_rsv->reserved == block_rsv->size)
  5009. block_rsv->full = 1;
  5010. else
  5011. block_rsv->full = 0;
  5012. spin_unlock(&block_rsv->lock);
  5013. spin_unlock(&sinfo->lock);
  5014. }
  5015. static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
  5016. {
  5017. struct btrfs_space_info *space_info;
  5018. space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
  5019. fs_info->chunk_block_rsv.space_info = space_info;
  5020. space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
  5021. fs_info->global_block_rsv.space_info = space_info;
  5022. fs_info->delalloc_block_rsv.space_info = space_info;
  5023. fs_info->trans_block_rsv.space_info = space_info;
  5024. fs_info->empty_block_rsv.space_info = space_info;
  5025. fs_info->delayed_block_rsv.space_info = space_info;
  5026. fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
  5027. fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
  5028. fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
  5029. fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
  5030. if (fs_info->quota_root)
  5031. fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
  5032. fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
  5033. update_global_block_rsv(fs_info);
  5034. }
  5035. static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
  5036. {
  5037. block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
  5038. (u64)-1);
  5039. WARN_ON(fs_info->delalloc_block_rsv.size > 0);
  5040. WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
  5041. WARN_ON(fs_info->trans_block_rsv.size > 0);
  5042. WARN_ON(fs_info->trans_block_rsv.reserved > 0);
  5043. WARN_ON(fs_info->chunk_block_rsv.size > 0);
  5044. WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
  5045. WARN_ON(fs_info->delayed_block_rsv.size > 0);
  5046. WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
  5047. }
  5048. void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
  5049. struct btrfs_fs_info *fs_info)
  5050. {
  5051. if (!trans->block_rsv)
  5052. return;
  5053. if (!trans->bytes_reserved)
  5054. return;
  5055. trace_btrfs_space_reservation(fs_info, "transaction",
  5056. trans->transid, trans->bytes_reserved, 0);
  5057. btrfs_block_rsv_release(fs_info, trans->block_rsv,
  5058. trans->bytes_reserved);
  5059. trans->bytes_reserved = 0;
  5060. }
  5061. /*
  5062. * To be called after all the new block groups attached to the transaction
  5063. * handle have been created (btrfs_create_pending_block_groups()).
  5064. */
  5065. void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
  5066. {
  5067. struct btrfs_fs_info *fs_info = trans->fs_info;
  5068. if (!trans->chunk_bytes_reserved)
  5069. return;
  5070. WARN_ON_ONCE(!list_empty(&trans->new_bgs));
  5071. block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
  5072. trans->chunk_bytes_reserved);
  5073. trans->chunk_bytes_reserved = 0;
  5074. }
  5075. /* Can only return 0 or -ENOSPC */
  5076. int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
  5077. struct inode *inode)
  5078. {
  5079. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  5080. struct btrfs_root *root = BTRFS_I(inode)->root;
  5081. /*
  5082. * We always use trans->block_rsv here as we will have reserved space
  5083. * for our orphan when starting the transaction, using get_block_rsv()
  5084. * here will sometimes make us choose the wrong block rsv as we could be
  5085. * doing a reloc inode for a non refcounted root.
  5086. */
  5087. struct btrfs_block_rsv *src_rsv = trans->block_rsv;
  5088. struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
  5089. /*
  5090. * We need to hold space in order to delete our orphan item once we've
  5091. * added it, so this takes the reservation so we can release it later
  5092. * when we are truly done with the orphan item.
  5093. */
  5094. u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
  5095. trace_btrfs_space_reservation(fs_info, "orphan",
  5096. btrfs_ino(BTRFS_I(inode)), num_bytes, 1);
  5097. return btrfs_block_rsv_migrate(src_rsv, dst_rsv, num_bytes, 1);
  5098. }
  5099. void btrfs_orphan_release_metadata(struct inode *inode)
  5100. {
  5101. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  5102. struct btrfs_root *root = BTRFS_I(inode)->root;
  5103. u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
  5104. trace_btrfs_space_reservation(fs_info, "orphan",
  5105. btrfs_ino(BTRFS_I(inode)), num_bytes, 0);
  5106. btrfs_block_rsv_release(fs_info, root->orphan_block_rsv, num_bytes);
  5107. }
  5108. /*
  5109. * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
  5110. * root: the root of the parent directory
  5111. * rsv: block reservation
  5112. * items: the number of items that we need do reservation
  5113. * qgroup_reserved: used to return the reserved size in qgroup
  5114. *
  5115. * This function is used to reserve the space for snapshot/subvolume
  5116. * creation and deletion. Those operations are different with the
  5117. * common file/directory operations, they change two fs/file trees
  5118. * and root tree, the number of items that the qgroup reserves is
  5119. * different with the free space reservation. So we can not use
  5120. * the space reservation mechanism in start_transaction().
  5121. */
  5122. int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
  5123. struct btrfs_block_rsv *rsv,
  5124. int items,
  5125. u64 *qgroup_reserved,
  5126. bool use_global_rsv)
  5127. {
  5128. u64 num_bytes;
  5129. int ret;
  5130. struct btrfs_fs_info *fs_info = root->fs_info;
  5131. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  5132. if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
  5133. /* One for parent inode, two for dir entries */
  5134. num_bytes = 3 * fs_info->nodesize;
  5135. ret = btrfs_qgroup_reserve_meta(root, num_bytes);
  5136. if (ret)
  5137. return ret;
  5138. } else {
  5139. num_bytes = 0;
  5140. }
  5141. *qgroup_reserved = num_bytes;
  5142. num_bytes = btrfs_calc_trans_metadata_size(fs_info, items);
  5143. rsv->space_info = __find_space_info(fs_info,
  5144. BTRFS_BLOCK_GROUP_METADATA);
  5145. ret = btrfs_block_rsv_add(root, rsv, num_bytes,
  5146. BTRFS_RESERVE_FLUSH_ALL);
  5147. if (ret == -ENOSPC && use_global_rsv)
  5148. ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, 1);
  5149. if (ret && *qgroup_reserved)
  5150. btrfs_qgroup_free_meta(root, *qgroup_reserved);
  5151. return ret;
  5152. }
  5153. void btrfs_subvolume_release_metadata(struct btrfs_fs_info *fs_info,
  5154. struct btrfs_block_rsv *rsv,
  5155. u64 qgroup_reserved)
  5156. {
  5157. btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
  5158. }
  5159. /**
  5160. * drop_outstanding_extent - drop an outstanding extent
  5161. * @inode: the inode we're dropping the extent for
  5162. * @num_bytes: the number of bytes we're releasing.
  5163. *
  5164. * This is called when we are freeing up an outstanding extent, either called
  5165. * after an error or after an extent is written. This will return the number of
  5166. * reserved extents that need to be freed. This must be called with
  5167. * BTRFS_I(inode)->lock held.
  5168. */
  5169. static unsigned drop_outstanding_extent(struct inode *inode, u64 num_bytes)
  5170. {
  5171. unsigned drop_inode_space = 0;
  5172. unsigned dropped_extents = 0;
  5173. unsigned num_extents;
  5174. num_extents = count_max_extents(num_bytes);
  5175. ASSERT(num_extents);
  5176. ASSERT(BTRFS_I(inode)->outstanding_extents >= num_extents);
  5177. BTRFS_I(inode)->outstanding_extents -= num_extents;
  5178. if (BTRFS_I(inode)->outstanding_extents == 0 &&
  5179. test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
  5180. &BTRFS_I(inode)->runtime_flags))
  5181. drop_inode_space = 1;
  5182. /*
  5183. * If we have more or the same amount of outstanding extents than we have
  5184. * reserved then we need to leave the reserved extents count alone.
  5185. */
  5186. if (BTRFS_I(inode)->outstanding_extents >=
  5187. BTRFS_I(inode)->reserved_extents)
  5188. return drop_inode_space;
  5189. dropped_extents = BTRFS_I(inode)->reserved_extents -
  5190. BTRFS_I(inode)->outstanding_extents;
  5191. BTRFS_I(inode)->reserved_extents -= dropped_extents;
  5192. return dropped_extents + drop_inode_space;
  5193. }
  5194. /**
  5195. * calc_csum_metadata_size - return the amount of metadata space that must be
  5196. * reserved/freed for the given bytes.
  5197. * @inode: the inode we're manipulating
  5198. * @num_bytes: the number of bytes in question
  5199. * @reserve: 1 if we are reserving space, 0 if we are freeing space
  5200. *
  5201. * This adjusts the number of csum_bytes in the inode and then returns the
  5202. * correct amount of metadata that must either be reserved or freed. We
  5203. * calculate how many checksums we can fit into one leaf and then divide the
  5204. * number of bytes that will need to be checksumed by this value to figure out
  5205. * how many checksums will be required. If we are adding bytes then the number
  5206. * may go up and we will return the number of additional bytes that must be
  5207. * reserved. If it is going down we will return the number of bytes that must
  5208. * be freed.
  5209. *
  5210. * This must be called with BTRFS_I(inode)->lock held.
  5211. */
  5212. static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
  5213. int reserve)
  5214. {
  5215. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  5216. u64 old_csums, num_csums;
  5217. if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
  5218. BTRFS_I(inode)->csum_bytes == 0)
  5219. return 0;
  5220. old_csums = btrfs_csum_bytes_to_leaves(fs_info,
  5221. BTRFS_I(inode)->csum_bytes);
  5222. if (reserve)
  5223. BTRFS_I(inode)->csum_bytes += num_bytes;
  5224. else
  5225. BTRFS_I(inode)->csum_bytes -= num_bytes;
  5226. num_csums = btrfs_csum_bytes_to_leaves(fs_info,
  5227. BTRFS_I(inode)->csum_bytes);
  5228. /* No change, no need to reserve more */
  5229. if (old_csums == num_csums)
  5230. return 0;
  5231. if (reserve)
  5232. return btrfs_calc_trans_metadata_size(fs_info,
  5233. num_csums - old_csums);
  5234. return btrfs_calc_trans_metadata_size(fs_info, old_csums - num_csums);
  5235. }
  5236. int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
  5237. {
  5238. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  5239. struct btrfs_root *root = BTRFS_I(inode)->root;
  5240. struct btrfs_block_rsv *block_rsv = &fs_info->delalloc_block_rsv;
  5241. u64 to_reserve = 0;
  5242. u64 csum_bytes;
  5243. unsigned nr_extents;
  5244. enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
  5245. int ret = 0;
  5246. bool delalloc_lock = true;
  5247. u64 to_free = 0;
  5248. unsigned dropped;
  5249. bool release_extra = false;
  5250. /* If we are a free space inode we need to not flush since we will be in
  5251. * the middle of a transaction commit. We also don't need the delalloc
  5252. * mutex since we won't race with anybody. We need this mostly to make
  5253. * lockdep shut its filthy mouth.
  5254. *
  5255. * If we have a transaction open (can happen if we call truncate_block
  5256. * from truncate), then we need FLUSH_LIMIT so we don't deadlock.
  5257. */
  5258. if (btrfs_is_free_space_inode(inode)) {
  5259. flush = BTRFS_RESERVE_NO_FLUSH;
  5260. delalloc_lock = false;
  5261. } else if (current->journal_info) {
  5262. flush = BTRFS_RESERVE_FLUSH_LIMIT;
  5263. }
  5264. if (flush != BTRFS_RESERVE_NO_FLUSH &&
  5265. btrfs_transaction_in_commit(fs_info))
  5266. schedule_timeout(1);
  5267. if (delalloc_lock)
  5268. mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
  5269. num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
  5270. spin_lock(&BTRFS_I(inode)->lock);
  5271. nr_extents = count_max_extents(num_bytes);
  5272. BTRFS_I(inode)->outstanding_extents += nr_extents;
  5273. nr_extents = 0;
  5274. if (BTRFS_I(inode)->outstanding_extents >
  5275. BTRFS_I(inode)->reserved_extents)
  5276. nr_extents += BTRFS_I(inode)->outstanding_extents -
  5277. BTRFS_I(inode)->reserved_extents;
  5278. /* We always want to reserve a slot for updating the inode. */
  5279. to_reserve = btrfs_calc_trans_metadata_size(fs_info, nr_extents + 1);
  5280. to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
  5281. csum_bytes = BTRFS_I(inode)->csum_bytes;
  5282. spin_unlock(&BTRFS_I(inode)->lock);
  5283. if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
  5284. ret = btrfs_qgroup_reserve_meta(root,
  5285. nr_extents * fs_info->nodesize);
  5286. if (ret)
  5287. goto out_fail;
  5288. }
  5289. ret = btrfs_block_rsv_add(root, block_rsv, to_reserve, flush);
  5290. if (unlikely(ret)) {
  5291. btrfs_qgroup_free_meta(root,
  5292. nr_extents * fs_info->nodesize);
  5293. goto out_fail;
  5294. }
  5295. spin_lock(&BTRFS_I(inode)->lock);
  5296. if (test_and_set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
  5297. &BTRFS_I(inode)->runtime_flags)) {
  5298. to_reserve -= btrfs_calc_trans_metadata_size(fs_info, 1);
  5299. release_extra = true;
  5300. }
  5301. BTRFS_I(inode)->reserved_extents += nr_extents;
  5302. spin_unlock(&BTRFS_I(inode)->lock);
  5303. if (delalloc_lock)
  5304. mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
  5305. if (to_reserve)
  5306. trace_btrfs_space_reservation(fs_info, "delalloc",
  5307. btrfs_ino(BTRFS_I(inode)), to_reserve, 1);
  5308. if (release_extra)
  5309. btrfs_block_rsv_release(fs_info, block_rsv,
  5310. btrfs_calc_trans_metadata_size(fs_info, 1));
  5311. return 0;
  5312. out_fail:
  5313. spin_lock(&BTRFS_I(inode)->lock);
  5314. dropped = drop_outstanding_extent(inode, num_bytes);
  5315. /*
  5316. * If the inodes csum_bytes is the same as the original
  5317. * csum_bytes then we know we haven't raced with any free()ers
  5318. * so we can just reduce our inodes csum bytes and carry on.
  5319. */
  5320. if (BTRFS_I(inode)->csum_bytes == csum_bytes) {
  5321. calc_csum_metadata_size(inode, num_bytes, 0);
  5322. } else {
  5323. u64 orig_csum_bytes = BTRFS_I(inode)->csum_bytes;
  5324. u64 bytes;
  5325. /*
  5326. * This is tricky, but first we need to figure out how much we
  5327. * freed from any free-ers that occurred during this
  5328. * reservation, so we reset ->csum_bytes to the csum_bytes
  5329. * before we dropped our lock, and then call the free for the
  5330. * number of bytes that were freed while we were trying our
  5331. * reservation.
  5332. */
  5333. bytes = csum_bytes - BTRFS_I(inode)->csum_bytes;
  5334. BTRFS_I(inode)->csum_bytes = csum_bytes;
  5335. to_free = calc_csum_metadata_size(inode, bytes, 0);
  5336. /*
  5337. * Now we need to see how much we would have freed had we not
  5338. * been making this reservation and our ->csum_bytes were not
  5339. * artificially inflated.
  5340. */
  5341. BTRFS_I(inode)->csum_bytes = csum_bytes - num_bytes;
  5342. bytes = csum_bytes - orig_csum_bytes;
  5343. bytes = calc_csum_metadata_size(inode, bytes, 0);
  5344. /*
  5345. * Now reset ->csum_bytes to what it should be. If bytes is
  5346. * more than to_free then we would have freed more space had we
  5347. * not had an artificially high ->csum_bytes, so we need to free
  5348. * the remainder. If bytes is the same or less then we don't
  5349. * need to do anything, the other free-ers did the correct
  5350. * thing.
  5351. */
  5352. BTRFS_I(inode)->csum_bytes = orig_csum_bytes - num_bytes;
  5353. if (bytes > to_free)
  5354. to_free = bytes - to_free;
  5355. else
  5356. to_free = 0;
  5357. }
  5358. spin_unlock(&BTRFS_I(inode)->lock);
  5359. if (dropped)
  5360. to_free += btrfs_calc_trans_metadata_size(fs_info, dropped);
  5361. if (to_free) {
  5362. btrfs_block_rsv_release(fs_info, block_rsv, to_free);
  5363. trace_btrfs_space_reservation(fs_info, "delalloc",
  5364. btrfs_ino(BTRFS_I(inode)), to_free, 0);
  5365. }
  5366. if (delalloc_lock)
  5367. mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
  5368. return ret;
  5369. }
  5370. /**
  5371. * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
  5372. * @inode: the inode to release the reservation for
  5373. * @num_bytes: the number of bytes we're releasing
  5374. *
  5375. * This will release the metadata reservation for an inode. This can be called
  5376. * once we complete IO for a given set of bytes to release their metadata
  5377. * reservations.
  5378. */
  5379. void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
  5380. {
  5381. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  5382. u64 to_free = 0;
  5383. unsigned dropped;
  5384. num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
  5385. spin_lock(&BTRFS_I(inode)->lock);
  5386. dropped = drop_outstanding_extent(inode, num_bytes);
  5387. if (num_bytes)
  5388. to_free = calc_csum_metadata_size(inode, num_bytes, 0);
  5389. spin_unlock(&BTRFS_I(inode)->lock);
  5390. if (dropped > 0)
  5391. to_free += btrfs_calc_trans_metadata_size(fs_info, dropped);
  5392. if (btrfs_is_testing(fs_info))
  5393. return;
  5394. trace_btrfs_space_reservation(fs_info, "delalloc",
  5395. btrfs_ino(BTRFS_I(inode)), to_free, 0);
  5396. btrfs_block_rsv_release(fs_info, &fs_info->delalloc_block_rsv, to_free);
  5397. }
  5398. /**
  5399. * btrfs_delalloc_reserve_space - reserve data and metadata space for
  5400. * delalloc
  5401. * @inode: inode we're writing to
  5402. * @start: start range we are writing to
  5403. * @len: how long the range we are writing to
  5404. *
  5405. * This will do the following things
  5406. *
  5407. * o reserve space in data space info for num bytes
  5408. * and reserve precious corresponding qgroup space
  5409. * (Done in check_data_free_space)
  5410. *
  5411. * o reserve space for metadata space, based on the number of outstanding
  5412. * extents and how much csums will be needed
  5413. * also reserve metadata space in a per root over-reserve method.
  5414. * o add to the inodes->delalloc_bytes
  5415. * o add it to the fs_info's delalloc inodes list.
  5416. * (Above 3 all done in delalloc_reserve_metadata)
  5417. *
  5418. * Return 0 for success
  5419. * Return <0 for error(-ENOSPC or -EQUOT)
  5420. */
  5421. int btrfs_delalloc_reserve_space(struct inode *inode, u64 start, u64 len)
  5422. {
  5423. int ret;
  5424. ret = btrfs_check_data_free_space(inode, start, len);
  5425. if (ret < 0)
  5426. return ret;
  5427. ret = btrfs_delalloc_reserve_metadata(inode, len);
  5428. if (ret < 0)
  5429. btrfs_free_reserved_data_space(inode, start, len);
  5430. return ret;
  5431. }
  5432. /**
  5433. * btrfs_delalloc_release_space - release data and metadata space for delalloc
  5434. * @inode: inode we're releasing space for
  5435. * @start: start position of the space already reserved
  5436. * @len: the len of the space already reserved
  5437. *
  5438. * This must be matched with a call to btrfs_delalloc_reserve_space. This is
  5439. * called in the case that we don't need the metadata AND data reservations
  5440. * anymore. So if there is an error or we insert an inline extent.
  5441. *
  5442. * This function will release the metadata space that was not used and will
  5443. * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
  5444. * list if there are no delalloc bytes left.
  5445. * Also it will handle the qgroup reserved space.
  5446. */
  5447. void btrfs_delalloc_release_space(struct inode *inode, u64 start, u64 len)
  5448. {
  5449. btrfs_delalloc_release_metadata(inode, len);
  5450. btrfs_free_reserved_data_space(inode, start, len);
  5451. }
  5452. static int update_block_group(struct btrfs_trans_handle *trans,
  5453. struct btrfs_fs_info *info, u64 bytenr,
  5454. u64 num_bytes, int alloc)
  5455. {
  5456. struct btrfs_block_group_cache *cache = NULL;
  5457. u64 total = num_bytes;
  5458. u64 old_val;
  5459. u64 byte_in_group;
  5460. int factor;
  5461. /* block accounting for super block */
  5462. spin_lock(&info->delalloc_root_lock);
  5463. old_val = btrfs_super_bytes_used(info->super_copy);
  5464. if (alloc)
  5465. old_val += num_bytes;
  5466. else
  5467. old_val -= num_bytes;
  5468. btrfs_set_super_bytes_used(info->super_copy, old_val);
  5469. spin_unlock(&info->delalloc_root_lock);
  5470. while (total) {
  5471. cache = btrfs_lookup_block_group(info, bytenr);
  5472. if (!cache)
  5473. return -ENOENT;
  5474. if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
  5475. BTRFS_BLOCK_GROUP_RAID1 |
  5476. BTRFS_BLOCK_GROUP_RAID10))
  5477. factor = 2;
  5478. else
  5479. factor = 1;
  5480. /*
  5481. * If this block group has free space cache written out, we
  5482. * need to make sure to load it if we are removing space. This
  5483. * is because we need the unpinning stage to actually add the
  5484. * space back to the block group, otherwise we will leak space.
  5485. */
  5486. if (!alloc && cache->cached == BTRFS_CACHE_NO)
  5487. cache_block_group(cache, 1);
  5488. byte_in_group = bytenr - cache->key.objectid;
  5489. WARN_ON(byte_in_group > cache->key.offset);
  5490. spin_lock(&cache->space_info->lock);
  5491. spin_lock(&cache->lock);
  5492. if (btrfs_test_opt(info, SPACE_CACHE) &&
  5493. cache->disk_cache_state < BTRFS_DC_CLEAR)
  5494. cache->disk_cache_state = BTRFS_DC_CLEAR;
  5495. old_val = btrfs_block_group_used(&cache->item);
  5496. num_bytes = min(total, cache->key.offset - byte_in_group);
  5497. if (alloc) {
  5498. old_val += num_bytes;
  5499. btrfs_set_block_group_used(&cache->item, old_val);
  5500. cache->reserved -= num_bytes;
  5501. cache->space_info->bytes_reserved -= num_bytes;
  5502. cache->space_info->bytes_used += num_bytes;
  5503. cache->space_info->disk_used += num_bytes * factor;
  5504. spin_unlock(&cache->lock);
  5505. spin_unlock(&cache->space_info->lock);
  5506. } else {
  5507. old_val -= num_bytes;
  5508. btrfs_set_block_group_used(&cache->item, old_val);
  5509. cache->pinned += num_bytes;
  5510. cache->space_info->bytes_pinned += num_bytes;
  5511. cache->space_info->bytes_used -= num_bytes;
  5512. cache->space_info->disk_used -= num_bytes * factor;
  5513. spin_unlock(&cache->lock);
  5514. spin_unlock(&cache->space_info->lock);
  5515. trace_btrfs_space_reservation(info, "pinned",
  5516. cache->space_info->flags,
  5517. num_bytes, 1);
  5518. set_extent_dirty(info->pinned_extents,
  5519. bytenr, bytenr + num_bytes - 1,
  5520. GFP_NOFS | __GFP_NOFAIL);
  5521. }
  5522. spin_lock(&trans->transaction->dirty_bgs_lock);
  5523. if (list_empty(&cache->dirty_list)) {
  5524. list_add_tail(&cache->dirty_list,
  5525. &trans->transaction->dirty_bgs);
  5526. trans->transaction->num_dirty_bgs++;
  5527. btrfs_get_block_group(cache);
  5528. }
  5529. spin_unlock(&trans->transaction->dirty_bgs_lock);
  5530. /*
  5531. * No longer have used bytes in this block group, queue it for
  5532. * deletion. We do this after adding the block group to the
  5533. * dirty list to avoid races between cleaner kthread and space
  5534. * cache writeout.
  5535. */
  5536. if (!alloc && old_val == 0) {
  5537. spin_lock(&info->unused_bgs_lock);
  5538. if (list_empty(&cache->bg_list)) {
  5539. btrfs_get_block_group(cache);
  5540. list_add_tail(&cache->bg_list,
  5541. &info->unused_bgs);
  5542. }
  5543. spin_unlock(&info->unused_bgs_lock);
  5544. }
  5545. btrfs_put_block_group(cache);
  5546. total -= num_bytes;
  5547. bytenr += num_bytes;
  5548. }
  5549. return 0;
  5550. }
  5551. static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
  5552. {
  5553. struct btrfs_block_group_cache *cache;
  5554. u64 bytenr;
  5555. spin_lock(&fs_info->block_group_cache_lock);
  5556. bytenr = fs_info->first_logical_byte;
  5557. spin_unlock(&fs_info->block_group_cache_lock);
  5558. if (bytenr < (u64)-1)
  5559. return bytenr;
  5560. cache = btrfs_lookup_first_block_group(fs_info, search_start);
  5561. if (!cache)
  5562. return 0;
  5563. bytenr = cache->key.objectid;
  5564. btrfs_put_block_group(cache);
  5565. return bytenr;
  5566. }
  5567. static int pin_down_extent(struct btrfs_fs_info *fs_info,
  5568. struct btrfs_block_group_cache *cache,
  5569. u64 bytenr, u64 num_bytes, int reserved)
  5570. {
  5571. spin_lock(&cache->space_info->lock);
  5572. spin_lock(&cache->lock);
  5573. cache->pinned += num_bytes;
  5574. cache->space_info->bytes_pinned += num_bytes;
  5575. if (reserved) {
  5576. cache->reserved -= num_bytes;
  5577. cache->space_info->bytes_reserved -= num_bytes;
  5578. }
  5579. spin_unlock(&cache->lock);
  5580. spin_unlock(&cache->space_info->lock);
  5581. trace_btrfs_space_reservation(fs_info, "pinned",
  5582. cache->space_info->flags, num_bytes, 1);
  5583. set_extent_dirty(fs_info->pinned_extents, bytenr,
  5584. bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
  5585. return 0;
  5586. }
  5587. /*
  5588. * this function must be called within transaction
  5589. */
  5590. int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
  5591. u64 bytenr, u64 num_bytes, int reserved)
  5592. {
  5593. struct btrfs_block_group_cache *cache;
  5594. cache = btrfs_lookup_block_group(fs_info, bytenr);
  5595. BUG_ON(!cache); /* Logic error */
  5596. pin_down_extent(fs_info, cache, bytenr, num_bytes, reserved);
  5597. btrfs_put_block_group(cache);
  5598. return 0;
  5599. }
  5600. /*
  5601. * this function must be called within transaction
  5602. */
  5603. int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
  5604. u64 bytenr, u64 num_bytes)
  5605. {
  5606. struct btrfs_block_group_cache *cache;
  5607. int ret;
  5608. cache = btrfs_lookup_block_group(fs_info, bytenr);
  5609. if (!cache)
  5610. return -EINVAL;
  5611. /*
  5612. * pull in the free space cache (if any) so that our pin
  5613. * removes the free space from the cache. We have load_only set
  5614. * to one because the slow code to read in the free extents does check
  5615. * the pinned extents.
  5616. */
  5617. cache_block_group(cache, 1);
  5618. pin_down_extent(fs_info, cache, bytenr, num_bytes, 0);
  5619. /* remove us from the free space cache (if we're there at all) */
  5620. ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
  5621. btrfs_put_block_group(cache);
  5622. return ret;
  5623. }
  5624. static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
  5625. u64 start, u64 num_bytes)
  5626. {
  5627. int ret;
  5628. struct btrfs_block_group_cache *block_group;
  5629. struct btrfs_caching_control *caching_ctl;
  5630. block_group = btrfs_lookup_block_group(fs_info, start);
  5631. if (!block_group)
  5632. return -EINVAL;
  5633. cache_block_group(block_group, 0);
  5634. caching_ctl = get_caching_control(block_group);
  5635. if (!caching_ctl) {
  5636. /* Logic error */
  5637. BUG_ON(!block_group_cache_done(block_group));
  5638. ret = btrfs_remove_free_space(block_group, start, num_bytes);
  5639. } else {
  5640. mutex_lock(&caching_ctl->mutex);
  5641. if (start >= caching_ctl->progress) {
  5642. ret = add_excluded_extent(fs_info, start, num_bytes);
  5643. } else if (start + num_bytes <= caching_ctl->progress) {
  5644. ret = btrfs_remove_free_space(block_group,
  5645. start, num_bytes);
  5646. } else {
  5647. num_bytes = caching_ctl->progress - start;
  5648. ret = btrfs_remove_free_space(block_group,
  5649. start, num_bytes);
  5650. if (ret)
  5651. goto out_lock;
  5652. num_bytes = (start + num_bytes) -
  5653. caching_ctl->progress;
  5654. start = caching_ctl->progress;
  5655. ret = add_excluded_extent(fs_info, start, num_bytes);
  5656. }
  5657. out_lock:
  5658. mutex_unlock(&caching_ctl->mutex);
  5659. put_caching_control(caching_ctl);
  5660. }
  5661. btrfs_put_block_group(block_group);
  5662. return ret;
  5663. }
  5664. int btrfs_exclude_logged_extents(struct btrfs_fs_info *fs_info,
  5665. struct extent_buffer *eb)
  5666. {
  5667. struct btrfs_file_extent_item *item;
  5668. struct btrfs_key key;
  5669. int found_type;
  5670. int i;
  5671. if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
  5672. return 0;
  5673. for (i = 0; i < btrfs_header_nritems(eb); i++) {
  5674. btrfs_item_key_to_cpu(eb, &key, i);
  5675. if (key.type != BTRFS_EXTENT_DATA_KEY)
  5676. continue;
  5677. item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
  5678. found_type = btrfs_file_extent_type(eb, item);
  5679. if (found_type == BTRFS_FILE_EXTENT_INLINE)
  5680. continue;
  5681. if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
  5682. continue;
  5683. key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
  5684. key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
  5685. __exclude_logged_extent(fs_info, key.objectid, key.offset);
  5686. }
  5687. return 0;
  5688. }
  5689. static void
  5690. btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
  5691. {
  5692. atomic_inc(&bg->reservations);
  5693. }
  5694. void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
  5695. const u64 start)
  5696. {
  5697. struct btrfs_block_group_cache *bg;
  5698. bg = btrfs_lookup_block_group(fs_info, start);
  5699. ASSERT(bg);
  5700. if (atomic_dec_and_test(&bg->reservations))
  5701. wake_up_atomic_t(&bg->reservations);
  5702. btrfs_put_block_group(bg);
  5703. }
  5704. static int btrfs_wait_bg_reservations_atomic_t(atomic_t *a)
  5705. {
  5706. schedule();
  5707. return 0;
  5708. }
  5709. void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
  5710. {
  5711. struct btrfs_space_info *space_info = bg->space_info;
  5712. ASSERT(bg->ro);
  5713. if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
  5714. return;
  5715. /*
  5716. * Our block group is read only but before we set it to read only,
  5717. * some task might have had allocated an extent from it already, but it
  5718. * has not yet created a respective ordered extent (and added it to a
  5719. * root's list of ordered extents).
  5720. * Therefore wait for any task currently allocating extents, since the
  5721. * block group's reservations counter is incremented while a read lock
  5722. * on the groups' semaphore is held and decremented after releasing
  5723. * the read access on that semaphore and creating the ordered extent.
  5724. */
  5725. down_write(&space_info->groups_sem);
  5726. up_write(&space_info->groups_sem);
  5727. wait_on_atomic_t(&bg->reservations,
  5728. btrfs_wait_bg_reservations_atomic_t,
  5729. TASK_UNINTERRUPTIBLE);
  5730. }
  5731. /**
  5732. * btrfs_add_reserved_bytes - update the block_group and space info counters
  5733. * @cache: The cache we are manipulating
  5734. * @ram_bytes: The number of bytes of file content, and will be same to
  5735. * @num_bytes except for the compress path.
  5736. * @num_bytes: The number of bytes in question
  5737. * @delalloc: The blocks are allocated for the delalloc write
  5738. *
  5739. * This is called by the allocator when it reserves space. If this is a
  5740. * reservation and the block group has become read only we cannot make the
  5741. * reservation and return -EAGAIN, otherwise this function always succeeds.
  5742. */
  5743. static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
  5744. u64 ram_bytes, u64 num_bytes, int delalloc)
  5745. {
  5746. struct btrfs_space_info *space_info = cache->space_info;
  5747. int ret = 0;
  5748. spin_lock(&space_info->lock);
  5749. spin_lock(&cache->lock);
  5750. if (cache->ro) {
  5751. ret = -EAGAIN;
  5752. } else {
  5753. cache->reserved += num_bytes;
  5754. space_info->bytes_reserved += num_bytes;
  5755. trace_btrfs_space_reservation(cache->fs_info,
  5756. "space_info", space_info->flags,
  5757. ram_bytes, 0);
  5758. space_info->bytes_may_use -= ram_bytes;
  5759. if (delalloc)
  5760. cache->delalloc_bytes += num_bytes;
  5761. }
  5762. spin_unlock(&cache->lock);
  5763. spin_unlock(&space_info->lock);
  5764. return ret;
  5765. }
  5766. /**
  5767. * btrfs_free_reserved_bytes - update the block_group and space info counters
  5768. * @cache: The cache we are manipulating
  5769. * @num_bytes: The number of bytes in question
  5770. * @delalloc: The blocks are allocated for the delalloc write
  5771. *
  5772. * This is called by somebody who is freeing space that was never actually used
  5773. * on disk. For example if you reserve some space for a new leaf in transaction
  5774. * A and before transaction A commits you free that leaf, you call this with
  5775. * reserve set to 0 in order to clear the reservation.
  5776. */
  5777. static int btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
  5778. u64 num_bytes, int delalloc)
  5779. {
  5780. struct btrfs_space_info *space_info = cache->space_info;
  5781. int ret = 0;
  5782. spin_lock(&space_info->lock);
  5783. spin_lock(&cache->lock);
  5784. if (cache->ro)
  5785. space_info->bytes_readonly += num_bytes;
  5786. cache->reserved -= num_bytes;
  5787. space_info->bytes_reserved -= num_bytes;
  5788. if (delalloc)
  5789. cache->delalloc_bytes -= num_bytes;
  5790. spin_unlock(&cache->lock);
  5791. spin_unlock(&space_info->lock);
  5792. return ret;
  5793. }
  5794. void btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
  5795. struct btrfs_fs_info *fs_info)
  5796. {
  5797. struct btrfs_caching_control *next;
  5798. struct btrfs_caching_control *caching_ctl;
  5799. struct btrfs_block_group_cache *cache;
  5800. down_write(&fs_info->commit_root_sem);
  5801. list_for_each_entry_safe(caching_ctl, next,
  5802. &fs_info->caching_block_groups, list) {
  5803. cache = caching_ctl->block_group;
  5804. if (block_group_cache_done(cache)) {
  5805. cache->last_byte_to_unpin = (u64)-1;
  5806. list_del_init(&caching_ctl->list);
  5807. put_caching_control(caching_ctl);
  5808. } else {
  5809. cache->last_byte_to_unpin = caching_ctl->progress;
  5810. }
  5811. }
  5812. if (fs_info->pinned_extents == &fs_info->freed_extents[0])
  5813. fs_info->pinned_extents = &fs_info->freed_extents[1];
  5814. else
  5815. fs_info->pinned_extents = &fs_info->freed_extents[0];
  5816. up_write(&fs_info->commit_root_sem);
  5817. update_global_block_rsv(fs_info);
  5818. }
  5819. /*
  5820. * Returns the free cluster for the given space info and sets empty_cluster to
  5821. * what it should be based on the mount options.
  5822. */
  5823. static struct btrfs_free_cluster *
  5824. fetch_cluster_info(struct btrfs_fs_info *fs_info,
  5825. struct btrfs_space_info *space_info, u64 *empty_cluster)
  5826. {
  5827. struct btrfs_free_cluster *ret = NULL;
  5828. bool ssd = btrfs_test_opt(fs_info, SSD);
  5829. *empty_cluster = 0;
  5830. if (btrfs_mixed_space_info(space_info))
  5831. return ret;
  5832. if (ssd)
  5833. *empty_cluster = SZ_2M;
  5834. if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
  5835. ret = &fs_info->meta_alloc_cluster;
  5836. if (!ssd)
  5837. *empty_cluster = SZ_64K;
  5838. } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) && ssd) {
  5839. ret = &fs_info->data_alloc_cluster;
  5840. }
  5841. return ret;
  5842. }
  5843. static int unpin_extent_range(struct btrfs_fs_info *fs_info,
  5844. u64 start, u64 end,
  5845. const bool return_free_space)
  5846. {
  5847. struct btrfs_block_group_cache *cache = NULL;
  5848. struct btrfs_space_info *space_info;
  5849. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  5850. struct btrfs_free_cluster *cluster = NULL;
  5851. u64 len;
  5852. u64 total_unpinned = 0;
  5853. u64 empty_cluster = 0;
  5854. bool readonly;
  5855. while (start <= end) {
  5856. readonly = false;
  5857. if (!cache ||
  5858. start >= cache->key.objectid + cache->key.offset) {
  5859. if (cache)
  5860. btrfs_put_block_group(cache);
  5861. total_unpinned = 0;
  5862. cache = btrfs_lookup_block_group(fs_info, start);
  5863. BUG_ON(!cache); /* Logic error */
  5864. cluster = fetch_cluster_info(fs_info,
  5865. cache->space_info,
  5866. &empty_cluster);
  5867. empty_cluster <<= 1;
  5868. }
  5869. len = cache->key.objectid + cache->key.offset - start;
  5870. len = min(len, end + 1 - start);
  5871. if (start < cache->last_byte_to_unpin) {
  5872. len = min(len, cache->last_byte_to_unpin - start);
  5873. if (return_free_space)
  5874. btrfs_add_free_space(cache, start, len);
  5875. }
  5876. start += len;
  5877. total_unpinned += len;
  5878. space_info = cache->space_info;
  5879. /*
  5880. * If this space cluster has been marked as fragmented and we've
  5881. * unpinned enough in this block group to potentially allow a
  5882. * cluster to be created inside of it go ahead and clear the
  5883. * fragmented check.
  5884. */
  5885. if (cluster && cluster->fragmented &&
  5886. total_unpinned > empty_cluster) {
  5887. spin_lock(&cluster->lock);
  5888. cluster->fragmented = 0;
  5889. spin_unlock(&cluster->lock);
  5890. }
  5891. spin_lock(&space_info->lock);
  5892. spin_lock(&cache->lock);
  5893. cache->pinned -= len;
  5894. space_info->bytes_pinned -= len;
  5895. trace_btrfs_space_reservation(fs_info, "pinned",
  5896. space_info->flags, len, 0);
  5897. space_info->max_extent_size = 0;
  5898. percpu_counter_add(&space_info->total_bytes_pinned, -len);
  5899. if (cache->ro) {
  5900. space_info->bytes_readonly += len;
  5901. readonly = true;
  5902. }
  5903. spin_unlock(&cache->lock);
  5904. if (!readonly && return_free_space &&
  5905. global_rsv->space_info == space_info) {
  5906. u64 to_add = len;
  5907. WARN_ON(!return_free_space);
  5908. spin_lock(&global_rsv->lock);
  5909. if (!global_rsv->full) {
  5910. to_add = min(len, global_rsv->size -
  5911. global_rsv->reserved);
  5912. global_rsv->reserved += to_add;
  5913. space_info->bytes_may_use += to_add;
  5914. if (global_rsv->reserved >= global_rsv->size)
  5915. global_rsv->full = 1;
  5916. trace_btrfs_space_reservation(fs_info,
  5917. "space_info",
  5918. space_info->flags,
  5919. to_add, 1);
  5920. len -= to_add;
  5921. }
  5922. spin_unlock(&global_rsv->lock);
  5923. /* Add to any tickets we may have */
  5924. if (len)
  5925. space_info_add_new_bytes(fs_info, space_info,
  5926. len);
  5927. }
  5928. spin_unlock(&space_info->lock);
  5929. }
  5930. if (cache)
  5931. btrfs_put_block_group(cache);
  5932. return 0;
  5933. }
  5934. int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
  5935. struct btrfs_fs_info *fs_info)
  5936. {
  5937. struct btrfs_block_group_cache *block_group, *tmp;
  5938. struct list_head *deleted_bgs;
  5939. struct extent_io_tree *unpin;
  5940. u64 start;
  5941. u64 end;
  5942. int ret;
  5943. if (fs_info->pinned_extents == &fs_info->freed_extents[0])
  5944. unpin = &fs_info->freed_extents[1];
  5945. else
  5946. unpin = &fs_info->freed_extents[0];
  5947. while (!trans->aborted) {
  5948. mutex_lock(&fs_info->unused_bg_unpin_mutex);
  5949. ret = find_first_extent_bit(unpin, 0, &start, &end,
  5950. EXTENT_DIRTY, NULL);
  5951. if (ret) {
  5952. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  5953. break;
  5954. }
  5955. if (btrfs_test_opt(fs_info, DISCARD))
  5956. ret = btrfs_discard_extent(fs_info, start,
  5957. end + 1 - start, NULL);
  5958. clear_extent_dirty(unpin, start, end);
  5959. unpin_extent_range(fs_info, start, end, true);
  5960. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  5961. cond_resched();
  5962. }
  5963. /*
  5964. * Transaction is finished. We don't need the lock anymore. We
  5965. * do need to clean up the block groups in case of a transaction
  5966. * abort.
  5967. */
  5968. deleted_bgs = &trans->transaction->deleted_bgs;
  5969. list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
  5970. u64 trimmed = 0;
  5971. ret = -EROFS;
  5972. if (!trans->aborted)
  5973. ret = btrfs_discard_extent(fs_info,
  5974. block_group->key.objectid,
  5975. block_group->key.offset,
  5976. &trimmed);
  5977. list_del_init(&block_group->bg_list);
  5978. btrfs_put_block_group_trimming(block_group);
  5979. btrfs_put_block_group(block_group);
  5980. if (ret) {
  5981. const char *errstr = btrfs_decode_error(ret);
  5982. btrfs_warn(fs_info,
  5983. "Discard failed while removing blockgroup: errno=%d %s\n",
  5984. ret, errstr);
  5985. }
  5986. }
  5987. return 0;
  5988. }
  5989. static void add_pinned_bytes(struct btrfs_fs_info *fs_info, u64 num_bytes,
  5990. u64 owner, u64 root_objectid)
  5991. {
  5992. struct btrfs_space_info *space_info;
  5993. u64 flags;
  5994. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  5995. if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
  5996. flags = BTRFS_BLOCK_GROUP_SYSTEM;
  5997. else
  5998. flags = BTRFS_BLOCK_GROUP_METADATA;
  5999. } else {
  6000. flags = BTRFS_BLOCK_GROUP_DATA;
  6001. }
  6002. space_info = __find_space_info(fs_info, flags);
  6003. BUG_ON(!space_info); /* Logic bug */
  6004. percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
  6005. }
  6006. static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
  6007. struct btrfs_fs_info *info,
  6008. struct btrfs_delayed_ref_node *node, u64 parent,
  6009. u64 root_objectid, u64 owner_objectid,
  6010. u64 owner_offset, int refs_to_drop,
  6011. struct btrfs_delayed_extent_op *extent_op)
  6012. {
  6013. struct btrfs_key key;
  6014. struct btrfs_path *path;
  6015. struct btrfs_root *extent_root = info->extent_root;
  6016. struct extent_buffer *leaf;
  6017. struct btrfs_extent_item *ei;
  6018. struct btrfs_extent_inline_ref *iref;
  6019. int ret;
  6020. int is_data;
  6021. int extent_slot = 0;
  6022. int found_extent = 0;
  6023. int num_to_del = 1;
  6024. u32 item_size;
  6025. u64 refs;
  6026. u64 bytenr = node->bytenr;
  6027. u64 num_bytes = node->num_bytes;
  6028. int last_ref = 0;
  6029. bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
  6030. path = btrfs_alloc_path();
  6031. if (!path)
  6032. return -ENOMEM;
  6033. path->reada = READA_FORWARD;
  6034. path->leave_spinning = 1;
  6035. is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
  6036. BUG_ON(!is_data && refs_to_drop != 1);
  6037. if (is_data)
  6038. skinny_metadata = 0;
  6039. ret = lookup_extent_backref(trans, extent_root, path, &iref,
  6040. bytenr, num_bytes, parent,
  6041. root_objectid, owner_objectid,
  6042. owner_offset);
  6043. if (ret == 0) {
  6044. extent_slot = path->slots[0];
  6045. while (extent_slot >= 0) {
  6046. btrfs_item_key_to_cpu(path->nodes[0], &key,
  6047. extent_slot);
  6048. if (key.objectid != bytenr)
  6049. break;
  6050. if (key.type == BTRFS_EXTENT_ITEM_KEY &&
  6051. key.offset == num_bytes) {
  6052. found_extent = 1;
  6053. break;
  6054. }
  6055. if (key.type == BTRFS_METADATA_ITEM_KEY &&
  6056. key.offset == owner_objectid) {
  6057. found_extent = 1;
  6058. break;
  6059. }
  6060. if (path->slots[0] - extent_slot > 5)
  6061. break;
  6062. extent_slot--;
  6063. }
  6064. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  6065. item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
  6066. if (found_extent && item_size < sizeof(*ei))
  6067. found_extent = 0;
  6068. #endif
  6069. if (!found_extent) {
  6070. BUG_ON(iref);
  6071. ret = remove_extent_backref(trans, extent_root, path,
  6072. NULL, refs_to_drop,
  6073. is_data, &last_ref);
  6074. if (ret) {
  6075. btrfs_abort_transaction(trans, ret);
  6076. goto out;
  6077. }
  6078. btrfs_release_path(path);
  6079. path->leave_spinning = 1;
  6080. key.objectid = bytenr;
  6081. key.type = BTRFS_EXTENT_ITEM_KEY;
  6082. key.offset = num_bytes;
  6083. if (!is_data && skinny_metadata) {
  6084. key.type = BTRFS_METADATA_ITEM_KEY;
  6085. key.offset = owner_objectid;
  6086. }
  6087. ret = btrfs_search_slot(trans, extent_root,
  6088. &key, path, -1, 1);
  6089. if (ret > 0 && skinny_metadata && path->slots[0]) {
  6090. /*
  6091. * Couldn't find our skinny metadata item,
  6092. * see if we have ye olde extent item.
  6093. */
  6094. path->slots[0]--;
  6095. btrfs_item_key_to_cpu(path->nodes[0], &key,
  6096. path->slots[0]);
  6097. if (key.objectid == bytenr &&
  6098. key.type == BTRFS_EXTENT_ITEM_KEY &&
  6099. key.offset == num_bytes)
  6100. ret = 0;
  6101. }
  6102. if (ret > 0 && skinny_metadata) {
  6103. skinny_metadata = false;
  6104. key.objectid = bytenr;
  6105. key.type = BTRFS_EXTENT_ITEM_KEY;
  6106. key.offset = num_bytes;
  6107. btrfs_release_path(path);
  6108. ret = btrfs_search_slot(trans, extent_root,
  6109. &key, path, -1, 1);
  6110. }
  6111. if (ret) {
  6112. btrfs_err(info,
  6113. "umm, got %d back from search, was looking for %llu",
  6114. ret, bytenr);
  6115. if (ret > 0)
  6116. btrfs_print_leaf(info, path->nodes[0]);
  6117. }
  6118. if (ret < 0) {
  6119. btrfs_abort_transaction(trans, ret);
  6120. goto out;
  6121. }
  6122. extent_slot = path->slots[0];
  6123. }
  6124. } else if (WARN_ON(ret == -ENOENT)) {
  6125. btrfs_print_leaf(info, path->nodes[0]);
  6126. btrfs_err(info,
  6127. "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
  6128. bytenr, parent, root_objectid, owner_objectid,
  6129. owner_offset);
  6130. btrfs_abort_transaction(trans, ret);
  6131. goto out;
  6132. } else {
  6133. btrfs_abort_transaction(trans, ret);
  6134. goto out;
  6135. }
  6136. leaf = path->nodes[0];
  6137. item_size = btrfs_item_size_nr(leaf, extent_slot);
  6138. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  6139. if (item_size < sizeof(*ei)) {
  6140. BUG_ON(found_extent || extent_slot != path->slots[0]);
  6141. ret = convert_extent_item_v0(trans, extent_root, path,
  6142. owner_objectid, 0);
  6143. if (ret < 0) {
  6144. btrfs_abort_transaction(trans, ret);
  6145. goto out;
  6146. }
  6147. btrfs_release_path(path);
  6148. path->leave_spinning = 1;
  6149. key.objectid = bytenr;
  6150. key.type = BTRFS_EXTENT_ITEM_KEY;
  6151. key.offset = num_bytes;
  6152. ret = btrfs_search_slot(trans, extent_root, &key, path,
  6153. -1, 1);
  6154. if (ret) {
  6155. btrfs_err(info,
  6156. "umm, got %d back from search, was looking for %llu",
  6157. ret, bytenr);
  6158. btrfs_print_leaf(info, path->nodes[0]);
  6159. }
  6160. if (ret < 0) {
  6161. btrfs_abort_transaction(trans, ret);
  6162. goto out;
  6163. }
  6164. extent_slot = path->slots[0];
  6165. leaf = path->nodes[0];
  6166. item_size = btrfs_item_size_nr(leaf, extent_slot);
  6167. }
  6168. #endif
  6169. BUG_ON(item_size < sizeof(*ei));
  6170. ei = btrfs_item_ptr(leaf, extent_slot,
  6171. struct btrfs_extent_item);
  6172. if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
  6173. key.type == BTRFS_EXTENT_ITEM_KEY) {
  6174. struct btrfs_tree_block_info *bi;
  6175. BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
  6176. bi = (struct btrfs_tree_block_info *)(ei + 1);
  6177. WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
  6178. }
  6179. refs = btrfs_extent_refs(leaf, ei);
  6180. if (refs < refs_to_drop) {
  6181. btrfs_err(info,
  6182. "trying to drop %d refs but we only have %Lu for bytenr %Lu",
  6183. refs_to_drop, refs, bytenr);
  6184. ret = -EINVAL;
  6185. btrfs_abort_transaction(trans, ret);
  6186. goto out;
  6187. }
  6188. refs -= refs_to_drop;
  6189. if (refs > 0) {
  6190. if (extent_op)
  6191. __run_delayed_extent_op(extent_op, leaf, ei);
  6192. /*
  6193. * In the case of inline back ref, reference count will
  6194. * be updated by remove_extent_backref
  6195. */
  6196. if (iref) {
  6197. BUG_ON(!found_extent);
  6198. } else {
  6199. btrfs_set_extent_refs(leaf, ei, refs);
  6200. btrfs_mark_buffer_dirty(leaf);
  6201. }
  6202. if (found_extent) {
  6203. ret = remove_extent_backref(trans, extent_root, path,
  6204. iref, refs_to_drop,
  6205. is_data, &last_ref);
  6206. if (ret) {
  6207. btrfs_abort_transaction(trans, ret);
  6208. goto out;
  6209. }
  6210. }
  6211. add_pinned_bytes(info, -num_bytes, owner_objectid,
  6212. root_objectid);
  6213. } else {
  6214. if (found_extent) {
  6215. BUG_ON(is_data && refs_to_drop !=
  6216. extent_data_ref_count(path, iref));
  6217. if (iref) {
  6218. BUG_ON(path->slots[0] != extent_slot);
  6219. } else {
  6220. BUG_ON(path->slots[0] != extent_slot + 1);
  6221. path->slots[0] = extent_slot;
  6222. num_to_del = 2;
  6223. }
  6224. }
  6225. last_ref = 1;
  6226. ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
  6227. num_to_del);
  6228. if (ret) {
  6229. btrfs_abort_transaction(trans, ret);
  6230. goto out;
  6231. }
  6232. btrfs_release_path(path);
  6233. if (is_data) {
  6234. ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
  6235. if (ret) {
  6236. btrfs_abort_transaction(trans, ret);
  6237. goto out;
  6238. }
  6239. }
  6240. ret = add_to_free_space_tree(trans, info, bytenr, num_bytes);
  6241. if (ret) {
  6242. btrfs_abort_transaction(trans, ret);
  6243. goto out;
  6244. }
  6245. ret = update_block_group(trans, info, bytenr, num_bytes, 0);
  6246. if (ret) {
  6247. btrfs_abort_transaction(trans, ret);
  6248. goto out;
  6249. }
  6250. }
  6251. btrfs_release_path(path);
  6252. out:
  6253. btrfs_free_path(path);
  6254. return ret;
  6255. }
  6256. /*
  6257. * when we free an block, it is possible (and likely) that we free the last
  6258. * delayed ref for that extent as well. This searches the delayed ref tree for
  6259. * a given extent, and if there are no other delayed refs to be processed, it
  6260. * removes it from the tree.
  6261. */
  6262. static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
  6263. u64 bytenr)
  6264. {
  6265. struct btrfs_delayed_ref_head *head;
  6266. struct btrfs_delayed_ref_root *delayed_refs;
  6267. int ret = 0;
  6268. delayed_refs = &trans->transaction->delayed_refs;
  6269. spin_lock(&delayed_refs->lock);
  6270. head = btrfs_find_delayed_ref_head(trans, bytenr);
  6271. if (!head)
  6272. goto out_delayed_unlock;
  6273. spin_lock(&head->lock);
  6274. if (!list_empty(&head->ref_list))
  6275. goto out;
  6276. if (head->extent_op) {
  6277. if (!head->must_insert_reserved)
  6278. goto out;
  6279. btrfs_free_delayed_extent_op(head->extent_op);
  6280. head->extent_op = NULL;
  6281. }
  6282. /*
  6283. * waiting for the lock here would deadlock. If someone else has it
  6284. * locked they are already in the process of dropping it anyway
  6285. */
  6286. if (!mutex_trylock(&head->mutex))
  6287. goto out;
  6288. /*
  6289. * at this point we have a head with no other entries. Go
  6290. * ahead and process it.
  6291. */
  6292. head->node.in_tree = 0;
  6293. rb_erase(&head->href_node, &delayed_refs->href_root);
  6294. atomic_dec(&delayed_refs->num_entries);
  6295. /*
  6296. * we don't take a ref on the node because we're removing it from the
  6297. * tree, so we just steal the ref the tree was holding.
  6298. */
  6299. delayed_refs->num_heads--;
  6300. if (head->processing == 0)
  6301. delayed_refs->num_heads_ready--;
  6302. head->processing = 0;
  6303. spin_unlock(&head->lock);
  6304. spin_unlock(&delayed_refs->lock);
  6305. BUG_ON(head->extent_op);
  6306. if (head->must_insert_reserved)
  6307. ret = 1;
  6308. mutex_unlock(&head->mutex);
  6309. btrfs_put_delayed_ref(&head->node);
  6310. return ret;
  6311. out:
  6312. spin_unlock(&head->lock);
  6313. out_delayed_unlock:
  6314. spin_unlock(&delayed_refs->lock);
  6315. return 0;
  6316. }
  6317. void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
  6318. struct btrfs_root *root,
  6319. struct extent_buffer *buf,
  6320. u64 parent, int last_ref)
  6321. {
  6322. struct btrfs_fs_info *fs_info = root->fs_info;
  6323. int pin = 1;
  6324. int ret;
  6325. if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
  6326. ret = btrfs_add_delayed_tree_ref(fs_info, trans,
  6327. buf->start, buf->len,
  6328. parent,
  6329. root->root_key.objectid,
  6330. btrfs_header_level(buf),
  6331. BTRFS_DROP_DELAYED_REF, NULL);
  6332. BUG_ON(ret); /* -ENOMEM */
  6333. }
  6334. if (!last_ref)
  6335. return;
  6336. if (btrfs_header_generation(buf) == trans->transid) {
  6337. struct btrfs_block_group_cache *cache;
  6338. if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
  6339. ret = check_ref_cleanup(trans, buf->start);
  6340. if (!ret)
  6341. goto out;
  6342. }
  6343. cache = btrfs_lookup_block_group(fs_info, buf->start);
  6344. if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
  6345. pin_down_extent(fs_info, cache, buf->start,
  6346. buf->len, 1);
  6347. btrfs_put_block_group(cache);
  6348. goto out;
  6349. }
  6350. WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
  6351. btrfs_add_free_space(cache, buf->start, buf->len);
  6352. btrfs_free_reserved_bytes(cache, buf->len, 0);
  6353. btrfs_put_block_group(cache);
  6354. trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
  6355. pin = 0;
  6356. }
  6357. out:
  6358. if (pin)
  6359. add_pinned_bytes(fs_info, buf->len, btrfs_header_level(buf),
  6360. root->root_key.objectid);
  6361. /*
  6362. * Deleting the buffer, clear the corrupt flag since it doesn't matter
  6363. * anymore.
  6364. */
  6365. clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
  6366. }
  6367. /* Can return -ENOMEM */
  6368. int btrfs_free_extent(struct btrfs_trans_handle *trans,
  6369. struct btrfs_fs_info *fs_info,
  6370. u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
  6371. u64 owner, u64 offset)
  6372. {
  6373. int ret;
  6374. if (btrfs_is_testing(fs_info))
  6375. return 0;
  6376. add_pinned_bytes(fs_info, num_bytes, owner, root_objectid);
  6377. /*
  6378. * tree log blocks never actually go into the extent allocation
  6379. * tree, just update pinning info and exit early.
  6380. */
  6381. if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
  6382. WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
  6383. /* unlocks the pinned mutex */
  6384. btrfs_pin_extent(fs_info, bytenr, num_bytes, 1);
  6385. ret = 0;
  6386. } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  6387. ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
  6388. num_bytes,
  6389. parent, root_objectid, (int)owner,
  6390. BTRFS_DROP_DELAYED_REF, NULL);
  6391. } else {
  6392. ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
  6393. num_bytes,
  6394. parent, root_objectid, owner,
  6395. offset, 0,
  6396. BTRFS_DROP_DELAYED_REF);
  6397. }
  6398. return ret;
  6399. }
  6400. /*
  6401. * when we wait for progress in the block group caching, its because
  6402. * our allocation attempt failed at least once. So, we must sleep
  6403. * and let some progress happen before we try again.
  6404. *
  6405. * This function will sleep at least once waiting for new free space to
  6406. * show up, and then it will check the block group free space numbers
  6407. * for our min num_bytes. Another option is to have it go ahead
  6408. * and look in the rbtree for a free extent of a given size, but this
  6409. * is a good start.
  6410. *
  6411. * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
  6412. * any of the information in this block group.
  6413. */
  6414. static noinline void
  6415. wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
  6416. u64 num_bytes)
  6417. {
  6418. struct btrfs_caching_control *caching_ctl;
  6419. caching_ctl = get_caching_control(cache);
  6420. if (!caching_ctl)
  6421. return;
  6422. wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
  6423. (cache->free_space_ctl->free_space >= num_bytes));
  6424. put_caching_control(caching_ctl);
  6425. }
  6426. static noinline int
  6427. wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
  6428. {
  6429. struct btrfs_caching_control *caching_ctl;
  6430. int ret = 0;
  6431. caching_ctl = get_caching_control(cache);
  6432. if (!caching_ctl)
  6433. return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
  6434. wait_event(caching_ctl->wait, block_group_cache_done(cache));
  6435. if (cache->cached == BTRFS_CACHE_ERROR)
  6436. ret = -EIO;
  6437. put_caching_control(caching_ctl);
  6438. return ret;
  6439. }
  6440. int __get_raid_index(u64 flags)
  6441. {
  6442. if (flags & BTRFS_BLOCK_GROUP_RAID10)
  6443. return BTRFS_RAID_RAID10;
  6444. else if (flags & BTRFS_BLOCK_GROUP_RAID1)
  6445. return BTRFS_RAID_RAID1;
  6446. else if (flags & BTRFS_BLOCK_GROUP_DUP)
  6447. return BTRFS_RAID_DUP;
  6448. else if (flags & BTRFS_BLOCK_GROUP_RAID0)
  6449. return BTRFS_RAID_RAID0;
  6450. else if (flags & BTRFS_BLOCK_GROUP_RAID5)
  6451. return BTRFS_RAID_RAID5;
  6452. else if (flags & BTRFS_BLOCK_GROUP_RAID6)
  6453. return BTRFS_RAID_RAID6;
  6454. return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
  6455. }
  6456. int get_block_group_index(struct btrfs_block_group_cache *cache)
  6457. {
  6458. return __get_raid_index(cache->flags);
  6459. }
  6460. static const char *btrfs_raid_type_names[BTRFS_NR_RAID_TYPES] = {
  6461. [BTRFS_RAID_RAID10] = "raid10",
  6462. [BTRFS_RAID_RAID1] = "raid1",
  6463. [BTRFS_RAID_DUP] = "dup",
  6464. [BTRFS_RAID_RAID0] = "raid0",
  6465. [BTRFS_RAID_SINGLE] = "single",
  6466. [BTRFS_RAID_RAID5] = "raid5",
  6467. [BTRFS_RAID_RAID6] = "raid6",
  6468. };
  6469. static const char *get_raid_name(enum btrfs_raid_types type)
  6470. {
  6471. if (type >= BTRFS_NR_RAID_TYPES)
  6472. return NULL;
  6473. return btrfs_raid_type_names[type];
  6474. }
  6475. enum btrfs_loop_type {
  6476. LOOP_CACHING_NOWAIT = 0,
  6477. LOOP_CACHING_WAIT = 1,
  6478. LOOP_ALLOC_CHUNK = 2,
  6479. LOOP_NO_EMPTY_SIZE = 3,
  6480. };
  6481. static inline void
  6482. btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
  6483. int delalloc)
  6484. {
  6485. if (delalloc)
  6486. down_read(&cache->data_rwsem);
  6487. }
  6488. static inline void
  6489. btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
  6490. int delalloc)
  6491. {
  6492. btrfs_get_block_group(cache);
  6493. if (delalloc)
  6494. down_read(&cache->data_rwsem);
  6495. }
  6496. static struct btrfs_block_group_cache *
  6497. btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
  6498. struct btrfs_free_cluster *cluster,
  6499. int delalloc)
  6500. {
  6501. struct btrfs_block_group_cache *used_bg = NULL;
  6502. spin_lock(&cluster->refill_lock);
  6503. while (1) {
  6504. used_bg = cluster->block_group;
  6505. if (!used_bg)
  6506. return NULL;
  6507. if (used_bg == block_group)
  6508. return used_bg;
  6509. btrfs_get_block_group(used_bg);
  6510. if (!delalloc)
  6511. return used_bg;
  6512. if (down_read_trylock(&used_bg->data_rwsem))
  6513. return used_bg;
  6514. spin_unlock(&cluster->refill_lock);
  6515. /* We should only have one-level nested. */
  6516. down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
  6517. spin_lock(&cluster->refill_lock);
  6518. if (used_bg == cluster->block_group)
  6519. return used_bg;
  6520. up_read(&used_bg->data_rwsem);
  6521. btrfs_put_block_group(used_bg);
  6522. }
  6523. }
  6524. static inline void
  6525. btrfs_release_block_group(struct btrfs_block_group_cache *cache,
  6526. int delalloc)
  6527. {
  6528. if (delalloc)
  6529. up_read(&cache->data_rwsem);
  6530. btrfs_put_block_group(cache);
  6531. }
  6532. /*
  6533. * walks the btree of allocated extents and find a hole of a given size.
  6534. * The key ins is changed to record the hole:
  6535. * ins->objectid == start position
  6536. * ins->flags = BTRFS_EXTENT_ITEM_KEY
  6537. * ins->offset == the size of the hole.
  6538. * Any available blocks before search_start are skipped.
  6539. *
  6540. * If there is no suitable free space, we will record the max size of
  6541. * the free space extent currently.
  6542. */
  6543. static noinline int find_free_extent(struct btrfs_root *orig_root,
  6544. u64 ram_bytes, u64 num_bytes, u64 empty_size,
  6545. u64 hint_byte, struct btrfs_key *ins,
  6546. u64 flags, int delalloc)
  6547. {
  6548. struct btrfs_fs_info *fs_info = orig_root->fs_info;
  6549. int ret = 0;
  6550. struct btrfs_root *root = fs_info->extent_root;
  6551. struct btrfs_free_cluster *last_ptr = NULL;
  6552. struct btrfs_block_group_cache *block_group = NULL;
  6553. u64 search_start = 0;
  6554. u64 max_extent_size = 0;
  6555. u64 empty_cluster = 0;
  6556. struct btrfs_space_info *space_info;
  6557. int loop = 0;
  6558. int index = __get_raid_index(flags);
  6559. bool failed_cluster_refill = false;
  6560. bool failed_alloc = false;
  6561. bool use_cluster = true;
  6562. bool have_caching_bg = false;
  6563. bool orig_have_caching_bg = false;
  6564. bool full_search = false;
  6565. WARN_ON(num_bytes < fs_info->sectorsize);
  6566. ins->type = BTRFS_EXTENT_ITEM_KEY;
  6567. ins->objectid = 0;
  6568. ins->offset = 0;
  6569. trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
  6570. space_info = __find_space_info(fs_info, flags);
  6571. if (!space_info) {
  6572. btrfs_err(fs_info, "No space info for %llu", flags);
  6573. return -ENOSPC;
  6574. }
  6575. /*
  6576. * If our free space is heavily fragmented we may not be able to make
  6577. * big contiguous allocations, so instead of doing the expensive search
  6578. * for free space, simply return ENOSPC with our max_extent_size so we
  6579. * can go ahead and search for a more manageable chunk.
  6580. *
  6581. * If our max_extent_size is large enough for our allocation simply
  6582. * disable clustering since we will likely not be able to find enough
  6583. * space to create a cluster and induce latency trying.
  6584. */
  6585. if (unlikely(space_info->max_extent_size)) {
  6586. spin_lock(&space_info->lock);
  6587. if (space_info->max_extent_size &&
  6588. num_bytes > space_info->max_extent_size) {
  6589. ins->offset = space_info->max_extent_size;
  6590. spin_unlock(&space_info->lock);
  6591. return -ENOSPC;
  6592. } else if (space_info->max_extent_size) {
  6593. use_cluster = false;
  6594. }
  6595. spin_unlock(&space_info->lock);
  6596. }
  6597. last_ptr = fetch_cluster_info(fs_info, space_info, &empty_cluster);
  6598. if (last_ptr) {
  6599. spin_lock(&last_ptr->lock);
  6600. if (last_ptr->block_group)
  6601. hint_byte = last_ptr->window_start;
  6602. if (last_ptr->fragmented) {
  6603. /*
  6604. * We still set window_start so we can keep track of the
  6605. * last place we found an allocation to try and save
  6606. * some time.
  6607. */
  6608. hint_byte = last_ptr->window_start;
  6609. use_cluster = false;
  6610. }
  6611. spin_unlock(&last_ptr->lock);
  6612. }
  6613. search_start = max(search_start, first_logical_byte(fs_info, 0));
  6614. search_start = max(search_start, hint_byte);
  6615. if (search_start == hint_byte) {
  6616. block_group = btrfs_lookup_block_group(fs_info, search_start);
  6617. /*
  6618. * we don't want to use the block group if it doesn't match our
  6619. * allocation bits, or if its not cached.
  6620. *
  6621. * However if we are re-searching with an ideal block group
  6622. * picked out then we don't care that the block group is cached.
  6623. */
  6624. if (block_group && block_group_bits(block_group, flags) &&
  6625. block_group->cached != BTRFS_CACHE_NO) {
  6626. down_read(&space_info->groups_sem);
  6627. if (list_empty(&block_group->list) ||
  6628. block_group->ro) {
  6629. /*
  6630. * someone is removing this block group,
  6631. * we can't jump into the have_block_group
  6632. * target because our list pointers are not
  6633. * valid
  6634. */
  6635. btrfs_put_block_group(block_group);
  6636. up_read(&space_info->groups_sem);
  6637. } else {
  6638. index = get_block_group_index(block_group);
  6639. btrfs_lock_block_group(block_group, delalloc);
  6640. goto have_block_group;
  6641. }
  6642. } else if (block_group) {
  6643. btrfs_put_block_group(block_group);
  6644. }
  6645. }
  6646. search:
  6647. have_caching_bg = false;
  6648. if (index == 0 || index == __get_raid_index(flags))
  6649. full_search = true;
  6650. down_read(&space_info->groups_sem);
  6651. list_for_each_entry(block_group, &space_info->block_groups[index],
  6652. list) {
  6653. u64 offset;
  6654. int cached;
  6655. btrfs_grab_block_group(block_group, delalloc);
  6656. search_start = block_group->key.objectid;
  6657. /*
  6658. * this can happen if we end up cycling through all the
  6659. * raid types, but we want to make sure we only allocate
  6660. * for the proper type.
  6661. */
  6662. if (!block_group_bits(block_group, flags)) {
  6663. u64 extra = BTRFS_BLOCK_GROUP_DUP |
  6664. BTRFS_BLOCK_GROUP_RAID1 |
  6665. BTRFS_BLOCK_GROUP_RAID5 |
  6666. BTRFS_BLOCK_GROUP_RAID6 |
  6667. BTRFS_BLOCK_GROUP_RAID10;
  6668. /*
  6669. * if they asked for extra copies and this block group
  6670. * doesn't provide them, bail. This does allow us to
  6671. * fill raid0 from raid1.
  6672. */
  6673. if ((flags & extra) && !(block_group->flags & extra))
  6674. goto loop;
  6675. }
  6676. have_block_group:
  6677. cached = block_group_cache_done(block_group);
  6678. if (unlikely(!cached)) {
  6679. have_caching_bg = true;
  6680. ret = cache_block_group(block_group, 0);
  6681. BUG_ON(ret < 0);
  6682. ret = 0;
  6683. }
  6684. if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
  6685. goto loop;
  6686. if (unlikely(block_group->ro))
  6687. goto loop;
  6688. /*
  6689. * Ok we want to try and use the cluster allocator, so
  6690. * lets look there
  6691. */
  6692. if (last_ptr && use_cluster) {
  6693. struct btrfs_block_group_cache *used_block_group;
  6694. unsigned long aligned_cluster;
  6695. /*
  6696. * the refill lock keeps out other
  6697. * people trying to start a new cluster
  6698. */
  6699. used_block_group = btrfs_lock_cluster(block_group,
  6700. last_ptr,
  6701. delalloc);
  6702. if (!used_block_group)
  6703. goto refill_cluster;
  6704. if (used_block_group != block_group &&
  6705. (used_block_group->ro ||
  6706. !block_group_bits(used_block_group, flags)))
  6707. goto release_cluster;
  6708. offset = btrfs_alloc_from_cluster(used_block_group,
  6709. last_ptr,
  6710. num_bytes,
  6711. used_block_group->key.objectid,
  6712. &max_extent_size);
  6713. if (offset) {
  6714. /* we have a block, we're done */
  6715. spin_unlock(&last_ptr->refill_lock);
  6716. trace_btrfs_reserve_extent_cluster(fs_info,
  6717. used_block_group,
  6718. search_start, num_bytes);
  6719. if (used_block_group != block_group) {
  6720. btrfs_release_block_group(block_group,
  6721. delalloc);
  6722. block_group = used_block_group;
  6723. }
  6724. goto checks;
  6725. }
  6726. WARN_ON(last_ptr->block_group != used_block_group);
  6727. release_cluster:
  6728. /* If we are on LOOP_NO_EMPTY_SIZE, we can't
  6729. * set up a new clusters, so lets just skip it
  6730. * and let the allocator find whatever block
  6731. * it can find. If we reach this point, we
  6732. * will have tried the cluster allocator
  6733. * plenty of times and not have found
  6734. * anything, so we are likely way too
  6735. * fragmented for the clustering stuff to find
  6736. * anything.
  6737. *
  6738. * However, if the cluster is taken from the
  6739. * current block group, release the cluster
  6740. * first, so that we stand a better chance of
  6741. * succeeding in the unclustered
  6742. * allocation. */
  6743. if (loop >= LOOP_NO_EMPTY_SIZE &&
  6744. used_block_group != block_group) {
  6745. spin_unlock(&last_ptr->refill_lock);
  6746. btrfs_release_block_group(used_block_group,
  6747. delalloc);
  6748. goto unclustered_alloc;
  6749. }
  6750. /*
  6751. * this cluster didn't work out, free it and
  6752. * start over
  6753. */
  6754. btrfs_return_cluster_to_free_space(NULL, last_ptr);
  6755. if (used_block_group != block_group)
  6756. btrfs_release_block_group(used_block_group,
  6757. delalloc);
  6758. refill_cluster:
  6759. if (loop >= LOOP_NO_EMPTY_SIZE) {
  6760. spin_unlock(&last_ptr->refill_lock);
  6761. goto unclustered_alloc;
  6762. }
  6763. aligned_cluster = max_t(unsigned long,
  6764. empty_cluster + empty_size,
  6765. block_group->full_stripe_len);
  6766. /* allocate a cluster in this block group */
  6767. ret = btrfs_find_space_cluster(fs_info, block_group,
  6768. last_ptr, search_start,
  6769. num_bytes,
  6770. aligned_cluster);
  6771. if (ret == 0) {
  6772. /*
  6773. * now pull our allocation out of this
  6774. * cluster
  6775. */
  6776. offset = btrfs_alloc_from_cluster(block_group,
  6777. last_ptr,
  6778. num_bytes,
  6779. search_start,
  6780. &max_extent_size);
  6781. if (offset) {
  6782. /* we found one, proceed */
  6783. spin_unlock(&last_ptr->refill_lock);
  6784. trace_btrfs_reserve_extent_cluster(fs_info,
  6785. block_group, search_start,
  6786. num_bytes);
  6787. goto checks;
  6788. }
  6789. } else if (!cached && loop > LOOP_CACHING_NOWAIT
  6790. && !failed_cluster_refill) {
  6791. spin_unlock(&last_ptr->refill_lock);
  6792. failed_cluster_refill = true;
  6793. wait_block_group_cache_progress(block_group,
  6794. num_bytes + empty_cluster + empty_size);
  6795. goto have_block_group;
  6796. }
  6797. /*
  6798. * at this point we either didn't find a cluster
  6799. * or we weren't able to allocate a block from our
  6800. * cluster. Free the cluster we've been trying
  6801. * to use, and go to the next block group
  6802. */
  6803. btrfs_return_cluster_to_free_space(NULL, last_ptr);
  6804. spin_unlock(&last_ptr->refill_lock);
  6805. goto loop;
  6806. }
  6807. unclustered_alloc:
  6808. /*
  6809. * We are doing an unclustered alloc, set the fragmented flag so
  6810. * we don't bother trying to setup a cluster again until we get
  6811. * more space.
  6812. */
  6813. if (unlikely(last_ptr)) {
  6814. spin_lock(&last_ptr->lock);
  6815. last_ptr->fragmented = 1;
  6816. spin_unlock(&last_ptr->lock);
  6817. }
  6818. spin_lock(&block_group->free_space_ctl->tree_lock);
  6819. if (cached &&
  6820. block_group->free_space_ctl->free_space <
  6821. num_bytes + empty_cluster + empty_size) {
  6822. if (block_group->free_space_ctl->free_space >
  6823. max_extent_size)
  6824. max_extent_size =
  6825. block_group->free_space_ctl->free_space;
  6826. spin_unlock(&block_group->free_space_ctl->tree_lock);
  6827. goto loop;
  6828. }
  6829. spin_unlock(&block_group->free_space_ctl->tree_lock);
  6830. offset = btrfs_find_space_for_alloc(block_group, search_start,
  6831. num_bytes, empty_size,
  6832. &max_extent_size);
  6833. /*
  6834. * If we didn't find a chunk, and we haven't failed on this
  6835. * block group before, and this block group is in the middle of
  6836. * caching and we are ok with waiting, then go ahead and wait
  6837. * for progress to be made, and set failed_alloc to true.
  6838. *
  6839. * If failed_alloc is true then we've already waited on this
  6840. * block group once and should move on to the next block group.
  6841. */
  6842. if (!offset && !failed_alloc && !cached &&
  6843. loop > LOOP_CACHING_NOWAIT) {
  6844. wait_block_group_cache_progress(block_group,
  6845. num_bytes + empty_size);
  6846. failed_alloc = true;
  6847. goto have_block_group;
  6848. } else if (!offset) {
  6849. goto loop;
  6850. }
  6851. checks:
  6852. search_start = ALIGN(offset, fs_info->stripesize);
  6853. /* move on to the next group */
  6854. if (search_start + num_bytes >
  6855. block_group->key.objectid + block_group->key.offset) {
  6856. btrfs_add_free_space(block_group, offset, num_bytes);
  6857. goto loop;
  6858. }
  6859. if (offset < search_start)
  6860. btrfs_add_free_space(block_group, offset,
  6861. search_start - offset);
  6862. BUG_ON(offset > search_start);
  6863. ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
  6864. num_bytes, delalloc);
  6865. if (ret == -EAGAIN) {
  6866. btrfs_add_free_space(block_group, offset, num_bytes);
  6867. goto loop;
  6868. }
  6869. btrfs_inc_block_group_reservations(block_group);
  6870. /* we are all good, lets return */
  6871. ins->objectid = search_start;
  6872. ins->offset = num_bytes;
  6873. trace_btrfs_reserve_extent(fs_info, block_group,
  6874. search_start, num_bytes);
  6875. btrfs_release_block_group(block_group, delalloc);
  6876. break;
  6877. loop:
  6878. failed_cluster_refill = false;
  6879. failed_alloc = false;
  6880. BUG_ON(index != get_block_group_index(block_group));
  6881. btrfs_release_block_group(block_group, delalloc);
  6882. }
  6883. up_read(&space_info->groups_sem);
  6884. if ((loop == LOOP_CACHING_NOWAIT) && have_caching_bg
  6885. && !orig_have_caching_bg)
  6886. orig_have_caching_bg = true;
  6887. if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
  6888. goto search;
  6889. if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
  6890. goto search;
  6891. /*
  6892. * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
  6893. * caching kthreads as we move along
  6894. * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
  6895. * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
  6896. * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
  6897. * again
  6898. */
  6899. if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
  6900. index = 0;
  6901. if (loop == LOOP_CACHING_NOWAIT) {
  6902. /*
  6903. * We want to skip the LOOP_CACHING_WAIT step if we
  6904. * don't have any uncached bgs and we've already done a
  6905. * full search through.
  6906. */
  6907. if (orig_have_caching_bg || !full_search)
  6908. loop = LOOP_CACHING_WAIT;
  6909. else
  6910. loop = LOOP_ALLOC_CHUNK;
  6911. } else {
  6912. loop++;
  6913. }
  6914. if (loop == LOOP_ALLOC_CHUNK) {
  6915. struct btrfs_trans_handle *trans;
  6916. int exist = 0;
  6917. trans = current->journal_info;
  6918. if (trans)
  6919. exist = 1;
  6920. else
  6921. trans = btrfs_join_transaction(root);
  6922. if (IS_ERR(trans)) {
  6923. ret = PTR_ERR(trans);
  6924. goto out;
  6925. }
  6926. ret = do_chunk_alloc(trans, fs_info, flags,
  6927. CHUNK_ALLOC_FORCE);
  6928. /*
  6929. * If we can't allocate a new chunk we've already looped
  6930. * through at least once, move on to the NO_EMPTY_SIZE
  6931. * case.
  6932. */
  6933. if (ret == -ENOSPC)
  6934. loop = LOOP_NO_EMPTY_SIZE;
  6935. /*
  6936. * Do not bail out on ENOSPC since we
  6937. * can do more things.
  6938. */
  6939. if (ret < 0 && ret != -ENOSPC)
  6940. btrfs_abort_transaction(trans, ret);
  6941. else
  6942. ret = 0;
  6943. if (!exist)
  6944. btrfs_end_transaction(trans);
  6945. if (ret)
  6946. goto out;
  6947. }
  6948. if (loop == LOOP_NO_EMPTY_SIZE) {
  6949. /*
  6950. * Don't loop again if we already have no empty_size and
  6951. * no empty_cluster.
  6952. */
  6953. if (empty_size == 0 &&
  6954. empty_cluster == 0) {
  6955. ret = -ENOSPC;
  6956. goto out;
  6957. }
  6958. empty_size = 0;
  6959. empty_cluster = 0;
  6960. }
  6961. goto search;
  6962. } else if (!ins->objectid) {
  6963. ret = -ENOSPC;
  6964. } else if (ins->objectid) {
  6965. if (!use_cluster && last_ptr) {
  6966. spin_lock(&last_ptr->lock);
  6967. last_ptr->window_start = ins->objectid;
  6968. spin_unlock(&last_ptr->lock);
  6969. }
  6970. ret = 0;
  6971. }
  6972. out:
  6973. if (ret == -ENOSPC) {
  6974. spin_lock(&space_info->lock);
  6975. space_info->max_extent_size = max_extent_size;
  6976. spin_unlock(&space_info->lock);
  6977. ins->offset = max_extent_size;
  6978. }
  6979. return ret;
  6980. }
  6981. static void dump_space_info(struct btrfs_fs_info *fs_info,
  6982. struct btrfs_space_info *info, u64 bytes,
  6983. int dump_block_groups)
  6984. {
  6985. struct btrfs_block_group_cache *cache;
  6986. int index = 0;
  6987. spin_lock(&info->lock);
  6988. btrfs_info(fs_info, "space_info %llu has %llu free, is %sfull",
  6989. info->flags,
  6990. info->total_bytes - info->bytes_used - info->bytes_pinned -
  6991. info->bytes_reserved - info->bytes_readonly -
  6992. info->bytes_may_use, (info->full) ? "" : "not ");
  6993. btrfs_info(fs_info,
  6994. "space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu",
  6995. info->total_bytes, info->bytes_used, info->bytes_pinned,
  6996. info->bytes_reserved, info->bytes_may_use,
  6997. info->bytes_readonly);
  6998. spin_unlock(&info->lock);
  6999. if (!dump_block_groups)
  7000. return;
  7001. down_read(&info->groups_sem);
  7002. again:
  7003. list_for_each_entry(cache, &info->block_groups[index], list) {
  7004. spin_lock(&cache->lock);
  7005. btrfs_info(fs_info,
  7006. "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s",
  7007. cache->key.objectid, cache->key.offset,
  7008. btrfs_block_group_used(&cache->item), cache->pinned,
  7009. cache->reserved, cache->ro ? "[readonly]" : "");
  7010. btrfs_dump_free_space(cache, bytes);
  7011. spin_unlock(&cache->lock);
  7012. }
  7013. if (++index < BTRFS_NR_RAID_TYPES)
  7014. goto again;
  7015. up_read(&info->groups_sem);
  7016. }
  7017. int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
  7018. u64 num_bytes, u64 min_alloc_size,
  7019. u64 empty_size, u64 hint_byte,
  7020. struct btrfs_key *ins, int is_data, int delalloc)
  7021. {
  7022. struct btrfs_fs_info *fs_info = root->fs_info;
  7023. bool final_tried = num_bytes == min_alloc_size;
  7024. u64 flags;
  7025. int ret;
  7026. flags = btrfs_get_alloc_profile(root, is_data);
  7027. again:
  7028. WARN_ON(num_bytes < fs_info->sectorsize);
  7029. ret = find_free_extent(root, ram_bytes, num_bytes, empty_size,
  7030. hint_byte, ins, flags, delalloc);
  7031. if (!ret && !is_data) {
  7032. btrfs_dec_block_group_reservations(fs_info, ins->objectid);
  7033. } else if (ret == -ENOSPC) {
  7034. if (!final_tried && ins->offset) {
  7035. num_bytes = min(num_bytes >> 1, ins->offset);
  7036. num_bytes = round_down(num_bytes,
  7037. fs_info->sectorsize);
  7038. num_bytes = max(num_bytes, min_alloc_size);
  7039. ram_bytes = num_bytes;
  7040. if (num_bytes == min_alloc_size)
  7041. final_tried = true;
  7042. goto again;
  7043. } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
  7044. struct btrfs_space_info *sinfo;
  7045. sinfo = __find_space_info(fs_info, flags);
  7046. btrfs_err(fs_info,
  7047. "allocation failed flags %llu, wanted %llu",
  7048. flags, num_bytes);
  7049. if (sinfo)
  7050. dump_space_info(fs_info, sinfo, num_bytes, 1);
  7051. }
  7052. }
  7053. return ret;
  7054. }
  7055. static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
  7056. u64 start, u64 len,
  7057. int pin, int delalloc)
  7058. {
  7059. struct btrfs_block_group_cache *cache;
  7060. int ret = 0;
  7061. cache = btrfs_lookup_block_group(fs_info, start);
  7062. if (!cache) {
  7063. btrfs_err(fs_info, "Unable to find block group for %llu",
  7064. start);
  7065. return -ENOSPC;
  7066. }
  7067. if (pin)
  7068. pin_down_extent(fs_info, cache, start, len, 1);
  7069. else {
  7070. if (btrfs_test_opt(fs_info, DISCARD))
  7071. ret = btrfs_discard_extent(fs_info, start, len, NULL);
  7072. btrfs_add_free_space(cache, start, len);
  7073. btrfs_free_reserved_bytes(cache, len, delalloc);
  7074. trace_btrfs_reserved_extent_free(fs_info, start, len);
  7075. }
  7076. btrfs_put_block_group(cache);
  7077. return ret;
  7078. }
  7079. int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
  7080. u64 start, u64 len, int delalloc)
  7081. {
  7082. return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
  7083. }
  7084. int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
  7085. u64 start, u64 len)
  7086. {
  7087. return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
  7088. }
  7089. static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
  7090. struct btrfs_fs_info *fs_info,
  7091. u64 parent, u64 root_objectid,
  7092. u64 flags, u64 owner, u64 offset,
  7093. struct btrfs_key *ins, int ref_mod)
  7094. {
  7095. int ret;
  7096. struct btrfs_extent_item *extent_item;
  7097. struct btrfs_extent_inline_ref *iref;
  7098. struct btrfs_path *path;
  7099. struct extent_buffer *leaf;
  7100. int type;
  7101. u32 size;
  7102. if (parent > 0)
  7103. type = BTRFS_SHARED_DATA_REF_KEY;
  7104. else
  7105. type = BTRFS_EXTENT_DATA_REF_KEY;
  7106. size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
  7107. path = btrfs_alloc_path();
  7108. if (!path)
  7109. return -ENOMEM;
  7110. path->leave_spinning = 1;
  7111. ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
  7112. ins, size);
  7113. if (ret) {
  7114. btrfs_free_path(path);
  7115. return ret;
  7116. }
  7117. leaf = path->nodes[0];
  7118. extent_item = btrfs_item_ptr(leaf, path->slots[0],
  7119. struct btrfs_extent_item);
  7120. btrfs_set_extent_refs(leaf, extent_item, ref_mod);
  7121. btrfs_set_extent_generation(leaf, extent_item, trans->transid);
  7122. btrfs_set_extent_flags(leaf, extent_item,
  7123. flags | BTRFS_EXTENT_FLAG_DATA);
  7124. iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
  7125. btrfs_set_extent_inline_ref_type(leaf, iref, type);
  7126. if (parent > 0) {
  7127. struct btrfs_shared_data_ref *ref;
  7128. ref = (struct btrfs_shared_data_ref *)(iref + 1);
  7129. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  7130. btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
  7131. } else {
  7132. struct btrfs_extent_data_ref *ref;
  7133. ref = (struct btrfs_extent_data_ref *)(&iref->offset);
  7134. btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
  7135. btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
  7136. btrfs_set_extent_data_ref_offset(leaf, ref, offset);
  7137. btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
  7138. }
  7139. btrfs_mark_buffer_dirty(path->nodes[0]);
  7140. btrfs_free_path(path);
  7141. ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
  7142. ins->offset);
  7143. if (ret)
  7144. return ret;
  7145. ret = update_block_group(trans, fs_info, ins->objectid, ins->offset, 1);
  7146. if (ret) { /* -ENOENT, logic error */
  7147. btrfs_err(fs_info, "update block group failed for %llu %llu",
  7148. ins->objectid, ins->offset);
  7149. BUG();
  7150. }
  7151. trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
  7152. return ret;
  7153. }
  7154. static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
  7155. struct btrfs_fs_info *fs_info,
  7156. u64 parent, u64 root_objectid,
  7157. u64 flags, struct btrfs_disk_key *key,
  7158. int level, struct btrfs_key *ins)
  7159. {
  7160. int ret;
  7161. struct btrfs_extent_item *extent_item;
  7162. struct btrfs_tree_block_info *block_info;
  7163. struct btrfs_extent_inline_ref *iref;
  7164. struct btrfs_path *path;
  7165. struct extent_buffer *leaf;
  7166. u32 size = sizeof(*extent_item) + sizeof(*iref);
  7167. u64 num_bytes = ins->offset;
  7168. bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
  7169. if (!skinny_metadata)
  7170. size += sizeof(*block_info);
  7171. path = btrfs_alloc_path();
  7172. if (!path) {
  7173. btrfs_free_and_pin_reserved_extent(fs_info, ins->objectid,
  7174. fs_info->nodesize);
  7175. return -ENOMEM;
  7176. }
  7177. path->leave_spinning = 1;
  7178. ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
  7179. ins, size);
  7180. if (ret) {
  7181. btrfs_free_path(path);
  7182. btrfs_free_and_pin_reserved_extent(fs_info, ins->objectid,
  7183. fs_info->nodesize);
  7184. return ret;
  7185. }
  7186. leaf = path->nodes[0];
  7187. extent_item = btrfs_item_ptr(leaf, path->slots[0],
  7188. struct btrfs_extent_item);
  7189. btrfs_set_extent_refs(leaf, extent_item, 1);
  7190. btrfs_set_extent_generation(leaf, extent_item, trans->transid);
  7191. btrfs_set_extent_flags(leaf, extent_item,
  7192. flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
  7193. if (skinny_metadata) {
  7194. iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
  7195. num_bytes = fs_info->nodesize;
  7196. } else {
  7197. block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
  7198. btrfs_set_tree_block_key(leaf, block_info, key);
  7199. btrfs_set_tree_block_level(leaf, block_info, level);
  7200. iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
  7201. }
  7202. if (parent > 0) {
  7203. BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
  7204. btrfs_set_extent_inline_ref_type(leaf, iref,
  7205. BTRFS_SHARED_BLOCK_REF_KEY);
  7206. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  7207. } else {
  7208. btrfs_set_extent_inline_ref_type(leaf, iref,
  7209. BTRFS_TREE_BLOCK_REF_KEY);
  7210. btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
  7211. }
  7212. btrfs_mark_buffer_dirty(leaf);
  7213. btrfs_free_path(path);
  7214. ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
  7215. num_bytes);
  7216. if (ret)
  7217. return ret;
  7218. ret = update_block_group(trans, fs_info, ins->objectid,
  7219. fs_info->nodesize, 1);
  7220. if (ret) { /* -ENOENT, logic error */
  7221. btrfs_err(fs_info, "update block group failed for %llu %llu",
  7222. ins->objectid, ins->offset);
  7223. BUG();
  7224. }
  7225. trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid,
  7226. fs_info->nodesize);
  7227. return ret;
  7228. }
  7229. int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
  7230. u64 root_objectid, u64 owner,
  7231. u64 offset, u64 ram_bytes,
  7232. struct btrfs_key *ins)
  7233. {
  7234. struct btrfs_fs_info *fs_info = trans->fs_info;
  7235. int ret;
  7236. BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
  7237. ret = btrfs_add_delayed_data_ref(fs_info, trans, ins->objectid,
  7238. ins->offset, 0,
  7239. root_objectid, owner, offset,
  7240. ram_bytes, BTRFS_ADD_DELAYED_EXTENT);
  7241. return ret;
  7242. }
  7243. /*
  7244. * this is used by the tree logging recovery code. It records that
  7245. * an extent has been allocated and makes sure to clear the free
  7246. * space cache bits as well
  7247. */
  7248. int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
  7249. struct btrfs_fs_info *fs_info,
  7250. u64 root_objectid, u64 owner, u64 offset,
  7251. struct btrfs_key *ins)
  7252. {
  7253. int ret;
  7254. struct btrfs_block_group_cache *block_group;
  7255. struct btrfs_space_info *space_info;
  7256. /*
  7257. * Mixed block groups will exclude before processing the log so we only
  7258. * need to do the exclude dance if this fs isn't mixed.
  7259. */
  7260. if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
  7261. ret = __exclude_logged_extent(fs_info, ins->objectid,
  7262. ins->offset);
  7263. if (ret)
  7264. return ret;
  7265. }
  7266. block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
  7267. if (!block_group)
  7268. return -EINVAL;
  7269. space_info = block_group->space_info;
  7270. spin_lock(&space_info->lock);
  7271. spin_lock(&block_group->lock);
  7272. space_info->bytes_reserved += ins->offset;
  7273. block_group->reserved += ins->offset;
  7274. spin_unlock(&block_group->lock);
  7275. spin_unlock(&space_info->lock);
  7276. ret = alloc_reserved_file_extent(trans, fs_info, 0, root_objectid,
  7277. 0, owner, offset, ins, 1);
  7278. btrfs_put_block_group(block_group);
  7279. return ret;
  7280. }
  7281. static struct extent_buffer *
  7282. btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  7283. u64 bytenr, int level)
  7284. {
  7285. struct btrfs_fs_info *fs_info = root->fs_info;
  7286. struct extent_buffer *buf;
  7287. buf = btrfs_find_create_tree_block(fs_info, bytenr);
  7288. if (IS_ERR(buf))
  7289. return buf;
  7290. btrfs_set_header_generation(buf, trans->transid);
  7291. btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
  7292. btrfs_tree_lock(buf);
  7293. clean_tree_block(trans, fs_info, buf);
  7294. clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
  7295. btrfs_set_lock_blocking(buf);
  7296. set_extent_buffer_uptodate(buf);
  7297. if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
  7298. buf->log_index = root->log_transid % 2;
  7299. /*
  7300. * we allow two log transactions at a time, use different
  7301. * EXENT bit to differentiate dirty pages.
  7302. */
  7303. if (buf->log_index == 0)
  7304. set_extent_dirty(&root->dirty_log_pages, buf->start,
  7305. buf->start + buf->len - 1, GFP_NOFS);
  7306. else
  7307. set_extent_new(&root->dirty_log_pages, buf->start,
  7308. buf->start + buf->len - 1);
  7309. } else {
  7310. buf->log_index = -1;
  7311. set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
  7312. buf->start + buf->len - 1, GFP_NOFS);
  7313. }
  7314. trans->dirty = true;
  7315. /* this returns a buffer locked for blocking */
  7316. return buf;
  7317. }
  7318. static struct btrfs_block_rsv *
  7319. use_block_rsv(struct btrfs_trans_handle *trans,
  7320. struct btrfs_root *root, u32 blocksize)
  7321. {
  7322. struct btrfs_fs_info *fs_info = root->fs_info;
  7323. struct btrfs_block_rsv *block_rsv;
  7324. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  7325. int ret;
  7326. bool global_updated = false;
  7327. block_rsv = get_block_rsv(trans, root);
  7328. if (unlikely(block_rsv->size == 0))
  7329. goto try_reserve;
  7330. again:
  7331. ret = block_rsv_use_bytes(block_rsv, blocksize);
  7332. if (!ret)
  7333. return block_rsv;
  7334. if (block_rsv->failfast)
  7335. return ERR_PTR(ret);
  7336. if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
  7337. global_updated = true;
  7338. update_global_block_rsv(fs_info);
  7339. goto again;
  7340. }
  7341. if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
  7342. static DEFINE_RATELIMIT_STATE(_rs,
  7343. DEFAULT_RATELIMIT_INTERVAL * 10,
  7344. /*DEFAULT_RATELIMIT_BURST*/ 1);
  7345. if (__ratelimit(&_rs))
  7346. WARN(1, KERN_DEBUG
  7347. "BTRFS: block rsv returned %d\n", ret);
  7348. }
  7349. try_reserve:
  7350. ret = reserve_metadata_bytes(root, block_rsv, blocksize,
  7351. BTRFS_RESERVE_NO_FLUSH);
  7352. if (!ret)
  7353. return block_rsv;
  7354. /*
  7355. * If we couldn't reserve metadata bytes try and use some from
  7356. * the global reserve if its space type is the same as the global
  7357. * reservation.
  7358. */
  7359. if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
  7360. block_rsv->space_info == global_rsv->space_info) {
  7361. ret = block_rsv_use_bytes(global_rsv, blocksize);
  7362. if (!ret)
  7363. return global_rsv;
  7364. }
  7365. return ERR_PTR(ret);
  7366. }
  7367. static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
  7368. struct btrfs_block_rsv *block_rsv, u32 blocksize)
  7369. {
  7370. block_rsv_add_bytes(block_rsv, blocksize, 0);
  7371. block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
  7372. }
  7373. /*
  7374. * finds a free extent and does all the dirty work required for allocation
  7375. * returns the tree buffer or an ERR_PTR on error.
  7376. */
  7377. struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
  7378. struct btrfs_root *root,
  7379. u64 parent, u64 root_objectid,
  7380. struct btrfs_disk_key *key, int level,
  7381. u64 hint, u64 empty_size)
  7382. {
  7383. struct btrfs_fs_info *fs_info = root->fs_info;
  7384. struct btrfs_key ins;
  7385. struct btrfs_block_rsv *block_rsv;
  7386. struct extent_buffer *buf;
  7387. struct btrfs_delayed_extent_op *extent_op;
  7388. u64 flags = 0;
  7389. int ret;
  7390. u32 blocksize = fs_info->nodesize;
  7391. bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
  7392. #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
  7393. if (btrfs_is_testing(fs_info)) {
  7394. buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
  7395. level);
  7396. if (!IS_ERR(buf))
  7397. root->alloc_bytenr += blocksize;
  7398. return buf;
  7399. }
  7400. #endif
  7401. block_rsv = use_block_rsv(trans, root, blocksize);
  7402. if (IS_ERR(block_rsv))
  7403. return ERR_CAST(block_rsv);
  7404. ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
  7405. empty_size, hint, &ins, 0, 0);
  7406. if (ret)
  7407. goto out_unuse;
  7408. buf = btrfs_init_new_buffer(trans, root, ins.objectid, level);
  7409. if (IS_ERR(buf)) {
  7410. ret = PTR_ERR(buf);
  7411. goto out_free_reserved;
  7412. }
  7413. if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
  7414. if (parent == 0)
  7415. parent = ins.objectid;
  7416. flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
  7417. } else
  7418. BUG_ON(parent > 0);
  7419. if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
  7420. extent_op = btrfs_alloc_delayed_extent_op();
  7421. if (!extent_op) {
  7422. ret = -ENOMEM;
  7423. goto out_free_buf;
  7424. }
  7425. if (key)
  7426. memcpy(&extent_op->key, key, sizeof(extent_op->key));
  7427. else
  7428. memset(&extent_op->key, 0, sizeof(extent_op->key));
  7429. extent_op->flags_to_set = flags;
  7430. extent_op->update_key = skinny_metadata ? false : true;
  7431. extent_op->update_flags = true;
  7432. extent_op->is_data = false;
  7433. extent_op->level = level;
  7434. ret = btrfs_add_delayed_tree_ref(fs_info, trans,
  7435. ins.objectid, ins.offset,
  7436. parent, root_objectid, level,
  7437. BTRFS_ADD_DELAYED_EXTENT,
  7438. extent_op);
  7439. if (ret)
  7440. goto out_free_delayed;
  7441. }
  7442. return buf;
  7443. out_free_delayed:
  7444. btrfs_free_delayed_extent_op(extent_op);
  7445. out_free_buf:
  7446. free_extent_buffer(buf);
  7447. out_free_reserved:
  7448. btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
  7449. out_unuse:
  7450. unuse_block_rsv(fs_info, block_rsv, blocksize);
  7451. return ERR_PTR(ret);
  7452. }
  7453. struct walk_control {
  7454. u64 refs[BTRFS_MAX_LEVEL];
  7455. u64 flags[BTRFS_MAX_LEVEL];
  7456. struct btrfs_key update_progress;
  7457. int stage;
  7458. int level;
  7459. int shared_level;
  7460. int update_ref;
  7461. int keep_locks;
  7462. int reada_slot;
  7463. int reada_count;
  7464. int for_reloc;
  7465. };
  7466. #define DROP_REFERENCE 1
  7467. #define UPDATE_BACKREF 2
  7468. static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
  7469. struct btrfs_root *root,
  7470. struct walk_control *wc,
  7471. struct btrfs_path *path)
  7472. {
  7473. struct btrfs_fs_info *fs_info = root->fs_info;
  7474. u64 bytenr;
  7475. u64 generation;
  7476. u64 refs;
  7477. u64 flags;
  7478. u32 nritems;
  7479. struct btrfs_key key;
  7480. struct extent_buffer *eb;
  7481. int ret;
  7482. int slot;
  7483. int nread = 0;
  7484. if (path->slots[wc->level] < wc->reada_slot) {
  7485. wc->reada_count = wc->reada_count * 2 / 3;
  7486. wc->reada_count = max(wc->reada_count, 2);
  7487. } else {
  7488. wc->reada_count = wc->reada_count * 3 / 2;
  7489. wc->reada_count = min_t(int, wc->reada_count,
  7490. BTRFS_NODEPTRS_PER_BLOCK(fs_info));
  7491. }
  7492. eb = path->nodes[wc->level];
  7493. nritems = btrfs_header_nritems(eb);
  7494. for (slot = path->slots[wc->level]; slot < nritems; slot++) {
  7495. if (nread >= wc->reada_count)
  7496. break;
  7497. cond_resched();
  7498. bytenr = btrfs_node_blockptr(eb, slot);
  7499. generation = btrfs_node_ptr_generation(eb, slot);
  7500. if (slot == path->slots[wc->level])
  7501. goto reada;
  7502. if (wc->stage == UPDATE_BACKREF &&
  7503. generation <= root->root_key.offset)
  7504. continue;
  7505. /* We don't lock the tree block, it's OK to be racy here */
  7506. ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
  7507. wc->level - 1, 1, &refs,
  7508. &flags);
  7509. /* We don't care about errors in readahead. */
  7510. if (ret < 0)
  7511. continue;
  7512. BUG_ON(refs == 0);
  7513. if (wc->stage == DROP_REFERENCE) {
  7514. if (refs == 1)
  7515. goto reada;
  7516. if (wc->level == 1 &&
  7517. (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7518. continue;
  7519. if (!wc->update_ref ||
  7520. generation <= root->root_key.offset)
  7521. continue;
  7522. btrfs_node_key_to_cpu(eb, &key, slot);
  7523. ret = btrfs_comp_cpu_keys(&key,
  7524. &wc->update_progress);
  7525. if (ret < 0)
  7526. continue;
  7527. } else {
  7528. if (wc->level == 1 &&
  7529. (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7530. continue;
  7531. }
  7532. reada:
  7533. readahead_tree_block(fs_info, bytenr);
  7534. nread++;
  7535. }
  7536. wc->reada_slot = slot;
  7537. }
  7538. /*
  7539. * helper to process tree block while walking down the tree.
  7540. *
  7541. * when wc->stage == UPDATE_BACKREF, this function updates
  7542. * back refs for pointers in the block.
  7543. *
  7544. * NOTE: return value 1 means we should stop walking down.
  7545. */
  7546. static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
  7547. struct btrfs_root *root,
  7548. struct btrfs_path *path,
  7549. struct walk_control *wc, int lookup_info)
  7550. {
  7551. struct btrfs_fs_info *fs_info = root->fs_info;
  7552. int level = wc->level;
  7553. struct extent_buffer *eb = path->nodes[level];
  7554. u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  7555. int ret;
  7556. if (wc->stage == UPDATE_BACKREF &&
  7557. btrfs_header_owner(eb) != root->root_key.objectid)
  7558. return 1;
  7559. /*
  7560. * when reference count of tree block is 1, it won't increase
  7561. * again. once full backref flag is set, we never clear it.
  7562. */
  7563. if (lookup_info &&
  7564. ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
  7565. (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
  7566. BUG_ON(!path->locks[level]);
  7567. ret = btrfs_lookup_extent_info(trans, fs_info,
  7568. eb->start, level, 1,
  7569. &wc->refs[level],
  7570. &wc->flags[level]);
  7571. BUG_ON(ret == -ENOMEM);
  7572. if (ret)
  7573. return ret;
  7574. BUG_ON(wc->refs[level] == 0);
  7575. }
  7576. if (wc->stage == DROP_REFERENCE) {
  7577. if (wc->refs[level] > 1)
  7578. return 1;
  7579. if (path->locks[level] && !wc->keep_locks) {
  7580. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7581. path->locks[level] = 0;
  7582. }
  7583. return 0;
  7584. }
  7585. /* wc->stage == UPDATE_BACKREF */
  7586. if (!(wc->flags[level] & flag)) {
  7587. BUG_ON(!path->locks[level]);
  7588. ret = btrfs_inc_ref(trans, root, eb, 1);
  7589. BUG_ON(ret); /* -ENOMEM */
  7590. ret = btrfs_dec_ref(trans, root, eb, 0);
  7591. BUG_ON(ret); /* -ENOMEM */
  7592. ret = btrfs_set_disk_extent_flags(trans, fs_info, eb->start,
  7593. eb->len, flag,
  7594. btrfs_header_level(eb), 0);
  7595. BUG_ON(ret); /* -ENOMEM */
  7596. wc->flags[level] |= flag;
  7597. }
  7598. /*
  7599. * the block is shared by multiple trees, so it's not good to
  7600. * keep the tree lock
  7601. */
  7602. if (path->locks[level] && level > 0) {
  7603. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7604. path->locks[level] = 0;
  7605. }
  7606. return 0;
  7607. }
  7608. /*
  7609. * helper to process tree block pointer.
  7610. *
  7611. * when wc->stage == DROP_REFERENCE, this function checks
  7612. * reference count of the block pointed to. if the block
  7613. * is shared and we need update back refs for the subtree
  7614. * rooted at the block, this function changes wc->stage to
  7615. * UPDATE_BACKREF. if the block is shared and there is no
  7616. * need to update back, this function drops the reference
  7617. * to the block.
  7618. *
  7619. * NOTE: return value 1 means we should stop walking down.
  7620. */
  7621. static noinline int do_walk_down(struct btrfs_trans_handle *trans,
  7622. struct btrfs_root *root,
  7623. struct btrfs_path *path,
  7624. struct walk_control *wc, int *lookup_info)
  7625. {
  7626. struct btrfs_fs_info *fs_info = root->fs_info;
  7627. u64 bytenr;
  7628. u64 generation;
  7629. u64 parent;
  7630. u32 blocksize;
  7631. struct btrfs_key key;
  7632. struct extent_buffer *next;
  7633. int level = wc->level;
  7634. int reada = 0;
  7635. int ret = 0;
  7636. bool need_account = false;
  7637. generation = btrfs_node_ptr_generation(path->nodes[level],
  7638. path->slots[level]);
  7639. /*
  7640. * if the lower level block was created before the snapshot
  7641. * was created, we know there is no need to update back refs
  7642. * for the subtree
  7643. */
  7644. if (wc->stage == UPDATE_BACKREF &&
  7645. generation <= root->root_key.offset) {
  7646. *lookup_info = 1;
  7647. return 1;
  7648. }
  7649. bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
  7650. blocksize = fs_info->nodesize;
  7651. next = find_extent_buffer(fs_info, bytenr);
  7652. if (!next) {
  7653. next = btrfs_find_create_tree_block(fs_info, bytenr);
  7654. if (IS_ERR(next))
  7655. return PTR_ERR(next);
  7656. btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
  7657. level - 1);
  7658. reada = 1;
  7659. }
  7660. btrfs_tree_lock(next);
  7661. btrfs_set_lock_blocking(next);
  7662. ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
  7663. &wc->refs[level - 1],
  7664. &wc->flags[level - 1]);
  7665. if (ret < 0)
  7666. goto out_unlock;
  7667. if (unlikely(wc->refs[level - 1] == 0)) {
  7668. btrfs_err(fs_info, "Missing references.");
  7669. ret = -EIO;
  7670. goto out_unlock;
  7671. }
  7672. *lookup_info = 0;
  7673. if (wc->stage == DROP_REFERENCE) {
  7674. if (wc->refs[level - 1] > 1) {
  7675. need_account = true;
  7676. if (level == 1 &&
  7677. (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7678. goto skip;
  7679. if (!wc->update_ref ||
  7680. generation <= root->root_key.offset)
  7681. goto skip;
  7682. btrfs_node_key_to_cpu(path->nodes[level], &key,
  7683. path->slots[level]);
  7684. ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
  7685. if (ret < 0)
  7686. goto skip;
  7687. wc->stage = UPDATE_BACKREF;
  7688. wc->shared_level = level - 1;
  7689. }
  7690. } else {
  7691. if (level == 1 &&
  7692. (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7693. goto skip;
  7694. }
  7695. if (!btrfs_buffer_uptodate(next, generation, 0)) {
  7696. btrfs_tree_unlock(next);
  7697. free_extent_buffer(next);
  7698. next = NULL;
  7699. *lookup_info = 1;
  7700. }
  7701. if (!next) {
  7702. if (reada && level == 1)
  7703. reada_walk_down(trans, root, wc, path);
  7704. next = read_tree_block(fs_info, bytenr, generation);
  7705. if (IS_ERR(next)) {
  7706. return PTR_ERR(next);
  7707. } else if (!extent_buffer_uptodate(next)) {
  7708. free_extent_buffer(next);
  7709. return -EIO;
  7710. }
  7711. btrfs_tree_lock(next);
  7712. btrfs_set_lock_blocking(next);
  7713. }
  7714. level--;
  7715. ASSERT(level == btrfs_header_level(next));
  7716. if (level != btrfs_header_level(next)) {
  7717. btrfs_err(root->fs_info, "mismatched level");
  7718. ret = -EIO;
  7719. goto out_unlock;
  7720. }
  7721. path->nodes[level] = next;
  7722. path->slots[level] = 0;
  7723. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7724. wc->level = level;
  7725. if (wc->level == 1)
  7726. wc->reada_slot = 0;
  7727. return 0;
  7728. skip:
  7729. wc->refs[level - 1] = 0;
  7730. wc->flags[level - 1] = 0;
  7731. if (wc->stage == DROP_REFERENCE) {
  7732. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
  7733. parent = path->nodes[level]->start;
  7734. } else {
  7735. ASSERT(root->root_key.objectid ==
  7736. btrfs_header_owner(path->nodes[level]));
  7737. if (root->root_key.objectid !=
  7738. btrfs_header_owner(path->nodes[level])) {
  7739. btrfs_err(root->fs_info,
  7740. "mismatched block owner");
  7741. ret = -EIO;
  7742. goto out_unlock;
  7743. }
  7744. parent = 0;
  7745. }
  7746. if (need_account) {
  7747. ret = btrfs_qgroup_trace_subtree(trans, root, next,
  7748. generation, level - 1);
  7749. if (ret) {
  7750. btrfs_err_rl(fs_info,
  7751. "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
  7752. ret);
  7753. }
  7754. }
  7755. ret = btrfs_free_extent(trans, fs_info, bytenr, blocksize,
  7756. parent, root->root_key.objectid,
  7757. level - 1, 0);
  7758. if (ret)
  7759. goto out_unlock;
  7760. }
  7761. *lookup_info = 1;
  7762. ret = 1;
  7763. out_unlock:
  7764. btrfs_tree_unlock(next);
  7765. free_extent_buffer(next);
  7766. return ret;
  7767. }
  7768. /*
  7769. * helper to process tree block while walking up the tree.
  7770. *
  7771. * when wc->stage == DROP_REFERENCE, this function drops
  7772. * reference count on the block.
  7773. *
  7774. * when wc->stage == UPDATE_BACKREF, this function changes
  7775. * wc->stage back to DROP_REFERENCE if we changed wc->stage
  7776. * to UPDATE_BACKREF previously while processing the block.
  7777. *
  7778. * NOTE: return value 1 means we should stop walking up.
  7779. */
  7780. static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
  7781. struct btrfs_root *root,
  7782. struct btrfs_path *path,
  7783. struct walk_control *wc)
  7784. {
  7785. struct btrfs_fs_info *fs_info = root->fs_info;
  7786. int ret;
  7787. int level = wc->level;
  7788. struct extent_buffer *eb = path->nodes[level];
  7789. u64 parent = 0;
  7790. if (wc->stage == UPDATE_BACKREF) {
  7791. BUG_ON(wc->shared_level < level);
  7792. if (level < wc->shared_level)
  7793. goto out;
  7794. ret = find_next_key(path, level + 1, &wc->update_progress);
  7795. if (ret > 0)
  7796. wc->update_ref = 0;
  7797. wc->stage = DROP_REFERENCE;
  7798. wc->shared_level = -1;
  7799. path->slots[level] = 0;
  7800. /*
  7801. * check reference count again if the block isn't locked.
  7802. * we should start walking down the tree again if reference
  7803. * count is one.
  7804. */
  7805. if (!path->locks[level]) {
  7806. BUG_ON(level == 0);
  7807. btrfs_tree_lock(eb);
  7808. btrfs_set_lock_blocking(eb);
  7809. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7810. ret = btrfs_lookup_extent_info(trans, fs_info,
  7811. eb->start, level, 1,
  7812. &wc->refs[level],
  7813. &wc->flags[level]);
  7814. if (ret < 0) {
  7815. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7816. path->locks[level] = 0;
  7817. return ret;
  7818. }
  7819. BUG_ON(wc->refs[level] == 0);
  7820. if (wc->refs[level] == 1) {
  7821. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7822. path->locks[level] = 0;
  7823. return 1;
  7824. }
  7825. }
  7826. }
  7827. /* wc->stage == DROP_REFERENCE */
  7828. BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
  7829. if (wc->refs[level] == 1) {
  7830. if (level == 0) {
  7831. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  7832. ret = btrfs_dec_ref(trans, root, eb, 1);
  7833. else
  7834. ret = btrfs_dec_ref(trans, root, eb, 0);
  7835. BUG_ON(ret); /* -ENOMEM */
  7836. ret = btrfs_qgroup_trace_leaf_items(trans, fs_info, eb);
  7837. if (ret) {
  7838. btrfs_err_rl(fs_info,
  7839. "error %d accounting leaf items. Quota is out of sync, rescan required.",
  7840. ret);
  7841. }
  7842. }
  7843. /* make block locked assertion in clean_tree_block happy */
  7844. if (!path->locks[level] &&
  7845. btrfs_header_generation(eb) == trans->transid) {
  7846. btrfs_tree_lock(eb);
  7847. btrfs_set_lock_blocking(eb);
  7848. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7849. }
  7850. clean_tree_block(trans, fs_info, eb);
  7851. }
  7852. if (eb == root->node) {
  7853. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  7854. parent = eb->start;
  7855. else
  7856. BUG_ON(root->root_key.objectid !=
  7857. btrfs_header_owner(eb));
  7858. } else {
  7859. if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  7860. parent = path->nodes[level + 1]->start;
  7861. else
  7862. BUG_ON(root->root_key.objectid !=
  7863. btrfs_header_owner(path->nodes[level + 1]));
  7864. }
  7865. btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
  7866. out:
  7867. wc->refs[level] = 0;
  7868. wc->flags[level] = 0;
  7869. return 0;
  7870. }
  7871. static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
  7872. struct btrfs_root *root,
  7873. struct btrfs_path *path,
  7874. struct walk_control *wc)
  7875. {
  7876. int level = wc->level;
  7877. int lookup_info = 1;
  7878. int ret;
  7879. while (level >= 0) {
  7880. ret = walk_down_proc(trans, root, path, wc, lookup_info);
  7881. if (ret > 0)
  7882. break;
  7883. if (level == 0)
  7884. break;
  7885. if (path->slots[level] >=
  7886. btrfs_header_nritems(path->nodes[level]))
  7887. break;
  7888. ret = do_walk_down(trans, root, path, wc, &lookup_info);
  7889. if (ret > 0) {
  7890. path->slots[level]++;
  7891. continue;
  7892. } else if (ret < 0)
  7893. return ret;
  7894. level = wc->level;
  7895. }
  7896. return 0;
  7897. }
  7898. static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
  7899. struct btrfs_root *root,
  7900. struct btrfs_path *path,
  7901. struct walk_control *wc, int max_level)
  7902. {
  7903. int level = wc->level;
  7904. int ret;
  7905. path->slots[level] = btrfs_header_nritems(path->nodes[level]);
  7906. while (level < max_level && path->nodes[level]) {
  7907. wc->level = level;
  7908. if (path->slots[level] + 1 <
  7909. btrfs_header_nritems(path->nodes[level])) {
  7910. path->slots[level]++;
  7911. return 0;
  7912. } else {
  7913. ret = walk_up_proc(trans, root, path, wc);
  7914. if (ret > 0)
  7915. return 0;
  7916. if (path->locks[level]) {
  7917. btrfs_tree_unlock_rw(path->nodes[level],
  7918. path->locks[level]);
  7919. path->locks[level] = 0;
  7920. }
  7921. free_extent_buffer(path->nodes[level]);
  7922. path->nodes[level] = NULL;
  7923. level++;
  7924. }
  7925. }
  7926. return 1;
  7927. }
  7928. /*
  7929. * drop a subvolume tree.
  7930. *
  7931. * this function traverses the tree freeing any blocks that only
  7932. * referenced by the tree.
  7933. *
  7934. * when a shared tree block is found. this function decreases its
  7935. * reference count by one. if update_ref is true, this function
  7936. * also make sure backrefs for the shared block and all lower level
  7937. * blocks are properly updated.
  7938. *
  7939. * If called with for_reloc == 0, may exit early with -EAGAIN
  7940. */
  7941. int btrfs_drop_snapshot(struct btrfs_root *root,
  7942. struct btrfs_block_rsv *block_rsv, int update_ref,
  7943. int for_reloc)
  7944. {
  7945. struct btrfs_fs_info *fs_info = root->fs_info;
  7946. struct btrfs_path *path;
  7947. struct btrfs_trans_handle *trans;
  7948. struct btrfs_root *tree_root = fs_info->tree_root;
  7949. struct btrfs_root_item *root_item = &root->root_item;
  7950. struct walk_control *wc;
  7951. struct btrfs_key key;
  7952. int err = 0;
  7953. int ret;
  7954. int level;
  7955. bool root_dropped = false;
  7956. btrfs_debug(fs_info, "Drop subvolume %llu", root->objectid);
  7957. path = btrfs_alloc_path();
  7958. if (!path) {
  7959. err = -ENOMEM;
  7960. goto out;
  7961. }
  7962. wc = kzalloc(sizeof(*wc), GFP_NOFS);
  7963. if (!wc) {
  7964. btrfs_free_path(path);
  7965. err = -ENOMEM;
  7966. goto out;
  7967. }
  7968. trans = btrfs_start_transaction(tree_root, 0);
  7969. if (IS_ERR(trans)) {
  7970. err = PTR_ERR(trans);
  7971. goto out_free;
  7972. }
  7973. if (block_rsv)
  7974. trans->block_rsv = block_rsv;
  7975. if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
  7976. level = btrfs_header_level(root->node);
  7977. path->nodes[level] = btrfs_lock_root_node(root);
  7978. btrfs_set_lock_blocking(path->nodes[level]);
  7979. path->slots[level] = 0;
  7980. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7981. memset(&wc->update_progress, 0,
  7982. sizeof(wc->update_progress));
  7983. } else {
  7984. btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
  7985. memcpy(&wc->update_progress, &key,
  7986. sizeof(wc->update_progress));
  7987. level = root_item->drop_level;
  7988. BUG_ON(level == 0);
  7989. path->lowest_level = level;
  7990. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  7991. path->lowest_level = 0;
  7992. if (ret < 0) {
  7993. err = ret;
  7994. goto out_end_trans;
  7995. }
  7996. WARN_ON(ret > 0);
  7997. /*
  7998. * unlock our path, this is safe because only this
  7999. * function is allowed to delete this snapshot
  8000. */
  8001. btrfs_unlock_up_safe(path, 0);
  8002. level = btrfs_header_level(root->node);
  8003. while (1) {
  8004. btrfs_tree_lock(path->nodes[level]);
  8005. btrfs_set_lock_blocking(path->nodes[level]);
  8006. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  8007. ret = btrfs_lookup_extent_info(trans, fs_info,
  8008. path->nodes[level]->start,
  8009. level, 1, &wc->refs[level],
  8010. &wc->flags[level]);
  8011. if (ret < 0) {
  8012. err = ret;
  8013. goto out_end_trans;
  8014. }
  8015. BUG_ON(wc->refs[level] == 0);
  8016. if (level == root_item->drop_level)
  8017. break;
  8018. btrfs_tree_unlock(path->nodes[level]);
  8019. path->locks[level] = 0;
  8020. WARN_ON(wc->refs[level] != 1);
  8021. level--;
  8022. }
  8023. }
  8024. wc->level = level;
  8025. wc->shared_level = -1;
  8026. wc->stage = DROP_REFERENCE;
  8027. wc->update_ref = update_ref;
  8028. wc->keep_locks = 0;
  8029. wc->for_reloc = for_reloc;
  8030. wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
  8031. while (1) {
  8032. ret = walk_down_tree(trans, root, path, wc);
  8033. if (ret < 0) {
  8034. err = ret;
  8035. break;
  8036. }
  8037. ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
  8038. if (ret < 0) {
  8039. err = ret;
  8040. break;
  8041. }
  8042. if (ret > 0) {
  8043. BUG_ON(wc->stage != DROP_REFERENCE);
  8044. break;
  8045. }
  8046. if (wc->stage == DROP_REFERENCE) {
  8047. level = wc->level;
  8048. btrfs_node_key(path->nodes[level],
  8049. &root_item->drop_progress,
  8050. path->slots[level]);
  8051. root_item->drop_level = level;
  8052. }
  8053. BUG_ON(wc->level == 0);
  8054. if (btrfs_should_end_transaction(trans) ||
  8055. (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
  8056. ret = btrfs_update_root(trans, tree_root,
  8057. &root->root_key,
  8058. root_item);
  8059. if (ret) {
  8060. btrfs_abort_transaction(trans, ret);
  8061. err = ret;
  8062. goto out_end_trans;
  8063. }
  8064. btrfs_end_transaction_throttle(trans);
  8065. if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
  8066. btrfs_debug(fs_info,
  8067. "drop snapshot early exit");
  8068. err = -EAGAIN;
  8069. goto out_free;
  8070. }
  8071. trans = btrfs_start_transaction(tree_root, 0);
  8072. if (IS_ERR(trans)) {
  8073. err = PTR_ERR(trans);
  8074. goto out_free;
  8075. }
  8076. if (block_rsv)
  8077. trans->block_rsv = block_rsv;
  8078. }
  8079. }
  8080. btrfs_release_path(path);
  8081. if (err)
  8082. goto out_end_trans;
  8083. ret = btrfs_del_root(trans, tree_root, &root->root_key);
  8084. if (ret) {
  8085. btrfs_abort_transaction(trans, ret);
  8086. goto out_end_trans;
  8087. }
  8088. if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
  8089. ret = btrfs_find_root(tree_root, &root->root_key, path,
  8090. NULL, NULL);
  8091. if (ret < 0) {
  8092. btrfs_abort_transaction(trans, ret);
  8093. err = ret;
  8094. goto out_end_trans;
  8095. } else if (ret > 0) {
  8096. /* if we fail to delete the orphan item this time
  8097. * around, it'll get picked up the next time.
  8098. *
  8099. * The most common failure here is just -ENOENT.
  8100. */
  8101. btrfs_del_orphan_item(trans, tree_root,
  8102. root->root_key.objectid);
  8103. }
  8104. }
  8105. if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
  8106. btrfs_add_dropped_root(trans, root);
  8107. } else {
  8108. free_extent_buffer(root->node);
  8109. free_extent_buffer(root->commit_root);
  8110. btrfs_put_fs_root(root);
  8111. }
  8112. root_dropped = true;
  8113. out_end_trans:
  8114. btrfs_end_transaction_throttle(trans);
  8115. out_free:
  8116. kfree(wc);
  8117. btrfs_free_path(path);
  8118. out:
  8119. /*
  8120. * So if we need to stop dropping the snapshot for whatever reason we
  8121. * need to make sure to add it back to the dead root list so that we
  8122. * keep trying to do the work later. This also cleans up roots if we
  8123. * don't have it in the radix (like when we recover after a power fail
  8124. * or unmount) so we don't leak memory.
  8125. */
  8126. if (!for_reloc && root_dropped == false)
  8127. btrfs_add_dead_root(root);
  8128. if (err && err != -EAGAIN)
  8129. btrfs_handle_fs_error(fs_info, err, NULL);
  8130. return err;
  8131. }
  8132. /*
  8133. * drop subtree rooted at tree block 'node'.
  8134. *
  8135. * NOTE: this function will unlock and release tree block 'node'
  8136. * only used by relocation code
  8137. */
  8138. int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
  8139. struct btrfs_root *root,
  8140. struct extent_buffer *node,
  8141. struct extent_buffer *parent)
  8142. {
  8143. struct btrfs_fs_info *fs_info = root->fs_info;
  8144. struct btrfs_path *path;
  8145. struct walk_control *wc;
  8146. int level;
  8147. int parent_level;
  8148. int ret = 0;
  8149. int wret;
  8150. BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
  8151. path = btrfs_alloc_path();
  8152. if (!path)
  8153. return -ENOMEM;
  8154. wc = kzalloc(sizeof(*wc), GFP_NOFS);
  8155. if (!wc) {
  8156. btrfs_free_path(path);
  8157. return -ENOMEM;
  8158. }
  8159. btrfs_assert_tree_locked(parent);
  8160. parent_level = btrfs_header_level(parent);
  8161. extent_buffer_get(parent);
  8162. path->nodes[parent_level] = parent;
  8163. path->slots[parent_level] = btrfs_header_nritems(parent);
  8164. btrfs_assert_tree_locked(node);
  8165. level = btrfs_header_level(node);
  8166. path->nodes[level] = node;
  8167. path->slots[level] = 0;
  8168. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  8169. wc->refs[parent_level] = 1;
  8170. wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  8171. wc->level = level;
  8172. wc->shared_level = -1;
  8173. wc->stage = DROP_REFERENCE;
  8174. wc->update_ref = 0;
  8175. wc->keep_locks = 1;
  8176. wc->for_reloc = 1;
  8177. wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
  8178. while (1) {
  8179. wret = walk_down_tree(trans, root, path, wc);
  8180. if (wret < 0) {
  8181. ret = wret;
  8182. break;
  8183. }
  8184. wret = walk_up_tree(trans, root, path, wc, parent_level);
  8185. if (wret < 0)
  8186. ret = wret;
  8187. if (wret != 0)
  8188. break;
  8189. }
  8190. kfree(wc);
  8191. btrfs_free_path(path);
  8192. return ret;
  8193. }
  8194. static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
  8195. {
  8196. u64 num_devices;
  8197. u64 stripped;
  8198. /*
  8199. * if restripe for this chunk_type is on pick target profile and
  8200. * return, otherwise do the usual balance
  8201. */
  8202. stripped = get_restripe_target(fs_info, flags);
  8203. if (stripped)
  8204. return extended_to_chunk(stripped);
  8205. num_devices = fs_info->fs_devices->rw_devices;
  8206. stripped = BTRFS_BLOCK_GROUP_RAID0 |
  8207. BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
  8208. BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
  8209. if (num_devices == 1) {
  8210. stripped |= BTRFS_BLOCK_GROUP_DUP;
  8211. stripped = flags & ~stripped;
  8212. /* turn raid0 into single device chunks */
  8213. if (flags & BTRFS_BLOCK_GROUP_RAID0)
  8214. return stripped;
  8215. /* turn mirroring into duplication */
  8216. if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
  8217. BTRFS_BLOCK_GROUP_RAID10))
  8218. return stripped | BTRFS_BLOCK_GROUP_DUP;
  8219. } else {
  8220. /* they already had raid on here, just return */
  8221. if (flags & stripped)
  8222. return flags;
  8223. stripped |= BTRFS_BLOCK_GROUP_DUP;
  8224. stripped = flags & ~stripped;
  8225. /* switch duplicated blocks with raid1 */
  8226. if (flags & BTRFS_BLOCK_GROUP_DUP)
  8227. return stripped | BTRFS_BLOCK_GROUP_RAID1;
  8228. /* this is drive concat, leave it alone */
  8229. }
  8230. return flags;
  8231. }
  8232. static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
  8233. {
  8234. struct btrfs_space_info *sinfo = cache->space_info;
  8235. u64 num_bytes;
  8236. u64 min_allocable_bytes;
  8237. int ret = -ENOSPC;
  8238. /*
  8239. * We need some metadata space and system metadata space for
  8240. * allocating chunks in some corner cases until we force to set
  8241. * it to be readonly.
  8242. */
  8243. if ((sinfo->flags &
  8244. (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
  8245. !force)
  8246. min_allocable_bytes = SZ_1M;
  8247. else
  8248. min_allocable_bytes = 0;
  8249. spin_lock(&sinfo->lock);
  8250. spin_lock(&cache->lock);
  8251. if (cache->ro) {
  8252. cache->ro++;
  8253. ret = 0;
  8254. goto out;
  8255. }
  8256. num_bytes = cache->key.offset - cache->reserved - cache->pinned -
  8257. cache->bytes_super - btrfs_block_group_used(&cache->item);
  8258. if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
  8259. sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
  8260. min_allocable_bytes <= sinfo->total_bytes) {
  8261. sinfo->bytes_readonly += num_bytes;
  8262. cache->ro++;
  8263. list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
  8264. ret = 0;
  8265. }
  8266. out:
  8267. spin_unlock(&cache->lock);
  8268. spin_unlock(&sinfo->lock);
  8269. return ret;
  8270. }
  8271. int btrfs_inc_block_group_ro(struct btrfs_root *root,
  8272. struct btrfs_block_group_cache *cache)
  8273. {
  8274. struct btrfs_fs_info *fs_info = root->fs_info;
  8275. struct btrfs_trans_handle *trans;
  8276. u64 alloc_flags;
  8277. int ret;
  8278. again:
  8279. trans = btrfs_join_transaction(root);
  8280. if (IS_ERR(trans))
  8281. return PTR_ERR(trans);
  8282. /*
  8283. * we're not allowed to set block groups readonly after the dirty
  8284. * block groups cache has started writing. If it already started,
  8285. * back off and let this transaction commit
  8286. */
  8287. mutex_lock(&fs_info->ro_block_group_mutex);
  8288. if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
  8289. u64 transid = trans->transid;
  8290. mutex_unlock(&fs_info->ro_block_group_mutex);
  8291. btrfs_end_transaction(trans);
  8292. ret = btrfs_wait_for_commit(fs_info, transid);
  8293. if (ret)
  8294. return ret;
  8295. goto again;
  8296. }
  8297. /*
  8298. * if we are changing raid levels, try to allocate a corresponding
  8299. * block group with the new raid level.
  8300. */
  8301. alloc_flags = update_block_group_flags(fs_info, cache->flags);
  8302. if (alloc_flags != cache->flags) {
  8303. ret = do_chunk_alloc(trans, fs_info, alloc_flags,
  8304. CHUNK_ALLOC_FORCE);
  8305. /*
  8306. * ENOSPC is allowed here, we may have enough space
  8307. * already allocated at the new raid level to
  8308. * carry on
  8309. */
  8310. if (ret == -ENOSPC)
  8311. ret = 0;
  8312. if (ret < 0)
  8313. goto out;
  8314. }
  8315. ret = inc_block_group_ro(cache, 0);
  8316. if (!ret)
  8317. goto out;
  8318. alloc_flags = get_alloc_profile(fs_info, cache->space_info->flags);
  8319. ret = do_chunk_alloc(trans, fs_info, alloc_flags,
  8320. CHUNK_ALLOC_FORCE);
  8321. if (ret < 0)
  8322. goto out;
  8323. ret = inc_block_group_ro(cache, 0);
  8324. out:
  8325. if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
  8326. alloc_flags = update_block_group_flags(fs_info, cache->flags);
  8327. mutex_lock(&fs_info->chunk_mutex);
  8328. check_system_chunk(trans, fs_info, alloc_flags);
  8329. mutex_unlock(&fs_info->chunk_mutex);
  8330. }
  8331. mutex_unlock(&fs_info->ro_block_group_mutex);
  8332. btrfs_end_transaction(trans);
  8333. return ret;
  8334. }
  8335. int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
  8336. struct btrfs_fs_info *fs_info, u64 type)
  8337. {
  8338. u64 alloc_flags = get_alloc_profile(fs_info, type);
  8339. return do_chunk_alloc(trans, fs_info, alloc_flags, CHUNK_ALLOC_FORCE);
  8340. }
  8341. /*
  8342. * helper to account the unused space of all the readonly block group in the
  8343. * space_info. takes mirrors into account.
  8344. */
  8345. u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
  8346. {
  8347. struct btrfs_block_group_cache *block_group;
  8348. u64 free_bytes = 0;
  8349. int factor;
  8350. /* It's df, we don't care if it's racy */
  8351. if (list_empty(&sinfo->ro_bgs))
  8352. return 0;
  8353. spin_lock(&sinfo->lock);
  8354. list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
  8355. spin_lock(&block_group->lock);
  8356. if (!block_group->ro) {
  8357. spin_unlock(&block_group->lock);
  8358. continue;
  8359. }
  8360. if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
  8361. BTRFS_BLOCK_GROUP_RAID10 |
  8362. BTRFS_BLOCK_GROUP_DUP))
  8363. factor = 2;
  8364. else
  8365. factor = 1;
  8366. free_bytes += (block_group->key.offset -
  8367. btrfs_block_group_used(&block_group->item)) *
  8368. factor;
  8369. spin_unlock(&block_group->lock);
  8370. }
  8371. spin_unlock(&sinfo->lock);
  8372. return free_bytes;
  8373. }
  8374. void btrfs_dec_block_group_ro(struct btrfs_block_group_cache *cache)
  8375. {
  8376. struct btrfs_space_info *sinfo = cache->space_info;
  8377. u64 num_bytes;
  8378. BUG_ON(!cache->ro);
  8379. spin_lock(&sinfo->lock);
  8380. spin_lock(&cache->lock);
  8381. if (!--cache->ro) {
  8382. num_bytes = cache->key.offset - cache->reserved -
  8383. cache->pinned - cache->bytes_super -
  8384. btrfs_block_group_used(&cache->item);
  8385. sinfo->bytes_readonly -= num_bytes;
  8386. list_del_init(&cache->ro_list);
  8387. }
  8388. spin_unlock(&cache->lock);
  8389. spin_unlock(&sinfo->lock);
  8390. }
  8391. /*
  8392. * checks to see if its even possible to relocate this block group.
  8393. *
  8394. * @return - -1 if it's not a good idea to relocate this block group, 0 if its
  8395. * ok to go ahead and try.
  8396. */
  8397. int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
  8398. {
  8399. struct btrfs_root *root = fs_info->extent_root;
  8400. struct btrfs_block_group_cache *block_group;
  8401. struct btrfs_space_info *space_info;
  8402. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  8403. struct btrfs_device *device;
  8404. struct btrfs_trans_handle *trans;
  8405. u64 min_free;
  8406. u64 dev_min = 1;
  8407. u64 dev_nr = 0;
  8408. u64 target;
  8409. int debug;
  8410. int index;
  8411. int full = 0;
  8412. int ret = 0;
  8413. debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
  8414. block_group = btrfs_lookup_block_group(fs_info, bytenr);
  8415. /* odd, couldn't find the block group, leave it alone */
  8416. if (!block_group) {
  8417. if (debug)
  8418. btrfs_warn(fs_info,
  8419. "can't find block group for bytenr %llu",
  8420. bytenr);
  8421. return -1;
  8422. }
  8423. min_free = btrfs_block_group_used(&block_group->item);
  8424. /* no bytes used, we're good */
  8425. if (!min_free)
  8426. goto out;
  8427. space_info = block_group->space_info;
  8428. spin_lock(&space_info->lock);
  8429. full = space_info->full;
  8430. /*
  8431. * if this is the last block group we have in this space, we can't
  8432. * relocate it unless we're able to allocate a new chunk below.
  8433. *
  8434. * Otherwise, we need to make sure we have room in the space to handle
  8435. * all of the extents from this block group. If we can, we're good
  8436. */
  8437. if ((space_info->total_bytes != block_group->key.offset) &&
  8438. (space_info->bytes_used + space_info->bytes_reserved +
  8439. space_info->bytes_pinned + space_info->bytes_readonly +
  8440. min_free < 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. }