extent-tree.c 309 KB

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