extent-tree.c 278 KB

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