extent-tree.c 279 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_path *path,
  1178. struct btrfs_extent_inline_ref *iref)
  1179. {
  1180. struct btrfs_key key;
  1181. struct extent_buffer *leaf;
  1182. struct btrfs_extent_data_ref *ref1;
  1183. struct btrfs_shared_data_ref *ref2;
  1184. u32 num_refs = 0;
  1185. leaf = path->nodes[0];
  1186. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1187. if (iref) {
  1188. if (btrfs_extent_inline_ref_type(leaf, iref) ==
  1189. BTRFS_EXTENT_DATA_REF_KEY) {
  1190. ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
  1191. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  1192. } else {
  1193. ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
  1194. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  1195. }
  1196. } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
  1197. ref1 = btrfs_item_ptr(leaf, path->slots[0],
  1198. struct btrfs_extent_data_ref);
  1199. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  1200. } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
  1201. ref2 = btrfs_item_ptr(leaf, path->slots[0],
  1202. struct btrfs_shared_data_ref);
  1203. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  1204. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1205. } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
  1206. struct btrfs_extent_ref_v0 *ref0;
  1207. ref0 = btrfs_item_ptr(leaf, path->slots[0],
  1208. struct btrfs_extent_ref_v0);
  1209. num_refs = btrfs_ref_count_v0(leaf, ref0);
  1210. #endif
  1211. } else {
  1212. WARN_ON(1);
  1213. }
  1214. return num_refs;
  1215. }
  1216. static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
  1217. struct btrfs_root *root,
  1218. struct btrfs_path *path,
  1219. u64 bytenr, u64 parent,
  1220. u64 root_objectid)
  1221. {
  1222. struct btrfs_key key;
  1223. int ret;
  1224. key.objectid = bytenr;
  1225. if (parent) {
  1226. key.type = BTRFS_SHARED_BLOCK_REF_KEY;
  1227. key.offset = parent;
  1228. } else {
  1229. key.type = BTRFS_TREE_BLOCK_REF_KEY;
  1230. key.offset = root_objectid;
  1231. }
  1232. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1233. if (ret > 0)
  1234. ret = -ENOENT;
  1235. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1236. if (ret == -ENOENT && parent) {
  1237. btrfs_release_path(path);
  1238. key.type = BTRFS_EXTENT_REF_V0_KEY;
  1239. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1240. if (ret > 0)
  1241. ret = -ENOENT;
  1242. }
  1243. #endif
  1244. return ret;
  1245. }
  1246. static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
  1247. struct btrfs_root *root,
  1248. struct btrfs_path *path,
  1249. u64 bytenr, u64 parent,
  1250. u64 root_objectid)
  1251. {
  1252. struct btrfs_key key;
  1253. int ret;
  1254. key.objectid = bytenr;
  1255. if (parent) {
  1256. key.type = BTRFS_SHARED_BLOCK_REF_KEY;
  1257. key.offset = parent;
  1258. } else {
  1259. key.type = BTRFS_TREE_BLOCK_REF_KEY;
  1260. key.offset = root_objectid;
  1261. }
  1262. ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
  1263. btrfs_release_path(path);
  1264. return ret;
  1265. }
  1266. static inline int extent_ref_type(u64 parent, u64 owner)
  1267. {
  1268. int type;
  1269. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1270. if (parent > 0)
  1271. type = BTRFS_SHARED_BLOCK_REF_KEY;
  1272. else
  1273. type = BTRFS_TREE_BLOCK_REF_KEY;
  1274. } else {
  1275. if (parent > 0)
  1276. type = BTRFS_SHARED_DATA_REF_KEY;
  1277. else
  1278. type = BTRFS_EXTENT_DATA_REF_KEY;
  1279. }
  1280. return type;
  1281. }
  1282. static int find_next_key(struct btrfs_path *path, int level,
  1283. struct btrfs_key *key)
  1284. {
  1285. for (; level < BTRFS_MAX_LEVEL; level++) {
  1286. if (!path->nodes[level])
  1287. break;
  1288. if (path->slots[level] + 1 >=
  1289. btrfs_header_nritems(path->nodes[level]))
  1290. continue;
  1291. if (level == 0)
  1292. btrfs_item_key_to_cpu(path->nodes[level], key,
  1293. path->slots[level] + 1);
  1294. else
  1295. btrfs_node_key_to_cpu(path->nodes[level], key,
  1296. path->slots[level] + 1);
  1297. return 0;
  1298. }
  1299. return 1;
  1300. }
  1301. /*
  1302. * look for inline back ref. if back ref is found, *ref_ret is set
  1303. * to the address of inline back ref, and 0 is returned.
  1304. *
  1305. * if back ref isn't found, *ref_ret is set to the address where it
  1306. * should be inserted, and -ENOENT is returned.
  1307. *
  1308. * if insert is true and there are too many inline back refs, the path
  1309. * points to the extent item, and -EAGAIN is returned.
  1310. *
  1311. * NOTE: inline back refs are ordered in the same way that back ref
  1312. * items in the tree are ordered.
  1313. */
  1314. static noinline_for_stack
  1315. int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
  1316. struct btrfs_root *root,
  1317. struct btrfs_path *path,
  1318. struct btrfs_extent_inline_ref **ref_ret,
  1319. u64 bytenr, u64 num_bytes,
  1320. u64 parent, u64 root_objectid,
  1321. u64 owner, u64 offset, int insert)
  1322. {
  1323. struct btrfs_key key;
  1324. struct extent_buffer *leaf;
  1325. struct btrfs_extent_item *ei;
  1326. struct btrfs_extent_inline_ref *iref;
  1327. u64 flags;
  1328. u64 item_size;
  1329. unsigned long ptr;
  1330. unsigned long end;
  1331. int extra_size;
  1332. int type;
  1333. int want;
  1334. int ret;
  1335. int err = 0;
  1336. bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
  1337. SKINNY_METADATA);
  1338. key.objectid = bytenr;
  1339. key.type = BTRFS_EXTENT_ITEM_KEY;
  1340. key.offset = num_bytes;
  1341. want = extent_ref_type(parent, owner);
  1342. if (insert) {
  1343. extra_size = btrfs_extent_inline_ref_size(want);
  1344. path->keep_locks = 1;
  1345. } else
  1346. extra_size = -1;
  1347. /*
  1348. * Owner is our parent level, so we can just add one to get the level
  1349. * for the block we are interested in.
  1350. */
  1351. if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
  1352. key.type = BTRFS_METADATA_ITEM_KEY;
  1353. key.offset = owner;
  1354. }
  1355. again:
  1356. ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
  1357. if (ret < 0) {
  1358. err = ret;
  1359. goto out;
  1360. }
  1361. /*
  1362. * We may be a newly converted file system which still has the old fat
  1363. * extent entries for metadata, so try and see if we have one of those.
  1364. */
  1365. if (ret > 0 && skinny_metadata) {
  1366. skinny_metadata = false;
  1367. if (path->slots[0]) {
  1368. path->slots[0]--;
  1369. btrfs_item_key_to_cpu(path->nodes[0], &key,
  1370. path->slots[0]);
  1371. if (key.objectid == bytenr &&
  1372. key.type == BTRFS_EXTENT_ITEM_KEY &&
  1373. key.offset == num_bytes)
  1374. ret = 0;
  1375. }
  1376. if (ret) {
  1377. key.objectid = bytenr;
  1378. key.type = BTRFS_EXTENT_ITEM_KEY;
  1379. key.offset = num_bytes;
  1380. btrfs_release_path(path);
  1381. goto again;
  1382. }
  1383. }
  1384. if (ret && !insert) {
  1385. err = -ENOENT;
  1386. goto out;
  1387. } else if (WARN_ON(ret)) {
  1388. err = -EIO;
  1389. goto out;
  1390. }
  1391. leaf = path->nodes[0];
  1392. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1393. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1394. if (item_size < sizeof(*ei)) {
  1395. if (!insert) {
  1396. err = -ENOENT;
  1397. goto out;
  1398. }
  1399. ret = convert_extent_item_v0(trans, root, path, owner,
  1400. extra_size);
  1401. if (ret < 0) {
  1402. err = ret;
  1403. goto out;
  1404. }
  1405. leaf = path->nodes[0];
  1406. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1407. }
  1408. #endif
  1409. BUG_ON(item_size < sizeof(*ei));
  1410. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1411. flags = btrfs_extent_flags(leaf, ei);
  1412. ptr = (unsigned long)(ei + 1);
  1413. end = (unsigned long)ei + item_size;
  1414. if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
  1415. ptr += sizeof(struct btrfs_tree_block_info);
  1416. BUG_ON(ptr > end);
  1417. }
  1418. err = -ENOENT;
  1419. while (1) {
  1420. if (ptr >= end) {
  1421. WARN_ON(ptr > end);
  1422. break;
  1423. }
  1424. iref = (struct btrfs_extent_inline_ref *)ptr;
  1425. type = btrfs_extent_inline_ref_type(leaf, iref);
  1426. if (want < type)
  1427. break;
  1428. if (want > type) {
  1429. ptr += btrfs_extent_inline_ref_size(type);
  1430. continue;
  1431. }
  1432. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1433. struct btrfs_extent_data_ref *dref;
  1434. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  1435. if (match_extent_data_ref(leaf, dref, root_objectid,
  1436. owner, offset)) {
  1437. err = 0;
  1438. break;
  1439. }
  1440. if (hash_extent_data_ref_item(leaf, dref) <
  1441. hash_extent_data_ref(root_objectid, owner, offset))
  1442. break;
  1443. } else {
  1444. u64 ref_offset;
  1445. ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
  1446. if (parent > 0) {
  1447. if (parent == ref_offset) {
  1448. err = 0;
  1449. break;
  1450. }
  1451. if (ref_offset < parent)
  1452. break;
  1453. } else {
  1454. if (root_objectid == ref_offset) {
  1455. err = 0;
  1456. break;
  1457. }
  1458. if (ref_offset < root_objectid)
  1459. break;
  1460. }
  1461. }
  1462. ptr += btrfs_extent_inline_ref_size(type);
  1463. }
  1464. if (err == -ENOENT && insert) {
  1465. if (item_size + extra_size >=
  1466. BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
  1467. err = -EAGAIN;
  1468. goto out;
  1469. }
  1470. /*
  1471. * To add new inline back ref, we have to make sure
  1472. * there is no corresponding back ref item.
  1473. * For simplicity, we just do not add new inline back
  1474. * ref if there is any kind of item for this block
  1475. */
  1476. if (find_next_key(path, 0, &key) == 0 &&
  1477. key.objectid == bytenr &&
  1478. key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
  1479. err = -EAGAIN;
  1480. goto out;
  1481. }
  1482. }
  1483. *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
  1484. out:
  1485. if (insert) {
  1486. path->keep_locks = 0;
  1487. btrfs_unlock_up_safe(path, 1);
  1488. }
  1489. return err;
  1490. }
  1491. /*
  1492. * helper to add new inline back ref
  1493. */
  1494. static noinline_for_stack
  1495. void setup_inline_extent_backref(struct btrfs_root *root,
  1496. struct btrfs_path *path,
  1497. struct btrfs_extent_inline_ref *iref,
  1498. u64 parent, u64 root_objectid,
  1499. u64 owner, u64 offset, int refs_to_add,
  1500. struct btrfs_delayed_extent_op *extent_op)
  1501. {
  1502. struct extent_buffer *leaf;
  1503. struct btrfs_extent_item *ei;
  1504. unsigned long ptr;
  1505. unsigned long end;
  1506. unsigned long item_offset;
  1507. u64 refs;
  1508. int size;
  1509. int type;
  1510. leaf = path->nodes[0];
  1511. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1512. item_offset = (unsigned long)iref - (unsigned long)ei;
  1513. type = extent_ref_type(parent, owner);
  1514. size = btrfs_extent_inline_ref_size(type);
  1515. btrfs_extend_item(root, path, size);
  1516. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1517. refs = btrfs_extent_refs(leaf, ei);
  1518. refs += refs_to_add;
  1519. btrfs_set_extent_refs(leaf, ei, refs);
  1520. if (extent_op)
  1521. __run_delayed_extent_op(extent_op, leaf, ei);
  1522. ptr = (unsigned long)ei + item_offset;
  1523. end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
  1524. if (ptr < end - size)
  1525. memmove_extent_buffer(leaf, ptr + size, ptr,
  1526. end - size - ptr);
  1527. iref = (struct btrfs_extent_inline_ref *)ptr;
  1528. btrfs_set_extent_inline_ref_type(leaf, iref, type);
  1529. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1530. struct btrfs_extent_data_ref *dref;
  1531. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  1532. btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
  1533. btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
  1534. btrfs_set_extent_data_ref_offset(leaf, dref, offset);
  1535. btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
  1536. } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
  1537. struct btrfs_shared_data_ref *sref;
  1538. sref = (struct btrfs_shared_data_ref *)(iref + 1);
  1539. btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
  1540. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  1541. } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
  1542. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  1543. } else {
  1544. btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
  1545. }
  1546. btrfs_mark_buffer_dirty(leaf);
  1547. }
  1548. static int lookup_extent_backref(struct btrfs_trans_handle *trans,
  1549. struct btrfs_root *root,
  1550. struct btrfs_path *path,
  1551. struct btrfs_extent_inline_ref **ref_ret,
  1552. u64 bytenr, u64 num_bytes, u64 parent,
  1553. u64 root_objectid, u64 owner, u64 offset)
  1554. {
  1555. int ret;
  1556. ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
  1557. bytenr, num_bytes, parent,
  1558. root_objectid, owner, offset, 0);
  1559. if (ret != -ENOENT)
  1560. return ret;
  1561. btrfs_release_path(path);
  1562. *ref_ret = NULL;
  1563. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1564. ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
  1565. root_objectid);
  1566. } else {
  1567. ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
  1568. root_objectid, owner, offset);
  1569. }
  1570. return ret;
  1571. }
  1572. /*
  1573. * helper to update/remove inline back ref
  1574. */
  1575. static noinline_for_stack
  1576. void update_inline_extent_backref(struct btrfs_root *root,
  1577. struct btrfs_path *path,
  1578. struct btrfs_extent_inline_ref *iref,
  1579. int refs_to_mod,
  1580. struct btrfs_delayed_extent_op *extent_op,
  1581. int *last_ref)
  1582. {
  1583. struct extent_buffer *leaf;
  1584. struct btrfs_extent_item *ei;
  1585. struct btrfs_extent_data_ref *dref = NULL;
  1586. struct btrfs_shared_data_ref *sref = NULL;
  1587. unsigned long ptr;
  1588. unsigned long end;
  1589. u32 item_size;
  1590. int size;
  1591. int type;
  1592. u64 refs;
  1593. leaf = path->nodes[0];
  1594. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1595. refs = btrfs_extent_refs(leaf, ei);
  1596. WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
  1597. refs += refs_to_mod;
  1598. btrfs_set_extent_refs(leaf, ei, refs);
  1599. if (extent_op)
  1600. __run_delayed_extent_op(extent_op, leaf, ei);
  1601. type = btrfs_extent_inline_ref_type(leaf, iref);
  1602. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1603. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  1604. refs = btrfs_extent_data_ref_count(leaf, dref);
  1605. } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
  1606. sref = (struct btrfs_shared_data_ref *)(iref + 1);
  1607. refs = btrfs_shared_data_ref_count(leaf, sref);
  1608. } else {
  1609. refs = 1;
  1610. BUG_ON(refs_to_mod != -1);
  1611. }
  1612. BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
  1613. refs += refs_to_mod;
  1614. if (refs > 0) {
  1615. if (type == BTRFS_EXTENT_DATA_REF_KEY)
  1616. btrfs_set_extent_data_ref_count(leaf, dref, refs);
  1617. else
  1618. btrfs_set_shared_data_ref_count(leaf, sref, refs);
  1619. } else {
  1620. *last_ref = 1;
  1621. size = btrfs_extent_inline_ref_size(type);
  1622. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1623. ptr = (unsigned long)iref;
  1624. end = (unsigned long)ei + item_size;
  1625. if (ptr + size < end)
  1626. memmove_extent_buffer(leaf, ptr, ptr + size,
  1627. end - ptr - size);
  1628. item_size -= size;
  1629. btrfs_truncate_item(root, path, item_size, 1);
  1630. }
  1631. btrfs_mark_buffer_dirty(leaf);
  1632. }
  1633. static noinline_for_stack
  1634. int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
  1635. struct btrfs_root *root,
  1636. struct btrfs_path *path,
  1637. u64 bytenr, u64 num_bytes, u64 parent,
  1638. u64 root_objectid, u64 owner,
  1639. u64 offset, int refs_to_add,
  1640. struct btrfs_delayed_extent_op *extent_op)
  1641. {
  1642. struct btrfs_extent_inline_ref *iref;
  1643. int ret;
  1644. ret = lookup_inline_extent_backref(trans, root, path, &iref,
  1645. bytenr, num_bytes, parent,
  1646. root_objectid, owner, offset, 1);
  1647. if (ret == 0) {
  1648. BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
  1649. update_inline_extent_backref(root, path, iref,
  1650. refs_to_add, extent_op, NULL);
  1651. } else if (ret == -ENOENT) {
  1652. setup_inline_extent_backref(root, path, iref, parent,
  1653. root_objectid, owner, offset,
  1654. refs_to_add, extent_op);
  1655. ret = 0;
  1656. }
  1657. return ret;
  1658. }
  1659. static int insert_extent_backref(struct btrfs_trans_handle *trans,
  1660. struct btrfs_root *root,
  1661. struct btrfs_path *path,
  1662. u64 bytenr, u64 parent, u64 root_objectid,
  1663. u64 owner, u64 offset, int refs_to_add)
  1664. {
  1665. int ret;
  1666. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1667. BUG_ON(refs_to_add != 1);
  1668. ret = insert_tree_block_ref(trans, root, path, bytenr,
  1669. parent, root_objectid);
  1670. } else {
  1671. ret = insert_extent_data_ref(trans, root, path, bytenr,
  1672. parent, root_objectid,
  1673. owner, offset, refs_to_add);
  1674. }
  1675. return ret;
  1676. }
  1677. static int remove_extent_backref(struct btrfs_trans_handle *trans,
  1678. struct btrfs_root *root,
  1679. struct btrfs_path *path,
  1680. struct btrfs_extent_inline_ref *iref,
  1681. int refs_to_drop, int is_data, int *last_ref)
  1682. {
  1683. int ret = 0;
  1684. BUG_ON(!is_data && refs_to_drop != 1);
  1685. if (iref) {
  1686. update_inline_extent_backref(root, path, iref,
  1687. -refs_to_drop, NULL, last_ref);
  1688. } else if (is_data) {
  1689. ret = remove_extent_data_ref(trans, root, path, refs_to_drop,
  1690. last_ref);
  1691. } else {
  1692. *last_ref = 1;
  1693. ret = btrfs_del_item(trans, root, path);
  1694. }
  1695. return ret;
  1696. }
  1697. #define in_range(b, first, len) ((b) >= (first) && (b) < (first) + (len))
  1698. static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
  1699. u64 *discarded_bytes)
  1700. {
  1701. int j, ret = 0;
  1702. u64 bytes_left, end;
  1703. u64 aligned_start = ALIGN(start, 1 << 9);
  1704. if (WARN_ON(start != aligned_start)) {
  1705. len -= aligned_start - start;
  1706. len = round_down(len, 1 << 9);
  1707. start = aligned_start;
  1708. }
  1709. *discarded_bytes = 0;
  1710. if (!len)
  1711. return 0;
  1712. end = start + len;
  1713. bytes_left = len;
  1714. /* Skip any superblocks on this device. */
  1715. for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
  1716. u64 sb_start = btrfs_sb_offset(j);
  1717. u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
  1718. u64 size = sb_start - start;
  1719. if (!in_range(sb_start, start, bytes_left) &&
  1720. !in_range(sb_end, start, bytes_left) &&
  1721. !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
  1722. continue;
  1723. /*
  1724. * Superblock spans beginning of range. Adjust start and
  1725. * try again.
  1726. */
  1727. if (sb_start <= start) {
  1728. start += sb_end - start;
  1729. if (start > end) {
  1730. bytes_left = 0;
  1731. break;
  1732. }
  1733. bytes_left = end - start;
  1734. continue;
  1735. }
  1736. if (size) {
  1737. ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
  1738. GFP_NOFS, 0);
  1739. if (!ret)
  1740. *discarded_bytes += size;
  1741. else if (ret != -EOPNOTSUPP)
  1742. return ret;
  1743. }
  1744. start = sb_end;
  1745. if (start > end) {
  1746. bytes_left = 0;
  1747. break;
  1748. }
  1749. bytes_left = end - start;
  1750. }
  1751. if (bytes_left) {
  1752. ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
  1753. GFP_NOFS, 0);
  1754. if (!ret)
  1755. *discarded_bytes += bytes_left;
  1756. }
  1757. return ret;
  1758. }
  1759. int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
  1760. u64 num_bytes, u64 *actual_bytes)
  1761. {
  1762. int ret;
  1763. u64 discarded_bytes = 0;
  1764. struct btrfs_bio *bbio = NULL;
  1765. /* Tell the block device(s) that the sectors can be discarded */
  1766. ret = btrfs_map_block(root->fs_info, REQ_DISCARD,
  1767. bytenr, &num_bytes, &bbio, 0);
  1768. /* Error condition is -ENOMEM */
  1769. if (!ret) {
  1770. struct btrfs_bio_stripe *stripe = bbio->stripes;
  1771. int i;
  1772. for (i = 0; i < bbio->num_stripes; i++, stripe++) {
  1773. u64 bytes;
  1774. if (!stripe->dev->can_discard)
  1775. continue;
  1776. ret = btrfs_issue_discard(stripe->dev->bdev,
  1777. stripe->physical,
  1778. stripe->length,
  1779. &bytes);
  1780. if (!ret)
  1781. discarded_bytes += bytes;
  1782. else if (ret != -EOPNOTSUPP)
  1783. break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
  1784. /*
  1785. * Just in case we get back EOPNOTSUPP for some reason,
  1786. * just ignore the return value so we don't screw up
  1787. * people calling discard_extent.
  1788. */
  1789. ret = 0;
  1790. }
  1791. btrfs_put_bbio(bbio);
  1792. }
  1793. if (actual_bytes)
  1794. *actual_bytes = discarded_bytes;
  1795. if (ret == -EOPNOTSUPP)
  1796. ret = 0;
  1797. return ret;
  1798. }
  1799. /* Can return -ENOMEM */
  1800. int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
  1801. struct btrfs_root *root,
  1802. u64 bytenr, u64 num_bytes, u64 parent,
  1803. u64 root_objectid, u64 owner, u64 offset,
  1804. int no_quota)
  1805. {
  1806. int ret;
  1807. struct btrfs_fs_info *fs_info = root->fs_info;
  1808. BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
  1809. root_objectid == BTRFS_TREE_LOG_OBJECTID);
  1810. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1811. ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
  1812. num_bytes,
  1813. parent, root_objectid, (int)owner,
  1814. BTRFS_ADD_DELAYED_REF, NULL, no_quota);
  1815. } else {
  1816. ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
  1817. num_bytes,
  1818. parent, root_objectid, owner, offset,
  1819. BTRFS_ADD_DELAYED_REF, NULL, no_quota);
  1820. }
  1821. return ret;
  1822. }
  1823. static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
  1824. struct btrfs_root *root,
  1825. struct btrfs_delayed_ref_node *node,
  1826. u64 parent, u64 root_objectid,
  1827. u64 owner, u64 offset, int refs_to_add,
  1828. struct btrfs_delayed_extent_op *extent_op)
  1829. {
  1830. struct btrfs_fs_info *fs_info = root->fs_info;
  1831. struct btrfs_path *path;
  1832. struct extent_buffer *leaf;
  1833. struct btrfs_extent_item *item;
  1834. struct btrfs_key key;
  1835. u64 bytenr = node->bytenr;
  1836. u64 num_bytes = node->num_bytes;
  1837. u64 refs;
  1838. int ret;
  1839. int no_quota = node->no_quota;
  1840. path = btrfs_alloc_path();
  1841. if (!path)
  1842. return -ENOMEM;
  1843. if (!is_fstree(root_objectid) || !root->fs_info->quota_enabled)
  1844. no_quota = 1;
  1845. path->reada = 1;
  1846. path->leave_spinning = 1;
  1847. /* this will setup the path even if it fails to insert the back ref */
  1848. ret = insert_inline_extent_backref(trans, fs_info->extent_root, path,
  1849. bytenr, num_bytes, parent,
  1850. root_objectid, owner, offset,
  1851. refs_to_add, extent_op);
  1852. if ((ret < 0 && ret != -EAGAIN) || !ret)
  1853. goto out;
  1854. /*
  1855. * Ok we had -EAGAIN which means we didn't have space to insert and
  1856. * inline extent ref, so just update the reference count and add a
  1857. * normal backref.
  1858. */
  1859. leaf = path->nodes[0];
  1860. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1861. item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1862. refs = btrfs_extent_refs(leaf, item);
  1863. btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
  1864. if (extent_op)
  1865. __run_delayed_extent_op(extent_op, leaf, item);
  1866. btrfs_mark_buffer_dirty(leaf);
  1867. btrfs_release_path(path);
  1868. path->reada = 1;
  1869. path->leave_spinning = 1;
  1870. /* now insert the actual backref */
  1871. ret = insert_extent_backref(trans, root->fs_info->extent_root,
  1872. path, bytenr, parent, root_objectid,
  1873. owner, offset, refs_to_add);
  1874. if (ret)
  1875. btrfs_abort_transaction(trans, root, ret);
  1876. out:
  1877. btrfs_free_path(path);
  1878. return ret;
  1879. }
  1880. static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
  1881. struct btrfs_root *root,
  1882. struct btrfs_delayed_ref_node *node,
  1883. struct btrfs_delayed_extent_op *extent_op,
  1884. int insert_reserved)
  1885. {
  1886. int ret = 0;
  1887. struct btrfs_delayed_data_ref *ref;
  1888. struct btrfs_key ins;
  1889. u64 parent = 0;
  1890. u64 ref_root = 0;
  1891. u64 flags = 0;
  1892. ins.objectid = node->bytenr;
  1893. ins.offset = node->num_bytes;
  1894. ins.type = BTRFS_EXTENT_ITEM_KEY;
  1895. ref = btrfs_delayed_node_to_data_ref(node);
  1896. trace_run_delayed_data_ref(node, ref, node->action);
  1897. if (node->type == BTRFS_SHARED_DATA_REF_KEY)
  1898. parent = ref->parent;
  1899. ref_root = ref->root;
  1900. if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
  1901. if (extent_op)
  1902. flags |= extent_op->flags_to_set;
  1903. ret = alloc_reserved_file_extent(trans, root,
  1904. parent, ref_root, flags,
  1905. ref->objectid, ref->offset,
  1906. &ins, node->ref_mod);
  1907. } else if (node->action == BTRFS_ADD_DELAYED_REF) {
  1908. ret = __btrfs_inc_extent_ref(trans, root, node, parent,
  1909. ref_root, ref->objectid,
  1910. ref->offset, node->ref_mod,
  1911. extent_op);
  1912. } else if (node->action == BTRFS_DROP_DELAYED_REF) {
  1913. ret = __btrfs_free_extent(trans, root, node, parent,
  1914. ref_root, ref->objectid,
  1915. ref->offset, node->ref_mod,
  1916. extent_op);
  1917. } else {
  1918. BUG();
  1919. }
  1920. return ret;
  1921. }
  1922. static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
  1923. struct extent_buffer *leaf,
  1924. struct btrfs_extent_item *ei)
  1925. {
  1926. u64 flags = btrfs_extent_flags(leaf, ei);
  1927. if (extent_op->update_flags) {
  1928. flags |= extent_op->flags_to_set;
  1929. btrfs_set_extent_flags(leaf, ei, flags);
  1930. }
  1931. if (extent_op->update_key) {
  1932. struct btrfs_tree_block_info *bi;
  1933. BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
  1934. bi = (struct btrfs_tree_block_info *)(ei + 1);
  1935. btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
  1936. }
  1937. }
  1938. static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
  1939. struct btrfs_root *root,
  1940. struct btrfs_delayed_ref_node *node,
  1941. struct btrfs_delayed_extent_op *extent_op)
  1942. {
  1943. struct btrfs_key key;
  1944. struct btrfs_path *path;
  1945. struct btrfs_extent_item *ei;
  1946. struct extent_buffer *leaf;
  1947. u32 item_size;
  1948. int ret;
  1949. int err = 0;
  1950. int metadata = !extent_op->is_data;
  1951. if (trans->aborted)
  1952. return 0;
  1953. if (metadata && !btrfs_fs_incompat(root->fs_info, SKINNY_METADATA))
  1954. metadata = 0;
  1955. path = btrfs_alloc_path();
  1956. if (!path)
  1957. return -ENOMEM;
  1958. key.objectid = node->bytenr;
  1959. if (metadata) {
  1960. key.type = BTRFS_METADATA_ITEM_KEY;
  1961. key.offset = extent_op->level;
  1962. } else {
  1963. key.type = BTRFS_EXTENT_ITEM_KEY;
  1964. key.offset = node->num_bytes;
  1965. }
  1966. again:
  1967. path->reada = 1;
  1968. path->leave_spinning = 1;
  1969. ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
  1970. path, 0, 1);
  1971. if (ret < 0) {
  1972. err = ret;
  1973. goto out;
  1974. }
  1975. if (ret > 0) {
  1976. if (metadata) {
  1977. if (path->slots[0] > 0) {
  1978. path->slots[0]--;
  1979. btrfs_item_key_to_cpu(path->nodes[0], &key,
  1980. path->slots[0]);
  1981. if (key.objectid == node->bytenr &&
  1982. key.type == BTRFS_EXTENT_ITEM_KEY &&
  1983. key.offset == node->num_bytes)
  1984. ret = 0;
  1985. }
  1986. if (ret > 0) {
  1987. btrfs_release_path(path);
  1988. metadata = 0;
  1989. key.objectid = node->bytenr;
  1990. key.offset = node->num_bytes;
  1991. key.type = BTRFS_EXTENT_ITEM_KEY;
  1992. goto again;
  1993. }
  1994. } else {
  1995. err = -EIO;
  1996. goto out;
  1997. }
  1998. }
  1999. leaf = path->nodes[0];
  2000. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  2001. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  2002. if (item_size < sizeof(*ei)) {
  2003. ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
  2004. path, (u64)-1, 0);
  2005. if (ret < 0) {
  2006. err = ret;
  2007. goto out;
  2008. }
  2009. leaf = path->nodes[0];
  2010. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  2011. }
  2012. #endif
  2013. BUG_ON(item_size < sizeof(*ei));
  2014. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  2015. __run_delayed_extent_op(extent_op, leaf, ei);
  2016. btrfs_mark_buffer_dirty(leaf);
  2017. out:
  2018. btrfs_free_path(path);
  2019. return err;
  2020. }
  2021. static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
  2022. struct btrfs_root *root,
  2023. struct btrfs_delayed_ref_node *node,
  2024. struct btrfs_delayed_extent_op *extent_op,
  2025. int insert_reserved)
  2026. {
  2027. int ret = 0;
  2028. struct btrfs_delayed_tree_ref *ref;
  2029. struct btrfs_key ins;
  2030. u64 parent = 0;
  2031. u64 ref_root = 0;
  2032. bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
  2033. SKINNY_METADATA);
  2034. ref = btrfs_delayed_node_to_tree_ref(node);
  2035. trace_run_delayed_tree_ref(node, ref, node->action);
  2036. if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
  2037. parent = ref->parent;
  2038. ref_root = ref->root;
  2039. ins.objectid = node->bytenr;
  2040. if (skinny_metadata) {
  2041. ins.offset = ref->level;
  2042. ins.type = BTRFS_METADATA_ITEM_KEY;
  2043. } else {
  2044. ins.offset = node->num_bytes;
  2045. ins.type = BTRFS_EXTENT_ITEM_KEY;
  2046. }
  2047. BUG_ON(node->ref_mod != 1);
  2048. if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
  2049. BUG_ON(!extent_op || !extent_op->update_flags);
  2050. ret = alloc_reserved_tree_block(trans, root,
  2051. parent, ref_root,
  2052. extent_op->flags_to_set,
  2053. &extent_op->key,
  2054. ref->level, &ins,
  2055. node->no_quota);
  2056. } else if (node->action == BTRFS_ADD_DELAYED_REF) {
  2057. ret = __btrfs_inc_extent_ref(trans, root, node,
  2058. parent, ref_root,
  2059. ref->level, 0, 1,
  2060. extent_op);
  2061. } else if (node->action == BTRFS_DROP_DELAYED_REF) {
  2062. ret = __btrfs_free_extent(trans, root, node,
  2063. parent, ref_root,
  2064. ref->level, 0, 1, extent_op);
  2065. } else {
  2066. BUG();
  2067. }
  2068. return ret;
  2069. }
  2070. /* helper function to actually process a single delayed ref entry */
  2071. static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
  2072. struct btrfs_root *root,
  2073. struct btrfs_delayed_ref_node *node,
  2074. struct btrfs_delayed_extent_op *extent_op,
  2075. int insert_reserved)
  2076. {
  2077. int ret = 0;
  2078. if (trans->aborted) {
  2079. if (insert_reserved)
  2080. btrfs_pin_extent(root, node->bytenr,
  2081. node->num_bytes, 1);
  2082. return 0;
  2083. }
  2084. if (btrfs_delayed_ref_is_head(node)) {
  2085. struct btrfs_delayed_ref_head *head;
  2086. /*
  2087. * we've hit the end of the chain and we were supposed
  2088. * to insert this extent into the tree. But, it got
  2089. * deleted before we ever needed to insert it, so all
  2090. * we have to do is clean up the accounting
  2091. */
  2092. BUG_ON(extent_op);
  2093. head = btrfs_delayed_node_to_head(node);
  2094. trace_run_delayed_ref_head(node, head, node->action);
  2095. if (insert_reserved) {
  2096. btrfs_pin_extent(root, node->bytenr,
  2097. node->num_bytes, 1);
  2098. if (head->is_data) {
  2099. ret = btrfs_del_csums(trans, root,
  2100. node->bytenr,
  2101. node->num_bytes);
  2102. }
  2103. }
  2104. return ret;
  2105. }
  2106. if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
  2107. node->type == BTRFS_SHARED_BLOCK_REF_KEY)
  2108. ret = run_delayed_tree_ref(trans, root, node, extent_op,
  2109. insert_reserved);
  2110. else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
  2111. node->type == BTRFS_SHARED_DATA_REF_KEY)
  2112. ret = run_delayed_data_ref(trans, root, node, extent_op,
  2113. insert_reserved);
  2114. else
  2115. BUG();
  2116. return ret;
  2117. }
  2118. static inline struct btrfs_delayed_ref_node *
  2119. select_delayed_ref(struct btrfs_delayed_ref_head *head)
  2120. {
  2121. struct btrfs_delayed_ref_node *ref;
  2122. if (list_empty(&head->ref_list))
  2123. return NULL;
  2124. /*
  2125. * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
  2126. * This is to prevent a ref count from going down to zero, which deletes
  2127. * the extent item from the extent tree, when there still are references
  2128. * to add, which would fail because they would not find the extent item.
  2129. */
  2130. list_for_each_entry(ref, &head->ref_list, list) {
  2131. if (ref->action == BTRFS_ADD_DELAYED_REF)
  2132. return ref;
  2133. }
  2134. return list_entry(head->ref_list.next, struct btrfs_delayed_ref_node,
  2135. list);
  2136. }
  2137. /*
  2138. * Returns 0 on success or if called with an already aborted transaction.
  2139. * Returns -ENOMEM or -EIO on failure and will abort the transaction.
  2140. */
  2141. static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
  2142. struct btrfs_root *root,
  2143. unsigned long nr)
  2144. {
  2145. struct btrfs_delayed_ref_root *delayed_refs;
  2146. struct btrfs_delayed_ref_node *ref;
  2147. struct btrfs_delayed_ref_head *locked_ref = NULL;
  2148. struct btrfs_delayed_extent_op *extent_op;
  2149. struct btrfs_fs_info *fs_info = root->fs_info;
  2150. ktime_t start = ktime_get();
  2151. int ret;
  2152. unsigned long count = 0;
  2153. unsigned long actual_count = 0;
  2154. int must_insert_reserved = 0;
  2155. delayed_refs = &trans->transaction->delayed_refs;
  2156. while (1) {
  2157. if (!locked_ref) {
  2158. if (count >= nr)
  2159. break;
  2160. spin_lock(&delayed_refs->lock);
  2161. locked_ref = btrfs_select_ref_head(trans);
  2162. if (!locked_ref) {
  2163. spin_unlock(&delayed_refs->lock);
  2164. break;
  2165. }
  2166. /* grab the lock that says we are going to process
  2167. * all the refs for this head */
  2168. ret = btrfs_delayed_ref_lock(trans, locked_ref);
  2169. spin_unlock(&delayed_refs->lock);
  2170. /*
  2171. * we may have dropped the spin lock to get the head
  2172. * mutex lock, and that might have given someone else
  2173. * time to free the head. If that's true, it has been
  2174. * removed from our list and we can move on.
  2175. */
  2176. if (ret == -EAGAIN) {
  2177. locked_ref = NULL;
  2178. count++;
  2179. continue;
  2180. }
  2181. }
  2182. spin_lock(&locked_ref->lock);
  2183. /*
  2184. * locked_ref is the head node, so we have to go one
  2185. * node back for any delayed ref updates
  2186. */
  2187. ref = select_delayed_ref(locked_ref);
  2188. if (ref && ref->seq &&
  2189. btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
  2190. spin_unlock(&locked_ref->lock);
  2191. btrfs_delayed_ref_unlock(locked_ref);
  2192. spin_lock(&delayed_refs->lock);
  2193. locked_ref->processing = 0;
  2194. delayed_refs->num_heads_ready++;
  2195. spin_unlock(&delayed_refs->lock);
  2196. locked_ref = NULL;
  2197. cond_resched();
  2198. count++;
  2199. continue;
  2200. }
  2201. /*
  2202. * record the must insert reserved flag before we
  2203. * drop the spin lock.
  2204. */
  2205. must_insert_reserved = locked_ref->must_insert_reserved;
  2206. locked_ref->must_insert_reserved = 0;
  2207. extent_op = locked_ref->extent_op;
  2208. locked_ref->extent_op = NULL;
  2209. if (!ref) {
  2210. /* All delayed refs have been processed, Go ahead
  2211. * and send the head node to run_one_delayed_ref,
  2212. * so that any accounting fixes can happen
  2213. */
  2214. ref = &locked_ref->node;
  2215. if (extent_op && must_insert_reserved) {
  2216. btrfs_free_delayed_extent_op(extent_op);
  2217. extent_op = NULL;
  2218. }
  2219. if (extent_op) {
  2220. spin_unlock(&locked_ref->lock);
  2221. ret = run_delayed_extent_op(trans, root,
  2222. ref, extent_op);
  2223. btrfs_free_delayed_extent_op(extent_op);
  2224. if (ret) {
  2225. /*
  2226. * Need to reset must_insert_reserved if
  2227. * there was an error so the abort stuff
  2228. * can cleanup the reserved space
  2229. * properly.
  2230. */
  2231. if (must_insert_reserved)
  2232. locked_ref->must_insert_reserved = 1;
  2233. locked_ref->processing = 0;
  2234. btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
  2235. btrfs_delayed_ref_unlock(locked_ref);
  2236. return ret;
  2237. }
  2238. continue;
  2239. }
  2240. /*
  2241. * Need to drop our head ref lock and re-aqcuire the
  2242. * delayed ref lock and then re-check to make sure
  2243. * nobody got added.
  2244. */
  2245. spin_unlock(&locked_ref->lock);
  2246. spin_lock(&delayed_refs->lock);
  2247. spin_lock(&locked_ref->lock);
  2248. if (!list_empty(&locked_ref->ref_list) ||
  2249. locked_ref->extent_op) {
  2250. spin_unlock(&locked_ref->lock);
  2251. spin_unlock(&delayed_refs->lock);
  2252. continue;
  2253. }
  2254. ref->in_tree = 0;
  2255. delayed_refs->num_heads--;
  2256. rb_erase(&locked_ref->href_node,
  2257. &delayed_refs->href_root);
  2258. spin_unlock(&delayed_refs->lock);
  2259. } else {
  2260. actual_count++;
  2261. ref->in_tree = 0;
  2262. list_del(&ref->list);
  2263. }
  2264. atomic_dec(&delayed_refs->num_entries);
  2265. if (!btrfs_delayed_ref_is_head(ref)) {
  2266. /*
  2267. * when we play the delayed ref, also correct the
  2268. * ref_mod on head
  2269. */
  2270. switch (ref->action) {
  2271. case BTRFS_ADD_DELAYED_REF:
  2272. case BTRFS_ADD_DELAYED_EXTENT:
  2273. locked_ref->node.ref_mod -= ref->ref_mod;
  2274. break;
  2275. case BTRFS_DROP_DELAYED_REF:
  2276. locked_ref->node.ref_mod += ref->ref_mod;
  2277. break;
  2278. default:
  2279. WARN_ON(1);
  2280. }
  2281. }
  2282. spin_unlock(&locked_ref->lock);
  2283. ret = run_one_delayed_ref(trans, root, ref, extent_op,
  2284. must_insert_reserved);
  2285. btrfs_free_delayed_extent_op(extent_op);
  2286. if (ret) {
  2287. locked_ref->processing = 0;
  2288. btrfs_delayed_ref_unlock(locked_ref);
  2289. btrfs_put_delayed_ref(ref);
  2290. btrfs_debug(fs_info, "run_one_delayed_ref returned %d", ret);
  2291. return ret;
  2292. }
  2293. /*
  2294. * If this node is a head, that means all the refs in this head
  2295. * have been dealt with, and we will pick the next head to deal
  2296. * with, so we must unlock the head and drop it from the cluster
  2297. * list before we release it.
  2298. */
  2299. if (btrfs_delayed_ref_is_head(ref)) {
  2300. if (locked_ref->is_data &&
  2301. locked_ref->total_ref_mod < 0) {
  2302. spin_lock(&delayed_refs->lock);
  2303. delayed_refs->pending_csums -= ref->num_bytes;
  2304. spin_unlock(&delayed_refs->lock);
  2305. }
  2306. btrfs_delayed_ref_unlock(locked_ref);
  2307. locked_ref = NULL;
  2308. }
  2309. btrfs_put_delayed_ref(ref);
  2310. count++;
  2311. cond_resched();
  2312. }
  2313. /*
  2314. * We don't want to include ref heads since we can have empty ref heads
  2315. * and those will drastically skew our runtime down since we just do
  2316. * accounting, no actual extent tree updates.
  2317. */
  2318. if (actual_count > 0) {
  2319. u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
  2320. u64 avg;
  2321. /*
  2322. * We weigh the current average higher than our current runtime
  2323. * to avoid large swings in the average.
  2324. */
  2325. spin_lock(&delayed_refs->lock);
  2326. avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
  2327. fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
  2328. spin_unlock(&delayed_refs->lock);
  2329. }
  2330. return 0;
  2331. }
  2332. #ifdef SCRAMBLE_DELAYED_REFS
  2333. /*
  2334. * Normally delayed refs get processed in ascending bytenr order. This
  2335. * correlates in most cases to the order added. To expose dependencies on this
  2336. * order, we start to process the tree in the middle instead of the beginning
  2337. */
  2338. static u64 find_middle(struct rb_root *root)
  2339. {
  2340. struct rb_node *n = root->rb_node;
  2341. struct btrfs_delayed_ref_node *entry;
  2342. int alt = 1;
  2343. u64 middle;
  2344. u64 first = 0, last = 0;
  2345. n = rb_first(root);
  2346. if (n) {
  2347. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  2348. first = entry->bytenr;
  2349. }
  2350. n = rb_last(root);
  2351. if (n) {
  2352. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  2353. last = entry->bytenr;
  2354. }
  2355. n = root->rb_node;
  2356. while (n) {
  2357. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  2358. WARN_ON(!entry->in_tree);
  2359. middle = entry->bytenr;
  2360. if (alt)
  2361. n = n->rb_left;
  2362. else
  2363. n = n->rb_right;
  2364. alt = 1 - alt;
  2365. }
  2366. return middle;
  2367. }
  2368. #endif
  2369. static inline u64 heads_to_leaves(struct btrfs_root *root, u64 heads)
  2370. {
  2371. u64 num_bytes;
  2372. num_bytes = heads * (sizeof(struct btrfs_extent_item) +
  2373. sizeof(struct btrfs_extent_inline_ref));
  2374. if (!btrfs_fs_incompat(root->fs_info, SKINNY_METADATA))
  2375. num_bytes += heads * sizeof(struct btrfs_tree_block_info);
  2376. /*
  2377. * We don't ever fill up leaves all the way so multiply by 2 just to be
  2378. * closer to what we're really going to want to ouse.
  2379. */
  2380. return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(root));
  2381. }
  2382. /*
  2383. * Takes the number of bytes to be csumm'ed and figures out how many leaves it
  2384. * would require to store the csums for that many bytes.
  2385. */
  2386. u64 btrfs_csum_bytes_to_leaves(struct btrfs_root *root, u64 csum_bytes)
  2387. {
  2388. u64 csum_size;
  2389. u64 num_csums_per_leaf;
  2390. u64 num_csums;
  2391. csum_size = BTRFS_LEAF_DATA_SIZE(root) - sizeof(struct btrfs_item);
  2392. num_csums_per_leaf = div64_u64(csum_size,
  2393. (u64)btrfs_super_csum_size(root->fs_info->super_copy));
  2394. num_csums = div64_u64(csum_bytes, root->sectorsize);
  2395. num_csums += num_csums_per_leaf - 1;
  2396. num_csums = div64_u64(num_csums, num_csums_per_leaf);
  2397. return num_csums;
  2398. }
  2399. int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
  2400. struct btrfs_root *root)
  2401. {
  2402. struct btrfs_block_rsv *global_rsv;
  2403. u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
  2404. u64 csum_bytes = trans->transaction->delayed_refs.pending_csums;
  2405. u64 num_dirty_bgs = trans->transaction->num_dirty_bgs;
  2406. u64 num_bytes, num_dirty_bgs_bytes;
  2407. int ret = 0;
  2408. num_bytes = btrfs_calc_trans_metadata_size(root, 1);
  2409. num_heads = heads_to_leaves(root, num_heads);
  2410. if (num_heads > 1)
  2411. num_bytes += (num_heads - 1) * root->nodesize;
  2412. num_bytes <<= 1;
  2413. num_bytes += btrfs_csum_bytes_to_leaves(root, csum_bytes) * root->nodesize;
  2414. num_dirty_bgs_bytes = btrfs_calc_trans_metadata_size(root,
  2415. num_dirty_bgs);
  2416. global_rsv = &root->fs_info->global_block_rsv;
  2417. /*
  2418. * If we can't allocate any more chunks lets make sure we have _lots_ of
  2419. * wiggle room since running delayed refs can create more delayed refs.
  2420. */
  2421. if (global_rsv->space_info->full) {
  2422. num_dirty_bgs_bytes <<= 1;
  2423. num_bytes <<= 1;
  2424. }
  2425. spin_lock(&global_rsv->lock);
  2426. if (global_rsv->reserved <= num_bytes + num_dirty_bgs_bytes)
  2427. ret = 1;
  2428. spin_unlock(&global_rsv->lock);
  2429. return ret;
  2430. }
  2431. int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
  2432. struct btrfs_root *root)
  2433. {
  2434. struct btrfs_fs_info *fs_info = root->fs_info;
  2435. u64 num_entries =
  2436. atomic_read(&trans->transaction->delayed_refs.num_entries);
  2437. u64 avg_runtime;
  2438. u64 val;
  2439. smp_mb();
  2440. avg_runtime = fs_info->avg_delayed_ref_runtime;
  2441. val = num_entries * avg_runtime;
  2442. if (num_entries * avg_runtime >= NSEC_PER_SEC)
  2443. return 1;
  2444. if (val >= NSEC_PER_SEC / 2)
  2445. return 2;
  2446. return btrfs_check_space_for_delayed_refs(trans, root);
  2447. }
  2448. struct async_delayed_refs {
  2449. struct btrfs_root *root;
  2450. int count;
  2451. int error;
  2452. int sync;
  2453. struct completion wait;
  2454. struct btrfs_work work;
  2455. };
  2456. static void delayed_ref_async_start(struct btrfs_work *work)
  2457. {
  2458. struct async_delayed_refs *async;
  2459. struct btrfs_trans_handle *trans;
  2460. int ret;
  2461. async = container_of(work, struct async_delayed_refs, work);
  2462. trans = btrfs_join_transaction(async->root);
  2463. if (IS_ERR(trans)) {
  2464. async->error = PTR_ERR(trans);
  2465. goto done;
  2466. }
  2467. /*
  2468. * trans->sync means that when we call end_transaciton, we won't
  2469. * wait on delayed refs
  2470. */
  2471. trans->sync = true;
  2472. ret = btrfs_run_delayed_refs(trans, async->root, async->count);
  2473. if (ret)
  2474. async->error = ret;
  2475. ret = btrfs_end_transaction(trans, async->root);
  2476. if (ret && !async->error)
  2477. async->error = ret;
  2478. done:
  2479. if (async->sync)
  2480. complete(&async->wait);
  2481. else
  2482. kfree(async);
  2483. }
  2484. int btrfs_async_run_delayed_refs(struct btrfs_root *root,
  2485. unsigned long count, int wait)
  2486. {
  2487. struct async_delayed_refs *async;
  2488. int ret;
  2489. async = kmalloc(sizeof(*async), GFP_NOFS);
  2490. if (!async)
  2491. return -ENOMEM;
  2492. async->root = root->fs_info->tree_root;
  2493. async->count = count;
  2494. async->error = 0;
  2495. if (wait)
  2496. async->sync = 1;
  2497. else
  2498. async->sync = 0;
  2499. init_completion(&async->wait);
  2500. btrfs_init_work(&async->work, btrfs_extent_refs_helper,
  2501. delayed_ref_async_start, NULL, NULL);
  2502. btrfs_queue_work(root->fs_info->extent_workers, &async->work);
  2503. if (wait) {
  2504. wait_for_completion(&async->wait);
  2505. ret = async->error;
  2506. kfree(async);
  2507. return ret;
  2508. }
  2509. return 0;
  2510. }
  2511. /*
  2512. * this starts processing the delayed reference count updates and
  2513. * extent insertions we have queued up so far. count can be
  2514. * 0, which means to process everything in the tree at the start
  2515. * of the run (but not newly added entries), or it can be some target
  2516. * number you'd like to process.
  2517. *
  2518. * Returns 0 on success or if called with an aborted transaction
  2519. * Returns <0 on error and aborts the transaction
  2520. */
  2521. int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
  2522. struct btrfs_root *root, unsigned long count)
  2523. {
  2524. struct rb_node *node;
  2525. struct btrfs_delayed_ref_root *delayed_refs;
  2526. struct btrfs_delayed_ref_head *head;
  2527. int ret;
  2528. int run_all = count == (unsigned long)-1;
  2529. bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
  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. trans->can_flush_pending_bgs = false;
  2543. ret = __btrfs_run_delayed_refs(trans, root, count);
  2544. if (ret < 0) {
  2545. btrfs_abort_transaction(trans, root, ret);
  2546. return ret;
  2547. }
  2548. if (run_all) {
  2549. if (!list_empty(&trans->new_bgs))
  2550. btrfs_create_pending_block_groups(trans, root);
  2551. spin_lock(&delayed_refs->lock);
  2552. node = rb_first(&delayed_refs->href_root);
  2553. if (!node) {
  2554. spin_unlock(&delayed_refs->lock);
  2555. goto out;
  2556. }
  2557. count = (unsigned long)-1;
  2558. while (node) {
  2559. head = rb_entry(node, struct btrfs_delayed_ref_head,
  2560. href_node);
  2561. if (btrfs_delayed_ref_is_head(&head->node)) {
  2562. struct btrfs_delayed_ref_node *ref;
  2563. ref = &head->node;
  2564. atomic_inc(&ref->refs);
  2565. spin_unlock(&delayed_refs->lock);
  2566. /*
  2567. * Mutex was contended, block until it's
  2568. * released and try again
  2569. */
  2570. mutex_lock(&head->mutex);
  2571. mutex_unlock(&head->mutex);
  2572. btrfs_put_delayed_ref(ref);
  2573. cond_resched();
  2574. goto again;
  2575. } else {
  2576. WARN_ON(1);
  2577. }
  2578. node = rb_next(node);
  2579. }
  2580. spin_unlock(&delayed_refs->lock);
  2581. cond_resched();
  2582. goto again;
  2583. }
  2584. out:
  2585. assert_qgroups_uptodate(trans);
  2586. trans->can_flush_pending_bgs = can_flush_pending_bgs;
  2587. return 0;
  2588. }
  2589. int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
  2590. struct btrfs_root *root,
  2591. u64 bytenr, u64 num_bytes, u64 flags,
  2592. int level, int is_data)
  2593. {
  2594. struct btrfs_delayed_extent_op *extent_op;
  2595. int ret;
  2596. extent_op = btrfs_alloc_delayed_extent_op();
  2597. if (!extent_op)
  2598. return -ENOMEM;
  2599. extent_op->flags_to_set = flags;
  2600. extent_op->update_flags = 1;
  2601. extent_op->update_key = 0;
  2602. extent_op->is_data = is_data ? 1 : 0;
  2603. extent_op->level = level;
  2604. ret = btrfs_add_delayed_extent_op(root->fs_info, trans, bytenr,
  2605. num_bytes, extent_op);
  2606. if (ret)
  2607. btrfs_free_delayed_extent_op(extent_op);
  2608. return ret;
  2609. }
  2610. static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
  2611. struct btrfs_root *root,
  2612. struct btrfs_path *path,
  2613. u64 objectid, u64 offset, u64 bytenr)
  2614. {
  2615. struct btrfs_delayed_ref_head *head;
  2616. struct btrfs_delayed_ref_node *ref;
  2617. struct btrfs_delayed_data_ref *data_ref;
  2618. struct btrfs_delayed_ref_root *delayed_refs;
  2619. int ret = 0;
  2620. delayed_refs = &trans->transaction->delayed_refs;
  2621. spin_lock(&delayed_refs->lock);
  2622. head = btrfs_find_delayed_ref_head(trans, bytenr);
  2623. if (!head) {
  2624. spin_unlock(&delayed_refs->lock);
  2625. return 0;
  2626. }
  2627. if (!mutex_trylock(&head->mutex)) {
  2628. atomic_inc(&head->node.refs);
  2629. spin_unlock(&delayed_refs->lock);
  2630. btrfs_release_path(path);
  2631. /*
  2632. * Mutex was contended, block until it's released and let
  2633. * caller try again
  2634. */
  2635. mutex_lock(&head->mutex);
  2636. mutex_unlock(&head->mutex);
  2637. btrfs_put_delayed_ref(&head->node);
  2638. return -EAGAIN;
  2639. }
  2640. spin_unlock(&delayed_refs->lock);
  2641. spin_lock(&head->lock);
  2642. list_for_each_entry(ref, &head->ref_list, list) {
  2643. /* If it's a shared ref we know a cross reference exists */
  2644. if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
  2645. ret = 1;
  2646. break;
  2647. }
  2648. data_ref = btrfs_delayed_node_to_data_ref(ref);
  2649. /*
  2650. * If our ref doesn't match the one we're currently looking at
  2651. * then we have a cross reference.
  2652. */
  2653. if (data_ref->root != root->root_key.objectid ||
  2654. data_ref->objectid != objectid ||
  2655. data_ref->offset != offset) {
  2656. ret = 1;
  2657. break;
  2658. }
  2659. }
  2660. spin_unlock(&head->lock);
  2661. mutex_unlock(&head->mutex);
  2662. return ret;
  2663. }
  2664. static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
  2665. struct btrfs_root *root,
  2666. struct btrfs_path *path,
  2667. u64 objectid, u64 offset, u64 bytenr)
  2668. {
  2669. struct btrfs_root *extent_root = root->fs_info->extent_root;
  2670. struct extent_buffer *leaf;
  2671. struct btrfs_extent_data_ref *ref;
  2672. struct btrfs_extent_inline_ref *iref;
  2673. struct btrfs_extent_item *ei;
  2674. struct btrfs_key key;
  2675. u32 item_size;
  2676. int ret;
  2677. key.objectid = bytenr;
  2678. key.offset = (u64)-1;
  2679. key.type = BTRFS_EXTENT_ITEM_KEY;
  2680. ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
  2681. if (ret < 0)
  2682. goto out;
  2683. BUG_ON(ret == 0); /* Corruption */
  2684. ret = -ENOENT;
  2685. if (path->slots[0] == 0)
  2686. goto out;
  2687. path->slots[0]--;
  2688. leaf = path->nodes[0];
  2689. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  2690. if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
  2691. goto out;
  2692. ret = 1;
  2693. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  2694. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  2695. if (item_size < sizeof(*ei)) {
  2696. WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
  2697. goto out;
  2698. }
  2699. #endif
  2700. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  2701. if (item_size != sizeof(*ei) +
  2702. btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
  2703. goto out;
  2704. if (btrfs_extent_generation(leaf, ei) <=
  2705. btrfs_root_last_snapshot(&root->root_item))
  2706. goto out;
  2707. iref = (struct btrfs_extent_inline_ref *)(ei + 1);
  2708. if (btrfs_extent_inline_ref_type(leaf, iref) !=
  2709. BTRFS_EXTENT_DATA_REF_KEY)
  2710. goto out;
  2711. ref = (struct btrfs_extent_data_ref *)(&iref->offset);
  2712. if (btrfs_extent_refs(leaf, ei) !=
  2713. btrfs_extent_data_ref_count(leaf, ref) ||
  2714. btrfs_extent_data_ref_root(leaf, ref) !=
  2715. root->root_key.objectid ||
  2716. btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
  2717. btrfs_extent_data_ref_offset(leaf, ref) != offset)
  2718. goto out;
  2719. ret = 0;
  2720. out:
  2721. return ret;
  2722. }
  2723. int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
  2724. struct btrfs_root *root,
  2725. u64 objectid, u64 offset, u64 bytenr)
  2726. {
  2727. struct btrfs_path *path;
  2728. int ret;
  2729. int ret2;
  2730. path = btrfs_alloc_path();
  2731. if (!path)
  2732. return -ENOENT;
  2733. do {
  2734. ret = check_committed_ref(trans, root, path, objectid,
  2735. offset, bytenr);
  2736. if (ret && ret != -ENOENT)
  2737. goto out;
  2738. ret2 = check_delayed_ref(trans, root, path, objectid,
  2739. offset, bytenr);
  2740. } while (ret2 == -EAGAIN);
  2741. if (ret2 && ret2 != -ENOENT) {
  2742. ret = ret2;
  2743. goto out;
  2744. }
  2745. if (ret != -ENOENT || ret2 != -ENOENT)
  2746. ret = 0;
  2747. out:
  2748. btrfs_free_path(path);
  2749. if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
  2750. WARN_ON(ret > 0);
  2751. return ret;
  2752. }
  2753. static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
  2754. struct btrfs_root *root,
  2755. struct extent_buffer *buf,
  2756. int full_backref, int inc)
  2757. {
  2758. u64 bytenr;
  2759. u64 num_bytes;
  2760. u64 parent;
  2761. u64 ref_root;
  2762. u32 nritems;
  2763. struct btrfs_key key;
  2764. struct btrfs_file_extent_item *fi;
  2765. int i;
  2766. int level;
  2767. int ret = 0;
  2768. int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
  2769. u64, u64, u64, u64, u64, u64, int);
  2770. if (btrfs_test_is_dummy_root(root))
  2771. return 0;
  2772. ref_root = btrfs_header_owner(buf);
  2773. nritems = btrfs_header_nritems(buf);
  2774. level = btrfs_header_level(buf);
  2775. if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
  2776. return 0;
  2777. if (inc)
  2778. process_func = btrfs_inc_extent_ref;
  2779. else
  2780. process_func = btrfs_free_extent;
  2781. if (full_backref)
  2782. parent = buf->start;
  2783. else
  2784. parent = 0;
  2785. for (i = 0; i < nritems; i++) {
  2786. if (level == 0) {
  2787. btrfs_item_key_to_cpu(buf, &key, i);
  2788. if (key.type != BTRFS_EXTENT_DATA_KEY)
  2789. continue;
  2790. fi = btrfs_item_ptr(buf, i,
  2791. struct btrfs_file_extent_item);
  2792. if (btrfs_file_extent_type(buf, fi) ==
  2793. BTRFS_FILE_EXTENT_INLINE)
  2794. continue;
  2795. bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
  2796. if (bytenr == 0)
  2797. continue;
  2798. num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
  2799. key.offset -= btrfs_file_extent_offset(buf, fi);
  2800. ret = process_func(trans, root, bytenr, num_bytes,
  2801. parent, ref_root, key.objectid,
  2802. key.offset, 1);
  2803. if (ret)
  2804. goto fail;
  2805. } else {
  2806. bytenr = btrfs_node_blockptr(buf, i);
  2807. num_bytes = root->nodesize;
  2808. ret = process_func(trans, root, bytenr, num_bytes,
  2809. parent, ref_root, level - 1, 0,
  2810. 1);
  2811. if (ret)
  2812. goto fail;
  2813. }
  2814. }
  2815. return 0;
  2816. fail:
  2817. return ret;
  2818. }
  2819. int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  2820. struct extent_buffer *buf, int full_backref)
  2821. {
  2822. return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
  2823. }
  2824. int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  2825. struct extent_buffer *buf, int full_backref)
  2826. {
  2827. return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
  2828. }
  2829. static int write_one_cache_group(struct btrfs_trans_handle *trans,
  2830. struct btrfs_root *root,
  2831. struct btrfs_path *path,
  2832. struct btrfs_block_group_cache *cache)
  2833. {
  2834. int ret;
  2835. struct btrfs_root *extent_root = root->fs_info->extent_root;
  2836. unsigned long bi;
  2837. struct extent_buffer *leaf;
  2838. ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
  2839. if (ret) {
  2840. if (ret > 0)
  2841. ret = -ENOENT;
  2842. goto fail;
  2843. }
  2844. leaf = path->nodes[0];
  2845. bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
  2846. write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
  2847. btrfs_mark_buffer_dirty(leaf);
  2848. fail:
  2849. btrfs_release_path(path);
  2850. return ret;
  2851. }
  2852. static struct btrfs_block_group_cache *
  2853. next_block_group(struct btrfs_root *root,
  2854. struct btrfs_block_group_cache *cache)
  2855. {
  2856. struct rb_node *node;
  2857. spin_lock(&root->fs_info->block_group_cache_lock);
  2858. /* If our block group was removed, we need a full search. */
  2859. if (RB_EMPTY_NODE(&cache->cache_node)) {
  2860. const u64 next_bytenr = cache->key.objectid + cache->key.offset;
  2861. spin_unlock(&root->fs_info->block_group_cache_lock);
  2862. btrfs_put_block_group(cache);
  2863. cache = btrfs_lookup_first_block_group(root->fs_info,
  2864. next_bytenr);
  2865. return cache;
  2866. }
  2867. node = rb_next(&cache->cache_node);
  2868. btrfs_put_block_group(cache);
  2869. if (node) {
  2870. cache = rb_entry(node, struct btrfs_block_group_cache,
  2871. cache_node);
  2872. btrfs_get_block_group(cache);
  2873. } else
  2874. cache = NULL;
  2875. spin_unlock(&root->fs_info->block_group_cache_lock);
  2876. return cache;
  2877. }
  2878. static int cache_save_setup(struct btrfs_block_group_cache *block_group,
  2879. struct btrfs_trans_handle *trans,
  2880. struct btrfs_path *path)
  2881. {
  2882. struct btrfs_root *root = block_group->fs_info->tree_root;
  2883. struct inode *inode = NULL;
  2884. u64 alloc_hint = 0;
  2885. int dcs = BTRFS_DC_ERROR;
  2886. u64 num_pages = 0;
  2887. int retries = 0;
  2888. int ret = 0;
  2889. /*
  2890. * If this block group is smaller than 100 megs don't bother caching the
  2891. * block group.
  2892. */
  2893. if (block_group->key.offset < (100 * 1024 * 1024)) {
  2894. spin_lock(&block_group->lock);
  2895. block_group->disk_cache_state = BTRFS_DC_WRITTEN;
  2896. spin_unlock(&block_group->lock);
  2897. return 0;
  2898. }
  2899. if (trans->aborted)
  2900. return 0;
  2901. again:
  2902. inode = lookup_free_space_inode(root, block_group, path);
  2903. if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
  2904. ret = PTR_ERR(inode);
  2905. btrfs_release_path(path);
  2906. goto out;
  2907. }
  2908. if (IS_ERR(inode)) {
  2909. BUG_ON(retries);
  2910. retries++;
  2911. if (block_group->ro)
  2912. goto out_free;
  2913. ret = create_free_space_inode(root, trans, block_group, path);
  2914. if (ret)
  2915. goto out_free;
  2916. goto again;
  2917. }
  2918. /* We've already setup this transaction, go ahead and exit */
  2919. if (block_group->cache_generation == trans->transid &&
  2920. i_size_read(inode)) {
  2921. dcs = BTRFS_DC_SETUP;
  2922. goto out_put;
  2923. }
  2924. /*
  2925. * We want to set the generation to 0, that way if anything goes wrong
  2926. * from here on out we know not to trust this cache when we load up next
  2927. * time.
  2928. */
  2929. BTRFS_I(inode)->generation = 0;
  2930. ret = btrfs_update_inode(trans, root, inode);
  2931. if (ret) {
  2932. /*
  2933. * So theoretically we could recover from this, simply set the
  2934. * super cache generation to 0 so we know to invalidate the
  2935. * cache, but then we'd have to keep track of the block groups
  2936. * that fail this way so we know we _have_ to reset this cache
  2937. * before the next commit or risk reading stale cache. So to
  2938. * limit our exposure to horrible edge cases lets just abort the
  2939. * transaction, this only happens in really bad situations
  2940. * anyway.
  2941. */
  2942. btrfs_abort_transaction(trans, root, ret);
  2943. goto out_put;
  2944. }
  2945. WARN_ON(ret);
  2946. if (i_size_read(inode) > 0) {
  2947. ret = btrfs_check_trunc_cache_free_space(root,
  2948. &root->fs_info->global_block_rsv);
  2949. if (ret)
  2950. goto out_put;
  2951. ret = btrfs_truncate_free_space_cache(root, trans, NULL, inode);
  2952. if (ret)
  2953. goto out_put;
  2954. }
  2955. spin_lock(&block_group->lock);
  2956. if (block_group->cached != BTRFS_CACHE_FINISHED ||
  2957. !btrfs_test_opt(root, SPACE_CACHE)) {
  2958. /*
  2959. * don't bother trying to write stuff out _if_
  2960. * a) we're not cached,
  2961. * b) we're with nospace_cache mount option.
  2962. */
  2963. dcs = BTRFS_DC_WRITTEN;
  2964. spin_unlock(&block_group->lock);
  2965. goto out_put;
  2966. }
  2967. spin_unlock(&block_group->lock);
  2968. /*
  2969. * Try to preallocate enough space based on how big the block group is.
  2970. * Keep in mind this has to include any pinned space which could end up
  2971. * taking up quite a bit since it's not folded into the other space
  2972. * cache.
  2973. */
  2974. num_pages = div_u64(block_group->key.offset, 256 * 1024 * 1024);
  2975. if (!num_pages)
  2976. num_pages = 1;
  2977. num_pages *= 16;
  2978. num_pages *= PAGE_CACHE_SIZE;
  2979. ret = btrfs_check_data_free_space(inode, num_pages, num_pages);
  2980. if (ret)
  2981. goto out_put;
  2982. ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
  2983. num_pages, num_pages,
  2984. &alloc_hint);
  2985. if (!ret)
  2986. dcs = BTRFS_DC_SETUP;
  2987. btrfs_free_reserved_data_space(inode, num_pages);
  2988. out_put:
  2989. iput(inode);
  2990. out_free:
  2991. btrfs_release_path(path);
  2992. out:
  2993. spin_lock(&block_group->lock);
  2994. if (!ret && dcs == BTRFS_DC_SETUP)
  2995. block_group->cache_generation = trans->transid;
  2996. block_group->disk_cache_state = dcs;
  2997. spin_unlock(&block_group->lock);
  2998. return ret;
  2999. }
  3000. int btrfs_setup_space_cache(struct btrfs_trans_handle *trans,
  3001. struct btrfs_root *root)
  3002. {
  3003. struct btrfs_block_group_cache *cache, *tmp;
  3004. struct btrfs_transaction *cur_trans = trans->transaction;
  3005. struct btrfs_path *path;
  3006. if (list_empty(&cur_trans->dirty_bgs) ||
  3007. !btrfs_test_opt(root, SPACE_CACHE))
  3008. return 0;
  3009. path = btrfs_alloc_path();
  3010. if (!path)
  3011. return -ENOMEM;
  3012. /* Could add new block groups, use _safe just in case */
  3013. list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
  3014. dirty_list) {
  3015. if (cache->disk_cache_state == BTRFS_DC_CLEAR)
  3016. cache_save_setup(cache, trans, path);
  3017. }
  3018. btrfs_free_path(path);
  3019. return 0;
  3020. }
  3021. /*
  3022. * transaction commit does final block group cache writeback during a
  3023. * critical section where nothing is allowed to change the FS. This is
  3024. * required in order for the cache to actually match the block group,
  3025. * but can introduce a lot of latency into the commit.
  3026. *
  3027. * So, btrfs_start_dirty_block_groups is here to kick off block group
  3028. * cache IO. There's a chance we'll have to redo some of it if the
  3029. * block group changes again during the commit, but it greatly reduces
  3030. * the commit latency by getting rid of the easy block groups while
  3031. * we're still allowing others to join the commit.
  3032. */
  3033. int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans,
  3034. struct btrfs_root *root)
  3035. {
  3036. struct btrfs_block_group_cache *cache;
  3037. struct btrfs_transaction *cur_trans = trans->transaction;
  3038. int ret = 0;
  3039. int should_put;
  3040. struct btrfs_path *path = NULL;
  3041. LIST_HEAD(dirty);
  3042. struct list_head *io = &cur_trans->io_bgs;
  3043. int num_started = 0;
  3044. int loops = 0;
  3045. spin_lock(&cur_trans->dirty_bgs_lock);
  3046. if (list_empty(&cur_trans->dirty_bgs)) {
  3047. spin_unlock(&cur_trans->dirty_bgs_lock);
  3048. return 0;
  3049. }
  3050. list_splice_init(&cur_trans->dirty_bgs, &dirty);
  3051. spin_unlock(&cur_trans->dirty_bgs_lock);
  3052. again:
  3053. /*
  3054. * make sure all the block groups on our dirty list actually
  3055. * exist
  3056. */
  3057. btrfs_create_pending_block_groups(trans, root);
  3058. if (!path) {
  3059. path = btrfs_alloc_path();
  3060. if (!path)
  3061. return -ENOMEM;
  3062. }
  3063. /*
  3064. * cache_write_mutex is here only to save us from balance or automatic
  3065. * removal of empty block groups deleting this block group while we are
  3066. * writing out the cache
  3067. */
  3068. mutex_lock(&trans->transaction->cache_write_mutex);
  3069. while (!list_empty(&dirty)) {
  3070. cache = list_first_entry(&dirty,
  3071. struct btrfs_block_group_cache,
  3072. dirty_list);
  3073. /*
  3074. * this can happen if something re-dirties a block
  3075. * group that is already under IO. Just wait for it to
  3076. * finish and then do it all again
  3077. */
  3078. if (!list_empty(&cache->io_list)) {
  3079. list_del_init(&cache->io_list);
  3080. btrfs_wait_cache_io(root, trans, cache,
  3081. &cache->io_ctl, path,
  3082. cache->key.objectid);
  3083. btrfs_put_block_group(cache);
  3084. }
  3085. /*
  3086. * btrfs_wait_cache_io uses the cache->dirty_list to decide
  3087. * if it should update the cache_state. Don't delete
  3088. * until after we wait.
  3089. *
  3090. * Since we're not running in the commit critical section
  3091. * we need the dirty_bgs_lock to protect from update_block_group
  3092. */
  3093. spin_lock(&cur_trans->dirty_bgs_lock);
  3094. list_del_init(&cache->dirty_list);
  3095. spin_unlock(&cur_trans->dirty_bgs_lock);
  3096. should_put = 1;
  3097. cache_save_setup(cache, trans, path);
  3098. if (cache->disk_cache_state == BTRFS_DC_SETUP) {
  3099. cache->io_ctl.inode = NULL;
  3100. ret = btrfs_write_out_cache(root, trans, cache, path);
  3101. if (ret == 0 && cache->io_ctl.inode) {
  3102. num_started++;
  3103. should_put = 0;
  3104. /*
  3105. * the cache_write_mutex is protecting
  3106. * the io_list
  3107. */
  3108. list_add_tail(&cache->io_list, io);
  3109. } else {
  3110. /*
  3111. * if we failed to write the cache, the
  3112. * generation will be bad and life goes on
  3113. */
  3114. ret = 0;
  3115. }
  3116. }
  3117. if (!ret) {
  3118. ret = write_one_cache_group(trans, root, path, cache);
  3119. /*
  3120. * Our block group might still be attached to the list
  3121. * of new block groups in the transaction handle of some
  3122. * other task (struct btrfs_trans_handle->new_bgs). This
  3123. * means its block group item isn't yet in the extent
  3124. * tree. If this happens ignore the error, as we will
  3125. * try again later in the critical section of the
  3126. * transaction commit.
  3127. */
  3128. if (ret == -ENOENT) {
  3129. ret = 0;
  3130. spin_lock(&cur_trans->dirty_bgs_lock);
  3131. if (list_empty(&cache->dirty_list)) {
  3132. list_add_tail(&cache->dirty_list,
  3133. &cur_trans->dirty_bgs);
  3134. btrfs_get_block_group(cache);
  3135. }
  3136. spin_unlock(&cur_trans->dirty_bgs_lock);
  3137. } else if (ret) {
  3138. btrfs_abort_transaction(trans, root, ret);
  3139. }
  3140. }
  3141. /* if its not on the io list, we need to put the block group */
  3142. if (should_put)
  3143. btrfs_put_block_group(cache);
  3144. if (ret)
  3145. break;
  3146. /*
  3147. * Avoid blocking other tasks for too long. It might even save
  3148. * us from writing caches for block groups that are going to be
  3149. * removed.
  3150. */
  3151. mutex_unlock(&trans->transaction->cache_write_mutex);
  3152. mutex_lock(&trans->transaction->cache_write_mutex);
  3153. }
  3154. mutex_unlock(&trans->transaction->cache_write_mutex);
  3155. /*
  3156. * go through delayed refs for all the stuff we've just kicked off
  3157. * and then loop back (just once)
  3158. */
  3159. ret = btrfs_run_delayed_refs(trans, root, 0);
  3160. if (!ret && loops == 0) {
  3161. loops++;
  3162. spin_lock(&cur_trans->dirty_bgs_lock);
  3163. list_splice_init(&cur_trans->dirty_bgs, &dirty);
  3164. /*
  3165. * dirty_bgs_lock protects us from concurrent block group
  3166. * deletes too (not just cache_write_mutex).
  3167. */
  3168. if (!list_empty(&dirty)) {
  3169. spin_unlock(&cur_trans->dirty_bgs_lock);
  3170. goto again;
  3171. }
  3172. spin_unlock(&cur_trans->dirty_bgs_lock);
  3173. }
  3174. btrfs_free_path(path);
  3175. return ret;
  3176. }
  3177. int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
  3178. struct btrfs_root *root)
  3179. {
  3180. struct btrfs_block_group_cache *cache;
  3181. struct btrfs_transaction *cur_trans = trans->transaction;
  3182. int ret = 0;
  3183. int should_put;
  3184. struct btrfs_path *path;
  3185. struct list_head *io = &cur_trans->io_bgs;
  3186. int num_started = 0;
  3187. path = btrfs_alloc_path();
  3188. if (!path)
  3189. return -ENOMEM;
  3190. /*
  3191. * We don't need the lock here since we are protected by the transaction
  3192. * commit. We want to do the cache_save_setup first and then run the
  3193. * delayed refs to make sure we have the best chance at doing this all
  3194. * in one shot.
  3195. */
  3196. while (!list_empty(&cur_trans->dirty_bgs)) {
  3197. cache = list_first_entry(&cur_trans->dirty_bgs,
  3198. struct btrfs_block_group_cache,
  3199. dirty_list);
  3200. /*
  3201. * this can happen if cache_save_setup re-dirties a block
  3202. * group that is already under IO. Just wait for it to
  3203. * finish and then do it all again
  3204. */
  3205. if (!list_empty(&cache->io_list)) {
  3206. list_del_init(&cache->io_list);
  3207. btrfs_wait_cache_io(root, trans, cache,
  3208. &cache->io_ctl, path,
  3209. cache->key.objectid);
  3210. btrfs_put_block_group(cache);
  3211. }
  3212. /*
  3213. * don't remove from the dirty list until after we've waited
  3214. * on any pending IO
  3215. */
  3216. list_del_init(&cache->dirty_list);
  3217. should_put = 1;
  3218. cache_save_setup(cache, trans, path);
  3219. if (!ret)
  3220. ret = btrfs_run_delayed_refs(trans, root, (unsigned long) -1);
  3221. if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
  3222. cache->io_ctl.inode = NULL;
  3223. ret = btrfs_write_out_cache(root, trans, cache, path);
  3224. if (ret == 0 && cache->io_ctl.inode) {
  3225. num_started++;
  3226. should_put = 0;
  3227. list_add_tail(&cache->io_list, io);
  3228. } else {
  3229. /*
  3230. * if we failed to write the cache, the
  3231. * generation will be bad and life goes on
  3232. */
  3233. ret = 0;
  3234. }
  3235. }
  3236. if (!ret) {
  3237. ret = write_one_cache_group(trans, root, path, cache);
  3238. if (ret)
  3239. btrfs_abort_transaction(trans, root, ret);
  3240. }
  3241. /* if its not on the io list, we need to put the block group */
  3242. if (should_put)
  3243. btrfs_put_block_group(cache);
  3244. }
  3245. while (!list_empty(io)) {
  3246. cache = list_first_entry(io, struct btrfs_block_group_cache,
  3247. io_list);
  3248. list_del_init(&cache->io_list);
  3249. btrfs_wait_cache_io(root, trans, cache,
  3250. &cache->io_ctl, path, cache->key.objectid);
  3251. btrfs_put_block_group(cache);
  3252. }
  3253. btrfs_free_path(path);
  3254. return ret;
  3255. }
  3256. int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
  3257. {
  3258. struct btrfs_block_group_cache *block_group;
  3259. int readonly = 0;
  3260. block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
  3261. if (!block_group || block_group->ro)
  3262. readonly = 1;
  3263. if (block_group)
  3264. btrfs_put_block_group(block_group);
  3265. return readonly;
  3266. }
  3267. static const char *alloc_name(u64 flags)
  3268. {
  3269. switch (flags) {
  3270. case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
  3271. return "mixed";
  3272. case BTRFS_BLOCK_GROUP_METADATA:
  3273. return "metadata";
  3274. case BTRFS_BLOCK_GROUP_DATA:
  3275. return "data";
  3276. case BTRFS_BLOCK_GROUP_SYSTEM:
  3277. return "system";
  3278. default:
  3279. WARN_ON(1);
  3280. return "invalid-combination";
  3281. };
  3282. }
  3283. static int update_space_info(struct btrfs_fs_info *info, u64 flags,
  3284. u64 total_bytes, u64 bytes_used,
  3285. struct btrfs_space_info **space_info)
  3286. {
  3287. struct btrfs_space_info *found;
  3288. int i;
  3289. int factor;
  3290. int ret;
  3291. if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
  3292. BTRFS_BLOCK_GROUP_RAID10))
  3293. factor = 2;
  3294. else
  3295. factor = 1;
  3296. found = __find_space_info(info, flags);
  3297. if (found) {
  3298. spin_lock(&found->lock);
  3299. found->total_bytes += total_bytes;
  3300. found->disk_total += total_bytes * factor;
  3301. found->bytes_used += bytes_used;
  3302. found->disk_used += bytes_used * factor;
  3303. if (total_bytes > 0)
  3304. found->full = 0;
  3305. spin_unlock(&found->lock);
  3306. *space_info = found;
  3307. return 0;
  3308. }
  3309. found = kzalloc(sizeof(*found), GFP_NOFS);
  3310. if (!found)
  3311. return -ENOMEM;
  3312. ret = percpu_counter_init(&found->total_bytes_pinned, 0, GFP_KERNEL);
  3313. if (ret) {
  3314. kfree(found);
  3315. return ret;
  3316. }
  3317. for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
  3318. INIT_LIST_HEAD(&found->block_groups[i]);
  3319. init_rwsem(&found->groups_sem);
  3320. spin_lock_init(&found->lock);
  3321. found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
  3322. found->total_bytes = total_bytes;
  3323. found->disk_total = total_bytes * factor;
  3324. found->bytes_used = bytes_used;
  3325. found->disk_used = bytes_used * factor;
  3326. found->bytes_pinned = 0;
  3327. found->bytes_reserved = 0;
  3328. found->bytes_readonly = 0;
  3329. found->bytes_may_use = 0;
  3330. found->full = 0;
  3331. found->force_alloc = CHUNK_ALLOC_NO_FORCE;
  3332. found->chunk_alloc = 0;
  3333. found->flush = 0;
  3334. init_waitqueue_head(&found->wait);
  3335. INIT_LIST_HEAD(&found->ro_bgs);
  3336. ret = kobject_init_and_add(&found->kobj, &space_info_ktype,
  3337. info->space_info_kobj, "%s",
  3338. alloc_name(found->flags));
  3339. if (ret) {
  3340. kfree(found);
  3341. return ret;
  3342. }
  3343. *space_info = found;
  3344. list_add_rcu(&found->list, &info->space_info);
  3345. if (flags & BTRFS_BLOCK_GROUP_DATA)
  3346. info->data_sinfo = found;
  3347. return ret;
  3348. }
  3349. static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
  3350. {
  3351. u64 extra_flags = chunk_to_extended(flags) &
  3352. BTRFS_EXTENDED_PROFILE_MASK;
  3353. write_seqlock(&fs_info->profiles_lock);
  3354. if (flags & BTRFS_BLOCK_GROUP_DATA)
  3355. fs_info->avail_data_alloc_bits |= extra_flags;
  3356. if (flags & BTRFS_BLOCK_GROUP_METADATA)
  3357. fs_info->avail_metadata_alloc_bits |= extra_flags;
  3358. if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
  3359. fs_info->avail_system_alloc_bits |= extra_flags;
  3360. write_sequnlock(&fs_info->profiles_lock);
  3361. }
  3362. /*
  3363. * returns target flags in extended format or 0 if restripe for this
  3364. * chunk_type is not in progress
  3365. *
  3366. * should be called with either volume_mutex or balance_lock held
  3367. */
  3368. static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
  3369. {
  3370. struct btrfs_balance_control *bctl = fs_info->balance_ctl;
  3371. u64 target = 0;
  3372. if (!bctl)
  3373. return 0;
  3374. if (flags & BTRFS_BLOCK_GROUP_DATA &&
  3375. bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
  3376. target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
  3377. } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
  3378. bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
  3379. target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
  3380. } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
  3381. bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
  3382. target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
  3383. }
  3384. return target;
  3385. }
  3386. /*
  3387. * @flags: available profiles in extended format (see ctree.h)
  3388. *
  3389. * Returns reduced profile in chunk format. If profile changing is in
  3390. * progress (either running or paused) picks the target profile (if it's
  3391. * already available), otherwise falls back to plain reducing.
  3392. */
  3393. static u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
  3394. {
  3395. u64 num_devices = root->fs_info->fs_devices->rw_devices;
  3396. u64 target;
  3397. u64 tmp;
  3398. /*
  3399. * see if restripe for this chunk_type is in progress, if so
  3400. * try to reduce to the target profile
  3401. */
  3402. spin_lock(&root->fs_info->balance_lock);
  3403. target = get_restripe_target(root->fs_info, flags);
  3404. if (target) {
  3405. /* pick target profile only if it's already available */
  3406. if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
  3407. spin_unlock(&root->fs_info->balance_lock);
  3408. return extended_to_chunk(target);
  3409. }
  3410. }
  3411. spin_unlock(&root->fs_info->balance_lock);
  3412. /* First, mask out the RAID levels which aren't possible */
  3413. if (num_devices == 1)
  3414. flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0 |
  3415. BTRFS_BLOCK_GROUP_RAID5);
  3416. if (num_devices < 3)
  3417. flags &= ~BTRFS_BLOCK_GROUP_RAID6;
  3418. if (num_devices < 4)
  3419. flags &= ~BTRFS_BLOCK_GROUP_RAID10;
  3420. tmp = flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
  3421. BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID5 |
  3422. BTRFS_BLOCK_GROUP_RAID6 | BTRFS_BLOCK_GROUP_RAID10);
  3423. flags &= ~tmp;
  3424. if (tmp & BTRFS_BLOCK_GROUP_RAID6)
  3425. tmp = BTRFS_BLOCK_GROUP_RAID6;
  3426. else if (tmp & BTRFS_BLOCK_GROUP_RAID5)
  3427. tmp = BTRFS_BLOCK_GROUP_RAID5;
  3428. else if (tmp & BTRFS_BLOCK_GROUP_RAID10)
  3429. tmp = BTRFS_BLOCK_GROUP_RAID10;
  3430. else if (tmp & BTRFS_BLOCK_GROUP_RAID1)
  3431. tmp = BTRFS_BLOCK_GROUP_RAID1;
  3432. else if (tmp & BTRFS_BLOCK_GROUP_RAID0)
  3433. tmp = BTRFS_BLOCK_GROUP_RAID0;
  3434. return extended_to_chunk(flags | tmp);
  3435. }
  3436. static u64 get_alloc_profile(struct btrfs_root *root, u64 orig_flags)
  3437. {
  3438. unsigned seq;
  3439. u64 flags;
  3440. do {
  3441. flags = orig_flags;
  3442. seq = read_seqbegin(&root->fs_info->profiles_lock);
  3443. if (flags & BTRFS_BLOCK_GROUP_DATA)
  3444. flags |= root->fs_info->avail_data_alloc_bits;
  3445. else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
  3446. flags |= root->fs_info->avail_system_alloc_bits;
  3447. else if (flags & BTRFS_BLOCK_GROUP_METADATA)
  3448. flags |= root->fs_info->avail_metadata_alloc_bits;
  3449. } while (read_seqretry(&root->fs_info->profiles_lock, seq));
  3450. return btrfs_reduce_alloc_profile(root, flags);
  3451. }
  3452. u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
  3453. {
  3454. u64 flags;
  3455. u64 ret;
  3456. if (data)
  3457. flags = BTRFS_BLOCK_GROUP_DATA;
  3458. else if (root == root->fs_info->chunk_root)
  3459. flags = BTRFS_BLOCK_GROUP_SYSTEM;
  3460. else
  3461. flags = BTRFS_BLOCK_GROUP_METADATA;
  3462. ret = get_alloc_profile(root, flags);
  3463. return ret;
  3464. }
  3465. /*
  3466. * This will check the space that the inode allocates from to make sure we have
  3467. * enough space for bytes.
  3468. */
  3469. int btrfs_check_data_free_space(struct inode *inode, u64 bytes, u64 write_bytes)
  3470. {
  3471. struct btrfs_space_info *data_sinfo;
  3472. struct btrfs_root *root = BTRFS_I(inode)->root;
  3473. struct btrfs_fs_info *fs_info = root->fs_info;
  3474. u64 used;
  3475. int ret = 0;
  3476. int need_commit = 2;
  3477. int have_pinned_space;
  3478. /* make sure bytes are sectorsize aligned */
  3479. bytes = ALIGN(bytes, root->sectorsize);
  3480. if (btrfs_is_free_space_inode(inode)) {
  3481. need_commit = 0;
  3482. ASSERT(current->journal_info);
  3483. }
  3484. data_sinfo = fs_info->data_sinfo;
  3485. if (!data_sinfo)
  3486. goto alloc;
  3487. again:
  3488. /* make sure we have enough space to handle the data first */
  3489. spin_lock(&data_sinfo->lock);
  3490. used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
  3491. data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
  3492. data_sinfo->bytes_may_use;
  3493. if (used + bytes > data_sinfo->total_bytes) {
  3494. struct btrfs_trans_handle *trans;
  3495. /*
  3496. * if we don't have enough free bytes in this space then we need
  3497. * to alloc a new chunk.
  3498. */
  3499. if (!data_sinfo->full) {
  3500. u64 alloc_target;
  3501. data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
  3502. spin_unlock(&data_sinfo->lock);
  3503. alloc:
  3504. alloc_target = btrfs_get_alloc_profile(root, 1);
  3505. /*
  3506. * It is ugly that we don't call nolock join
  3507. * transaction for the free space inode case here.
  3508. * But it is safe because we only do the data space
  3509. * reservation for the free space cache in the
  3510. * transaction context, the common join transaction
  3511. * just increase the counter of the current transaction
  3512. * handler, doesn't try to acquire the trans_lock of
  3513. * the fs.
  3514. */
  3515. trans = btrfs_join_transaction(root);
  3516. if (IS_ERR(trans))
  3517. return PTR_ERR(trans);
  3518. ret = do_chunk_alloc(trans, root->fs_info->extent_root,
  3519. alloc_target,
  3520. CHUNK_ALLOC_NO_FORCE);
  3521. btrfs_end_transaction(trans, root);
  3522. if (ret < 0) {
  3523. if (ret != -ENOSPC)
  3524. return ret;
  3525. else {
  3526. have_pinned_space = 1;
  3527. goto commit_trans;
  3528. }
  3529. }
  3530. if (!data_sinfo)
  3531. data_sinfo = fs_info->data_sinfo;
  3532. goto again;
  3533. }
  3534. /*
  3535. * If we don't have enough pinned space to deal with this
  3536. * allocation, and no removed chunk in current transaction,
  3537. * don't bother committing the transaction.
  3538. */
  3539. have_pinned_space = percpu_counter_compare(
  3540. &data_sinfo->total_bytes_pinned,
  3541. used + bytes - data_sinfo->total_bytes);
  3542. spin_unlock(&data_sinfo->lock);
  3543. /* commit the current transaction and try again */
  3544. commit_trans:
  3545. if (need_commit &&
  3546. !atomic_read(&root->fs_info->open_ioctl_trans)) {
  3547. need_commit--;
  3548. if (need_commit > 0)
  3549. btrfs_wait_ordered_roots(fs_info, -1);
  3550. trans = btrfs_join_transaction(root);
  3551. if (IS_ERR(trans))
  3552. return PTR_ERR(trans);
  3553. if (have_pinned_space >= 0 ||
  3554. trans->transaction->have_free_bgs ||
  3555. need_commit > 0) {
  3556. ret = btrfs_commit_transaction(trans, root);
  3557. if (ret)
  3558. return ret;
  3559. /*
  3560. * make sure that all running delayed iput are
  3561. * done
  3562. */
  3563. down_write(&root->fs_info->delayed_iput_sem);
  3564. up_write(&root->fs_info->delayed_iput_sem);
  3565. goto again;
  3566. } else {
  3567. btrfs_end_transaction(trans, root);
  3568. }
  3569. }
  3570. trace_btrfs_space_reservation(root->fs_info,
  3571. "space_info:enospc",
  3572. data_sinfo->flags, bytes, 1);
  3573. return -ENOSPC;
  3574. }
  3575. ret = btrfs_qgroup_reserve(root, write_bytes);
  3576. if (ret)
  3577. goto out;
  3578. data_sinfo->bytes_may_use += bytes;
  3579. trace_btrfs_space_reservation(root->fs_info, "space_info",
  3580. data_sinfo->flags, bytes, 1);
  3581. out:
  3582. spin_unlock(&data_sinfo->lock);
  3583. return ret;
  3584. }
  3585. /*
  3586. * Called if we need to clear a data reservation for this inode.
  3587. */
  3588. void btrfs_free_reserved_data_space(struct inode *inode, u64 bytes)
  3589. {
  3590. struct btrfs_root *root = BTRFS_I(inode)->root;
  3591. struct btrfs_space_info *data_sinfo;
  3592. /* make sure bytes are sectorsize aligned */
  3593. bytes = ALIGN(bytes, root->sectorsize);
  3594. data_sinfo = root->fs_info->data_sinfo;
  3595. spin_lock(&data_sinfo->lock);
  3596. WARN_ON(data_sinfo->bytes_may_use < bytes);
  3597. data_sinfo->bytes_may_use -= bytes;
  3598. trace_btrfs_space_reservation(root->fs_info, "space_info",
  3599. data_sinfo->flags, bytes, 0);
  3600. spin_unlock(&data_sinfo->lock);
  3601. }
  3602. static void force_metadata_allocation(struct btrfs_fs_info *info)
  3603. {
  3604. struct list_head *head = &info->space_info;
  3605. struct btrfs_space_info *found;
  3606. rcu_read_lock();
  3607. list_for_each_entry_rcu(found, head, list) {
  3608. if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
  3609. found->force_alloc = CHUNK_ALLOC_FORCE;
  3610. }
  3611. rcu_read_unlock();
  3612. }
  3613. static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
  3614. {
  3615. return (global->size << 1);
  3616. }
  3617. static int should_alloc_chunk(struct btrfs_root *root,
  3618. struct btrfs_space_info *sinfo, int force)
  3619. {
  3620. struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
  3621. u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
  3622. u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
  3623. u64 thresh;
  3624. if (force == CHUNK_ALLOC_FORCE)
  3625. return 1;
  3626. /*
  3627. * We need to take into account the global rsv because for all intents
  3628. * and purposes it's used space. Don't worry about locking the
  3629. * global_rsv, it doesn't change except when the transaction commits.
  3630. */
  3631. if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
  3632. num_allocated += calc_global_rsv_need_space(global_rsv);
  3633. /*
  3634. * in limited mode, we want to have some free space up to
  3635. * about 1% of the FS size.
  3636. */
  3637. if (force == CHUNK_ALLOC_LIMITED) {
  3638. thresh = btrfs_super_total_bytes(root->fs_info->super_copy);
  3639. thresh = max_t(u64, 64 * 1024 * 1024,
  3640. div_factor_fine(thresh, 1));
  3641. if (num_bytes - num_allocated < thresh)
  3642. return 1;
  3643. }
  3644. if (num_allocated + 2 * 1024 * 1024 < div_factor(num_bytes, 8))
  3645. return 0;
  3646. return 1;
  3647. }
  3648. static u64 get_profile_num_devs(struct btrfs_root *root, u64 type)
  3649. {
  3650. u64 num_dev;
  3651. if (type & (BTRFS_BLOCK_GROUP_RAID10 |
  3652. BTRFS_BLOCK_GROUP_RAID0 |
  3653. BTRFS_BLOCK_GROUP_RAID5 |
  3654. BTRFS_BLOCK_GROUP_RAID6))
  3655. num_dev = root->fs_info->fs_devices->rw_devices;
  3656. else if (type & BTRFS_BLOCK_GROUP_RAID1)
  3657. num_dev = 2;
  3658. else
  3659. num_dev = 1; /* DUP or single */
  3660. return num_dev;
  3661. }
  3662. /*
  3663. * If @is_allocation is true, reserve space in the system space info necessary
  3664. * for allocating a chunk, otherwise if it's false, reserve space necessary for
  3665. * removing a chunk.
  3666. */
  3667. void check_system_chunk(struct btrfs_trans_handle *trans,
  3668. struct btrfs_root *root,
  3669. u64 type)
  3670. {
  3671. struct btrfs_space_info *info;
  3672. u64 left;
  3673. u64 thresh;
  3674. int ret = 0;
  3675. u64 num_devs;
  3676. /*
  3677. * Needed because we can end up allocating a system chunk and for an
  3678. * atomic and race free space reservation in the chunk block reserve.
  3679. */
  3680. ASSERT(mutex_is_locked(&root->fs_info->chunk_mutex));
  3681. info = __find_space_info(root->fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
  3682. spin_lock(&info->lock);
  3683. left = info->total_bytes - info->bytes_used - info->bytes_pinned -
  3684. info->bytes_reserved - info->bytes_readonly -
  3685. info->bytes_may_use;
  3686. spin_unlock(&info->lock);
  3687. num_devs = get_profile_num_devs(root, type);
  3688. /* num_devs device items to update and 1 chunk item to add or remove */
  3689. thresh = btrfs_calc_trunc_metadata_size(root, num_devs) +
  3690. btrfs_calc_trans_metadata_size(root, 1);
  3691. if (left < thresh && btrfs_test_opt(root, ENOSPC_DEBUG)) {
  3692. btrfs_info(root->fs_info, "left=%llu, need=%llu, flags=%llu",
  3693. left, thresh, type);
  3694. dump_space_info(info, 0, 0);
  3695. }
  3696. if (left < thresh) {
  3697. u64 flags;
  3698. flags = btrfs_get_alloc_profile(root->fs_info->chunk_root, 0);
  3699. /*
  3700. * Ignore failure to create system chunk. We might end up not
  3701. * needing it, as we might not need to COW all nodes/leafs from
  3702. * the paths we visit in the chunk tree (they were already COWed
  3703. * or created in the current transaction for example).
  3704. */
  3705. ret = btrfs_alloc_chunk(trans, root, flags);
  3706. }
  3707. if (!ret) {
  3708. ret = btrfs_block_rsv_add(root->fs_info->chunk_root,
  3709. &root->fs_info->chunk_block_rsv,
  3710. thresh, BTRFS_RESERVE_NO_FLUSH);
  3711. if (!ret)
  3712. trans->chunk_bytes_reserved += thresh;
  3713. }
  3714. }
  3715. static int do_chunk_alloc(struct btrfs_trans_handle *trans,
  3716. struct btrfs_root *extent_root, u64 flags, int force)
  3717. {
  3718. struct btrfs_space_info *space_info;
  3719. struct btrfs_fs_info *fs_info = extent_root->fs_info;
  3720. int wait_for_alloc = 0;
  3721. int ret = 0;
  3722. /* Don't re-enter if we're already allocating a chunk */
  3723. if (trans->allocating_chunk)
  3724. return -ENOSPC;
  3725. space_info = __find_space_info(extent_root->fs_info, flags);
  3726. if (!space_info) {
  3727. ret = update_space_info(extent_root->fs_info, flags,
  3728. 0, 0, &space_info);
  3729. BUG_ON(ret); /* -ENOMEM */
  3730. }
  3731. BUG_ON(!space_info); /* Logic error */
  3732. again:
  3733. spin_lock(&space_info->lock);
  3734. if (force < space_info->force_alloc)
  3735. force = space_info->force_alloc;
  3736. if (space_info->full) {
  3737. if (should_alloc_chunk(extent_root, space_info, force))
  3738. ret = -ENOSPC;
  3739. else
  3740. ret = 0;
  3741. spin_unlock(&space_info->lock);
  3742. return ret;
  3743. }
  3744. if (!should_alloc_chunk(extent_root, space_info, force)) {
  3745. spin_unlock(&space_info->lock);
  3746. return 0;
  3747. } else if (space_info->chunk_alloc) {
  3748. wait_for_alloc = 1;
  3749. } else {
  3750. space_info->chunk_alloc = 1;
  3751. }
  3752. spin_unlock(&space_info->lock);
  3753. mutex_lock(&fs_info->chunk_mutex);
  3754. /*
  3755. * The chunk_mutex is held throughout the entirety of a chunk
  3756. * allocation, so once we've acquired the chunk_mutex we know that the
  3757. * other guy is done and we need to recheck and see if we should
  3758. * allocate.
  3759. */
  3760. if (wait_for_alloc) {
  3761. mutex_unlock(&fs_info->chunk_mutex);
  3762. wait_for_alloc = 0;
  3763. goto again;
  3764. }
  3765. trans->allocating_chunk = true;
  3766. /*
  3767. * If we have mixed data/metadata chunks we want to make sure we keep
  3768. * allocating mixed chunks instead of individual chunks.
  3769. */
  3770. if (btrfs_mixed_space_info(space_info))
  3771. flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
  3772. /*
  3773. * if we're doing a data chunk, go ahead and make sure that
  3774. * we keep a reasonable number of metadata chunks allocated in the
  3775. * FS as well.
  3776. */
  3777. if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
  3778. fs_info->data_chunk_allocations++;
  3779. if (!(fs_info->data_chunk_allocations %
  3780. fs_info->metadata_ratio))
  3781. force_metadata_allocation(fs_info);
  3782. }
  3783. /*
  3784. * Check if we have enough space in SYSTEM chunk because we may need
  3785. * to update devices.
  3786. */
  3787. check_system_chunk(trans, extent_root, flags);
  3788. ret = btrfs_alloc_chunk(trans, extent_root, flags);
  3789. trans->allocating_chunk = false;
  3790. spin_lock(&space_info->lock);
  3791. if (ret < 0 && ret != -ENOSPC)
  3792. goto out;
  3793. if (ret)
  3794. space_info->full = 1;
  3795. else
  3796. ret = 1;
  3797. space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
  3798. out:
  3799. space_info->chunk_alloc = 0;
  3800. spin_unlock(&space_info->lock);
  3801. mutex_unlock(&fs_info->chunk_mutex);
  3802. /*
  3803. * When we allocate a new chunk we reserve space in the chunk block
  3804. * reserve to make sure we can COW nodes/leafs in the chunk tree or
  3805. * add new nodes/leafs to it if we end up needing to do it when
  3806. * inserting the chunk item and updating device items as part of the
  3807. * second phase of chunk allocation, performed by
  3808. * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
  3809. * large number of new block groups to create in our transaction
  3810. * handle's new_bgs list to avoid exhausting the chunk block reserve
  3811. * in extreme cases - like having a single transaction create many new
  3812. * block groups when starting to write out the free space caches of all
  3813. * the block groups that were made dirty during the lifetime of the
  3814. * transaction.
  3815. */
  3816. if (trans->can_flush_pending_bgs &&
  3817. 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(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 tree buffer or an ERR_PTR on error.
  6747. */
  6748. struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
  6749. struct btrfs_root *root,
  6750. u64 parent, u64 root_objectid,
  6751. struct btrfs_disk_key *key, int level,
  6752. u64 hint, u64 empty_size)
  6753. {
  6754. struct btrfs_key ins;
  6755. struct btrfs_block_rsv *block_rsv;
  6756. struct extent_buffer *buf;
  6757. struct btrfs_delayed_extent_op *extent_op;
  6758. u64 flags = 0;
  6759. int ret;
  6760. u32 blocksize = root->nodesize;
  6761. bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
  6762. SKINNY_METADATA);
  6763. if (btrfs_test_is_dummy_root(root)) {
  6764. buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
  6765. level);
  6766. if (!IS_ERR(buf))
  6767. root->alloc_bytenr += blocksize;
  6768. return buf;
  6769. }
  6770. block_rsv = use_block_rsv(trans, root, blocksize);
  6771. if (IS_ERR(block_rsv))
  6772. return ERR_CAST(block_rsv);
  6773. ret = btrfs_reserve_extent(root, blocksize, blocksize,
  6774. empty_size, hint, &ins, 0, 0);
  6775. if (ret)
  6776. goto out_unuse;
  6777. buf = btrfs_init_new_buffer(trans, root, ins.objectid, level);
  6778. if (IS_ERR(buf)) {
  6779. ret = PTR_ERR(buf);
  6780. goto out_free_reserved;
  6781. }
  6782. if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
  6783. if (parent == 0)
  6784. parent = ins.objectid;
  6785. flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
  6786. } else
  6787. BUG_ON(parent > 0);
  6788. if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
  6789. extent_op = btrfs_alloc_delayed_extent_op();
  6790. if (!extent_op) {
  6791. ret = -ENOMEM;
  6792. goto out_free_buf;
  6793. }
  6794. if (key)
  6795. memcpy(&extent_op->key, key, sizeof(extent_op->key));
  6796. else
  6797. memset(&extent_op->key, 0, sizeof(extent_op->key));
  6798. extent_op->flags_to_set = flags;
  6799. if (skinny_metadata)
  6800. extent_op->update_key = 0;
  6801. else
  6802. extent_op->update_key = 1;
  6803. extent_op->update_flags = 1;
  6804. extent_op->is_data = 0;
  6805. extent_op->level = level;
  6806. ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
  6807. ins.objectid, ins.offset,
  6808. parent, root_objectid, level,
  6809. BTRFS_ADD_DELAYED_EXTENT,
  6810. extent_op, 0);
  6811. if (ret)
  6812. goto out_free_delayed;
  6813. }
  6814. return buf;
  6815. out_free_delayed:
  6816. btrfs_free_delayed_extent_op(extent_op);
  6817. out_free_buf:
  6818. free_extent_buffer(buf);
  6819. out_free_reserved:
  6820. btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 0);
  6821. out_unuse:
  6822. unuse_block_rsv(root->fs_info, block_rsv, blocksize);
  6823. return ERR_PTR(ret);
  6824. }
  6825. struct walk_control {
  6826. u64 refs[BTRFS_MAX_LEVEL];
  6827. u64 flags[BTRFS_MAX_LEVEL];
  6828. struct btrfs_key update_progress;
  6829. int stage;
  6830. int level;
  6831. int shared_level;
  6832. int update_ref;
  6833. int keep_locks;
  6834. int reada_slot;
  6835. int reada_count;
  6836. int for_reloc;
  6837. };
  6838. #define DROP_REFERENCE 1
  6839. #define UPDATE_BACKREF 2
  6840. static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
  6841. struct btrfs_root *root,
  6842. struct walk_control *wc,
  6843. struct btrfs_path *path)
  6844. {
  6845. u64 bytenr;
  6846. u64 generation;
  6847. u64 refs;
  6848. u64 flags;
  6849. u32 nritems;
  6850. u32 blocksize;
  6851. struct btrfs_key key;
  6852. struct extent_buffer *eb;
  6853. int ret;
  6854. int slot;
  6855. int nread = 0;
  6856. if (path->slots[wc->level] < wc->reada_slot) {
  6857. wc->reada_count = wc->reada_count * 2 / 3;
  6858. wc->reada_count = max(wc->reada_count, 2);
  6859. } else {
  6860. wc->reada_count = wc->reada_count * 3 / 2;
  6861. wc->reada_count = min_t(int, wc->reada_count,
  6862. BTRFS_NODEPTRS_PER_BLOCK(root));
  6863. }
  6864. eb = path->nodes[wc->level];
  6865. nritems = btrfs_header_nritems(eb);
  6866. blocksize = root->nodesize;
  6867. for (slot = path->slots[wc->level]; slot < nritems; slot++) {
  6868. if (nread >= wc->reada_count)
  6869. break;
  6870. cond_resched();
  6871. bytenr = btrfs_node_blockptr(eb, slot);
  6872. generation = btrfs_node_ptr_generation(eb, slot);
  6873. if (slot == path->slots[wc->level])
  6874. goto reada;
  6875. if (wc->stage == UPDATE_BACKREF &&
  6876. generation <= root->root_key.offset)
  6877. continue;
  6878. /* We don't lock the tree block, it's OK to be racy here */
  6879. ret = btrfs_lookup_extent_info(trans, root, bytenr,
  6880. wc->level - 1, 1, &refs,
  6881. &flags);
  6882. /* We don't care about errors in readahead. */
  6883. if (ret < 0)
  6884. continue;
  6885. BUG_ON(refs == 0);
  6886. if (wc->stage == DROP_REFERENCE) {
  6887. if (refs == 1)
  6888. goto reada;
  6889. if (wc->level == 1 &&
  6890. (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  6891. continue;
  6892. if (!wc->update_ref ||
  6893. generation <= root->root_key.offset)
  6894. continue;
  6895. btrfs_node_key_to_cpu(eb, &key, slot);
  6896. ret = btrfs_comp_cpu_keys(&key,
  6897. &wc->update_progress);
  6898. if (ret < 0)
  6899. continue;
  6900. } else {
  6901. if (wc->level == 1 &&
  6902. (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  6903. continue;
  6904. }
  6905. reada:
  6906. readahead_tree_block(root, bytenr);
  6907. nread++;
  6908. }
  6909. wc->reada_slot = slot;
  6910. }
  6911. /*
  6912. * TODO: Modify related function to add related node/leaf to dirty_extent_root,
  6913. * for later qgroup accounting.
  6914. *
  6915. * Current, this function does nothing.
  6916. */
  6917. static int account_leaf_items(struct btrfs_trans_handle *trans,
  6918. struct btrfs_root *root,
  6919. struct extent_buffer *eb)
  6920. {
  6921. int nr = btrfs_header_nritems(eb);
  6922. int i, extent_type;
  6923. struct btrfs_key key;
  6924. struct btrfs_file_extent_item *fi;
  6925. u64 bytenr, num_bytes;
  6926. for (i = 0; i < nr; i++) {
  6927. btrfs_item_key_to_cpu(eb, &key, i);
  6928. if (key.type != BTRFS_EXTENT_DATA_KEY)
  6929. continue;
  6930. fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
  6931. /* filter out non qgroup-accountable extents */
  6932. extent_type = btrfs_file_extent_type(eb, fi);
  6933. if (extent_type == BTRFS_FILE_EXTENT_INLINE)
  6934. continue;
  6935. bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
  6936. if (!bytenr)
  6937. continue;
  6938. num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
  6939. }
  6940. return 0;
  6941. }
  6942. /*
  6943. * Walk up the tree from the bottom, freeing leaves and any interior
  6944. * nodes which have had all slots visited. If a node (leaf or
  6945. * interior) is freed, the node above it will have it's slot
  6946. * incremented. The root node will never be freed.
  6947. *
  6948. * At the end of this function, we should have a path which has all
  6949. * slots incremented to the next position for a search. If we need to
  6950. * read a new node it will be NULL and the node above it will have the
  6951. * correct slot selected for a later read.
  6952. *
  6953. * If we increment the root nodes slot counter past the number of
  6954. * elements, 1 is returned to signal completion of the search.
  6955. */
  6956. static int adjust_slots_upwards(struct btrfs_root *root,
  6957. struct btrfs_path *path, int root_level)
  6958. {
  6959. int level = 0;
  6960. int nr, slot;
  6961. struct extent_buffer *eb;
  6962. if (root_level == 0)
  6963. return 1;
  6964. while (level <= root_level) {
  6965. eb = path->nodes[level];
  6966. nr = btrfs_header_nritems(eb);
  6967. path->slots[level]++;
  6968. slot = path->slots[level];
  6969. if (slot >= nr || level == 0) {
  6970. /*
  6971. * Don't free the root - we will detect this
  6972. * condition after our loop and return a
  6973. * positive value for caller to stop walking the tree.
  6974. */
  6975. if (level != root_level) {
  6976. btrfs_tree_unlock_rw(eb, path->locks[level]);
  6977. path->locks[level] = 0;
  6978. free_extent_buffer(eb);
  6979. path->nodes[level] = NULL;
  6980. path->slots[level] = 0;
  6981. }
  6982. } else {
  6983. /*
  6984. * We have a valid slot to walk back down
  6985. * from. Stop here so caller can process these
  6986. * new nodes.
  6987. */
  6988. break;
  6989. }
  6990. level++;
  6991. }
  6992. eb = path->nodes[root_level];
  6993. if (path->slots[root_level] >= btrfs_header_nritems(eb))
  6994. return 1;
  6995. return 0;
  6996. }
  6997. /*
  6998. * root_eb is the subtree root and is locked before this function is called.
  6999. * TODO: Modify this function to mark all (including complete shared node)
  7000. * to dirty_extent_root to allow it get accounted in qgroup.
  7001. */
  7002. static int account_shared_subtree(struct btrfs_trans_handle *trans,
  7003. struct btrfs_root *root,
  7004. struct extent_buffer *root_eb,
  7005. u64 root_gen,
  7006. int root_level)
  7007. {
  7008. int ret = 0;
  7009. int level;
  7010. struct extent_buffer *eb = root_eb;
  7011. struct btrfs_path *path = NULL;
  7012. BUG_ON(root_level < 0 || root_level > BTRFS_MAX_LEVEL);
  7013. BUG_ON(root_eb == NULL);
  7014. if (!root->fs_info->quota_enabled)
  7015. return 0;
  7016. if (!extent_buffer_uptodate(root_eb)) {
  7017. ret = btrfs_read_buffer(root_eb, root_gen);
  7018. if (ret)
  7019. goto out;
  7020. }
  7021. if (root_level == 0) {
  7022. ret = account_leaf_items(trans, root, root_eb);
  7023. goto out;
  7024. }
  7025. path = btrfs_alloc_path();
  7026. if (!path)
  7027. return -ENOMEM;
  7028. /*
  7029. * Walk down the tree. Missing extent blocks are filled in as
  7030. * we go. Metadata is accounted every time we read a new
  7031. * extent block.
  7032. *
  7033. * When we reach a leaf, we account for file extent items in it,
  7034. * walk back up the tree (adjusting slot pointers as we go)
  7035. * and restart the search process.
  7036. */
  7037. extent_buffer_get(root_eb); /* For path */
  7038. path->nodes[root_level] = root_eb;
  7039. path->slots[root_level] = 0;
  7040. path->locks[root_level] = 0; /* so release_path doesn't try to unlock */
  7041. walk_down:
  7042. level = root_level;
  7043. while (level >= 0) {
  7044. if (path->nodes[level] == NULL) {
  7045. int parent_slot;
  7046. u64 child_gen;
  7047. u64 child_bytenr;
  7048. /* We need to get child blockptr/gen from
  7049. * parent before we can read it. */
  7050. eb = path->nodes[level + 1];
  7051. parent_slot = path->slots[level + 1];
  7052. child_bytenr = btrfs_node_blockptr(eb, parent_slot);
  7053. child_gen = btrfs_node_ptr_generation(eb, parent_slot);
  7054. eb = read_tree_block(root, child_bytenr, child_gen);
  7055. if (IS_ERR(eb)) {
  7056. ret = PTR_ERR(eb);
  7057. goto out;
  7058. } else if (!extent_buffer_uptodate(eb)) {
  7059. free_extent_buffer(eb);
  7060. ret = -EIO;
  7061. goto out;
  7062. }
  7063. path->nodes[level] = eb;
  7064. path->slots[level] = 0;
  7065. btrfs_tree_read_lock(eb);
  7066. btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
  7067. path->locks[level] = BTRFS_READ_LOCK_BLOCKING;
  7068. }
  7069. if (level == 0) {
  7070. ret = account_leaf_items(trans, root, path->nodes[level]);
  7071. if (ret)
  7072. goto out;
  7073. /* Nonzero return here means we completed our search */
  7074. ret = adjust_slots_upwards(root, path, root_level);
  7075. if (ret)
  7076. break;
  7077. /* Restart search with new slots */
  7078. goto walk_down;
  7079. }
  7080. level--;
  7081. }
  7082. ret = 0;
  7083. out:
  7084. btrfs_free_path(path);
  7085. return ret;
  7086. }
  7087. /*
  7088. * helper to process tree block while walking down the tree.
  7089. *
  7090. * when wc->stage == UPDATE_BACKREF, this function updates
  7091. * back refs for pointers in the block.
  7092. *
  7093. * NOTE: return value 1 means we should stop walking down.
  7094. */
  7095. static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
  7096. struct btrfs_root *root,
  7097. struct btrfs_path *path,
  7098. struct walk_control *wc, int lookup_info)
  7099. {
  7100. int level = wc->level;
  7101. struct extent_buffer *eb = path->nodes[level];
  7102. u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  7103. int ret;
  7104. if (wc->stage == UPDATE_BACKREF &&
  7105. btrfs_header_owner(eb) != root->root_key.objectid)
  7106. return 1;
  7107. /*
  7108. * when reference count of tree block is 1, it won't increase
  7109. * again. once full backref flag is set, we never clear it.
  7110. */
  7111. if (lookup_info &&
  7112. ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
  7113. (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
  7114. BUG_ON(!path->locks[level]);
  7115. ret = btrfs_lookup_extent_info(trans, root,
  7116. eb->start, level, 1,
  7117. &wc->refs[level],
  7118. &wc->flags[level]);
  7119. BUG_ON(ret == -ENOMEM);
  7120. if (ret)
  7121. return ret;
  7122. BUG_ON(wc->refs[level] == 0);
  7123. }
  7124. if (wc->stage == DROP_REFERENCE) {
  7125. if (wc->refs[level] > 1)
  7126. return 1;
  7127. if (path->locks[level] && !wc->keep_locks) {
  7128. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7129. path->locks[level] = 0;
  7130. }
  7131. return 0;
  7132. }
  7133. /* wc->stage == UPDATE_BACKREF */
  7134. if (!(wc->flags[level] & flag)) {
  7135. BUG_ON(!path->locks[level]);
  7136. ret = btrfs_inc_ref(trans, root, eb, 1);
  7137. BUG_ON(ret); /* -ENOMEM */
  7138. ret = btrfs_dec_ref(trans, root, eb, 0);
  7139. BUG_ON(ret); /* -ENOMEM */
  7140. ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
  7141. eb->len, flag,
  7142. btrfs_header_level(eb), 0);
  7143. BUG_ON(ret); /* -ENOMEM */
  7144. wc->flags[level] |= flag;
  7145. }
  7146. /*
  7147. * the block is shared by multiple trees, so it's not good to
  7148. * keep the tree lock
  7149. */
  7150. if (path->locks[level] && level > 0) {
  7151. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7152. path->locks[level] = 0;
  7153. }
  7154. return 0;
  7155. }
  7156. /*
  7157. * helper to process tree block pointer.
  7158. *
  7159. * when wc->stage == DROP_REFERENCE, this function checks
  7160. * reference count of the block pointed to. if the block
  7161. * is shared and we need update back refs for the subtree
  7162. * rooted at the block, this function changes wc->stage to
  7163. * UPDATE_BACKREF. if the block is shared and there is no
  7164. * need to update back, this function drops the reference
  7165. * to the block.
  7166. *
  7167. * NOTE: return value 1 means we should stop walking down.
  7168. */
  7169. static noinline int do_walk_down(struct btrfs_trans_handle *trans,
  7170. struct btrfs_root *root,
  7171. struct btrfs_path *path,
  7172. struct walk_control *wc, int *lookup_info)
  7173. {
  7174. u64 bytenr;
  7175. u64 generation;
  7176. u64 parent;
  7177. u32 blocksize;
  7178. struct btrfs_key key;
  7179. struct extent_buffer *next;
  7180. int level = wc->level;
  7181. int reada = 0;
  7182. int ret = 0;
  7183. bool need_account = false;
  7184. generation = btrfs_node_ptr_generation(path->nodes[level],
  7185. path->slots[level]);
  7186. /*
  7187. * if the lower level block was created before the snapshot
  7188. * was created, we know there is no need to update back refs
  7189. * for the subtree
  7190. */
  7191. if (wc->stage == UPDATE_BACKREF &&
  7192. generation <= root->root_key.offset) {
  7193. *lookup_info = 1;
  7194. return 1;
  7195. }
  7196. bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
  7197. blocksize = root->nodesize;
  7198. next = btrfs_find_tree_block(root->fs_info, bytenr);
  7199. if (!next) {
  7200. next = btrfs_find_create_tree_block(root, bytenr);
  7201. if (!next)
  7202. return -ENOMEM;
  7203. btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
  7204. level - 1);
  7205. reada = 1;
  7206. }
  7207. btrfs_tree_lock(next);
  7208. btrfs_set_lock_blocking(next);
  7209. ret = btrfs_lookup_extent_info(trans, root, bytenr, level - 1, 1,
  7210. &wc->refs[level - 1],
  7211. &wc->flags[level - 1]);
  7212. if (ret < 0) {
  7213. btrfs_tree_unlock(next);
  7214. return ret;
  7215. }
  7216. if (unlikely(wc->refs[level - 1] == 0)) {
  7217. btrfs_err(root->fs_info, "Missing references.");
  7218. BUG();
  7219. }
  7220. *lookup_info = 0;
  7221. if (wc->stage == DROP_REFERENCE) {
  7222. if (wc->refs[level - 1] > 1) {
  7223. need_account = true;
  7224. if (level == 1 &&
  7225. (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7226. goto skip;
  7227. if (!wc->update_ref ||
  7228. generation <= root->root_key.offset)
  7229. goto skip;
  7230. btrfs_node_key_to_cpu(path->nodes[level], &key,
  7231. path->slots[level]);
  7232. ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
  7233. if (ret < 0)
  7234. goto skip;
  7235. wc->stage = UPDATE_BACKREF;
  7236. wc->shared_level = level - 1;
  7237. }
  7238. } else {
  7239. if (level == 1 &&
  7240. (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7241. goto skip;
  7242. }
  7243. if (!btrfs_buffer_uptodate(next, generation, 0)) {
  7244. btrfs_tree_unlock(next);
  7245. free_extent_buffer(next);
  7246. next = NULL;
  7247. *lookup_info = 1;
  7248. }
  7249. if (!next) {
  7250. if (reada && level == 1)
  7251. reada_walk_down(trans, root, wc, path);
  7252. next = read_tree_block(root, bytenr, generation);
  7253. if (IS_ERR(next)) {
  7254. return PTR_ERR(next);
  7255. } else if (!extent_buffer_uptodate(next)) {
  7256. free_extent_buffer(next);
  7257. return -EIO;
  7258. }
  7259. btrfs_tree_lock(next);
  7260. btrfs_set_lock_blocking(next);
  7261. }
  7262. level--;
  7263. BUG_ON(level != btrfs_header_level(next));
  7264. path->nodes[level] = next;
  7265. path->slots[level] = 0;
  7266. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7267. wc->level = level;
  7268. if (wc->level == 1)
  7269. wc->reada_slot = 0;
  7270. return 0;
  7271. skip:
  7272. wc->refs[level - 1] = 0;
  7273. wc->flags[level - 1] = 0;
  7274. if (wc->stage == DROP_REFERENCE) {
  7275. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
  7276. parent = path->nodes[level]->start;
  7277. } else {
  7278. BUG_ON(root->root_key.objectid !=
  7279. btrfs_header_owner(path->nodes[level]));
  7280. parent = 0;
  7281. }
  7282. if (need_account) {
  7283. ret = account_shared_subtree(trans, root, next,
  7284. generation, level - 1);
  7285. if (ret) {
  7286. printk_ratelimited(KERN_ERR "BTRFS: %s Error "
  7287. "%d accounting shared subtree. Quota "
  7288. "is out of sync, rescan required.\n",
  7289. root->fs_info->sb->s_id, ret);
  7290. }
  7291. }
  7292. ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
  7293. root->root_key.objectid, level - 1, 0, 0);
  7294. BUG_ON(ret); /* -ENOMEM */
  7295. }
  7296. btrfs_tree_unlock(next);
  7297. free_extent_buffer(next);
  7298. *lookup_info = 1;
  7299. return 1;
  7300. }
  7301. /*
  7302. * helper to process tree block while walking up the tree.
  7303. *
  7304. * when wc->stage == DROP_REFERENCE, this function drops
  7305. * reference count on the block.
  7306. *
  7307. * when wc->stage == UPDATE_BACKREF, this function changes
  7308. * wc->stage back to DROP_REFERENCE if we changed wc->stage
  7309. * to UPDATE_BACKREF previously while processing the block.
  7310. *
  7311. * NOTE: return value 1 means we should stop walking up.
  7312. */
  7313. static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
  7314. struct btrfs_root *root,
  7315. struct btrfs_path *path,
  7316. struct walk_control *wc)
  7317. {
  7318. int ret;
  7319. int level = wc->level;
  7320. struct extent_buffer *eb = path->nodes[level];
  7321. u64 parent = 0;
  7322. if (wc->stage == UPDATE_BACKREF) {
  7323. BUG_ON(wc->shared_level < level);
  7324. if (level < wc->shared_level)
  7325. goto out;
  7326. ret = find_next_key(path, level + 1, &wc->update_progress);
  7327. if (ret > 0)
  7328. wc->update_ref = 0;
  7329. wc->stage = DROP_REFERENCE;
  7330. wc->shared_level = -1;
  7331. path->slots[level] = 0;
  7332. /*
  7333. * check reference count again if the block isn't locked.
  7334. * we should start walking down the tree again if reference
  7335. * count is one.
  7336. */
  7337. if (!path->locks[level]) {
  7338. BUG_ON(level == 0);
  7339. btrfs_tree_lock(eb);
  7340. btrfs_set_lock_blocking(eb);
  7341. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7342. ret = btrfs_lookup_extent_info(trans, root,
  7343. eb->start, level, 1,
  7344. &wc->refs[level],
  7345. &wc->flags[level]);
  7346. if (ret < 0) {
  7347. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7348. path->locks[level] = 0;
  7349. return ret;
  7350. }
  7351. BUG_ON(wc->refs[level] == 0);
  7352. if (wc->refs[level] == 1) {
  7353. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7354. path->locks[level] = 0;
  7355. return 1;
  7356. }
  7357. }
  7358. }
  7359. /* wc->stage == DROP_REFERENCE */
  7360. BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
  7361. if (wc->refs[level] == 1) {
  7362. if (level == 0) {
  7363. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  7364. ret = btrfs_dec_ref(trans, root, eb, 1);
  7365. else
  7366. ret = btrfs_dec_ref(trans, root, eb, 0);
  7367. BUG_ON(ret); /* -ENOMEM */
  7368. ret = account_leaf_items(trans, root, eb);
  7369. if (ret) {
  7370. printk_ratelimited(KERN_ERR "BTRFS: %s Error "
  7371. "%d accounting leaf items. Quota "
  7372. "is out of sync, rescan required.\n",
  7373. root->fs_info->sb->s_id, ret);
  7374. }
  7375. }
  7376. /* make block locked assertion in clean_tree_block happy */
  7377. if (!path->locks[level] &&
  7378. btrfs_header_generation(eb) == trans->transid) {
  7379. btrfs_tree_lock(eb);
  7380. btrfs_set_lock_blocking(eb);
  7381. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7382. }
  7383. clean_tree_block(trans, root->fs_info, eb);
  7384. }
  7385. if (eb == root->node) {
  7386. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  7387. parent = eb->start;
  7388. else
  7389. BUG_ON(root->root_key.objectid !=
  7390. btrfs_header_owner(eb));
  7391. } else {
  7392. if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  7393. parent = path->nodes[level + 1]->start;
  7394. else
  7395. BUG_ON(root->root_key.objectid !=
  7396. btrfs_header_owner(path->nodes[level + 1]));
  7397. }
  7398. btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
  7399. out:
  7400. wc->refs[level] = 0;
  7401. wc->flags[level] = 0;
  7402. return 0;
  7403. }
  7404. static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
  7405. struct btrfs_root *root,
  7406. struct btrfs_path *path,
  7407. struct walk_control *wc)
  7408. {
  7409. int level = wc->level;
  7410. int lookup_info = 1;
  7411. int ret;
  7412. while (level >= 0) {
  7413. ret = walk_down_proc(trans, root, path, wc, lookup_info);
  7414. if (ret > 0)
  7415. break;
  7416. if (level == 0)
  7417. break;
  7418. if (path->slots[level] >=
  7419. btrfs_header_nritems(path->nodes[level]))
  7420. break;
  7421. ret = do_walk_down(trans, root, path, wc, &lookup_info);
  7422. if (ret > 0) {
  7423. path->slots[level]++;
  7424. continue;
  7425. } else if (ret < 0)
  7426. return ret;
  7427. level = wc->level;
  7428. }
  7429. return 0;
  7430. }
  7431. static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
  7432. struct btrfs_root *root,
  7433. struct btrfs_path *path,
  7434. struct walk_control *wc, int max_level)
  7435. {
  7436. int level = wc->level;
  7437. int ret;
  7438. path->slots[level] = btrfs_header_nritems(path->nodes[level]);
  7439. while (level < max_level && path->nodes[level]) {
  7440. wc->level = level;
  7441. if (path->slots[level] + 1 <
  7442. btrfs_header_nritems(path->nodes[level])) {
  7443. path->slots[level]++;
  7444. return 0;
  7445. } else {
  7446. ret = walk_up_proc(trans, root, path, wc);
  7447. if (ret > 0)
  7448. return 0;
  7449. if (path->locks[level]) {
  7450. btrfs_tree_unlock_rw(path->nodes[level],
  7451. path->locks[level]);
  7452. path->locks[level] = 0;
  7453. }
  7454. free_extent_buffer(path->nodes[level]);
  7455. path->nodes[level] = NULL;
  7456. level++;
  7457. }
  7458. }
  7459. return 1;
  7460. }
  7461. /*
  7462. * drop a subvolume tree.
  7463. *
  7464. * this function traverses the tree freeing any blocks that only
  7465. * referenced by the tree.
  7466. *
  7467. * when a shared tree block is found. this function decreases its
  7468. * reference count by one. if update_ref is true, this function
  7469. * also make sure backrefs for the shared block and all lower level
  7470. * blocks are properly updated.
  7471. *
  7472. * If called with for_reloc == 0, may exit early with -EAGAIN
  7473. */
  7474. int btrfs_drop_snapshot(struct btrfs_root *root,
  7475. struct btrfs_block_rsv *block_rsv, int update_ref,
  7476. int for_reloc)
  7477. {
  7478. struct btrfs_path *path;
  7479. struct btrfs_trans_handle *trans;
  7480. struct btrfs_root *tree_root = root->fs_info->tree_root;
  7481. struct btrfs_root_item *root_item = &root->root_item;
  7482. struct walk_control *wc;
  7483. struct btrfs_key key;
  7484. int err = 0;
  7485. int ret;
  7486. int level;
  7487. bool root_dropped = false;
  7488. btrfs_debug(root->fs_info, "Drop subvolume %llu", root->objectid);
  7489. path = btrfs_alloc_path();
  7490. if (!path) {
  7491. err = -ENOMEM;
  7492. goto out;
  7493. }
  7494. wc = kzalloc(sizeof(*wc), GFP_NOFS);
  7495. if (!wc) {
  7496. btrfs_free_path(path);
  7497. err = -ENOMEM;
  7498. goto out;
  7499. }
  7500. trans = btrfs_start_transaction(tree_root, 0);
  7501. if (IS_ERR(trans)) {
  7502. err = PTR_ERR(trans);
  7503. goto out_free;
  7504. }
  7505. if (block_rsv)
  7506. trans->block_rsv = block_rsv;
  7507. if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
  7508. level = btrfs_header_level(root->node);
  7509. path->nodes[level] = btrfs_lock_root_node(root);
  7510. btrfs_set_lock_blocking(path->nodes[level]);
  7511. path->slots[level] = 0;
  7512. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7513. memset(&wc->update_progress, 0,
  7514. sizeof(wc->update_progress));
  7515. } else {
  7516. btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
  7517. memcpy(&wc->update_progress, &key,
  7518. sizeof(wc->update_progress));
  7519. level = root_item->drop_level;
  7520. BUG_ON(level == 0);
  7521. path->lowest_level = level;
  7522. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  7523. path->lowest_level = 0;
  7524. if (ret < 0) {
  7525. err = ret;
  7526. goto out_end_trans;
  7527. }
  7528. WARN_ON(ret > 0);
  7529. /*
  7530. * unlock our path, this is safe because only this
  7531. * function is allowed to delete this snapshot
  7532. */
  7533. btrfs_unlock_up_safe(path, 0);
  7534. level = btrfs_header_level(root->node);
  7535. while (1) {
  7536. btrfs_tree_lock(path->nodes[level]);
  7537. btrfs_set_lock_blocking(path->nodes[level]);
  7538. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7539. ret = btrfs_lookup_extent_info(trans, root,
  7540. path->nodes[level]->start,
  7541. level, 1, &wc->refs[level],
  7542. &wc->flags[level]);
  7543. if (ret < 0) {
  7544. err = ret;
  7545. goto out_end_trans;
  7546. }
  7547. BUG_ON(wc->refs[level] == 0);
  7548. if (level == root_item->drop_level)
  7549. break;
  7550. btrfs_tree_unlock(path->nodes[level]);
  7551. path->locks[level] = 0;
  7552. WARN_ON(wc->refs[level] != 1);
  7553. level--;
  7554. }
  7555. }
  7556. wc->level = level;
  7557. wc->shared_level = -1;
  7558. wc->stage = DROP_REFERENCE;
  7559. wc->update_ref = update_ref;
  7560. wc->keep_locks = 0;
  7561. wc->for_reloc = for_reloc;
  7562. wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
  7563. while (1) {
  7564. ret = walk_down_tree(trans, root, path, wc);
  7565. if (ret < 0) {
  7566. err = ret;
  7567. break;
  7568. }
  7569. ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
  7570. if (ret < 0) {
  7571. err = ret;
  7572. break;
  7573. }
  7574. if (ret > 0) {
  7575. BUG_ON(wc->stage != DROP_REFERENCE);
  7576. break;
  7577. }
  7578. if (wc->stage == DROP_REFERENCE) {
  7579. level = wc->level;
  7580. btrfs_node_key(path->nodes[level],
  7581. &root_item->drop_progress,
  7582. path->slots[level]);
  7583. root_item->drop_level = level;
  7584. }
  7585. BUG_ON(wc->level == 0);
  7586. if (btrfs_should_end_transaction(trans, tree_root) ||
  7587. (!for_reloc && btrfs_need_cleaner_sleep(root))) {
  7588. ret = btrfs_update_root(trans, tree_root,
  7589. &root->root_key,
  7590. root_item);
  7591. if (ret) {
  7592. btrfs_abort_transaction(trans, tree_root, ret);
  7593. err = ret;
  7594. goto out_end_trans;
  7595. }
  7596. btrfs_end_transaction_throttle(trans, tree_root);
  7597. if (!for_reloc && btrfs_need_cleaner_sleep(root)) {
  7598. pr_debug("BTRFS: drop snapshot early exit\n");
  7599. err = -EAGAIN;
  7600. goto out_free;
  7601. }
  7602. trans = btrfs_start_transaction(tree_root, 0);
  7603. if (IS_ERR(trans)) {
  7604. err = PTR_ERR(trans);
  7605. goto out_free;
  7606. }
  7607. if (block_rsv)
  7608. trans->block_rsv = block_rsv;
  7609. }
  7610. }
  7611. btrfs_release_path(path);
  7612. if (err)
  7613. goto out_end_trans;
  7614. ret = btrfs_del_root(trans, tree_root, &root->root_key);
  7615. if (ret) {
  7616. btrfs_abort_transaction(trans, tree_root, ret);
  7617. goto out_end_trans;
  7618. }
  7619. if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
  7620. ret = btrfs_find_root(tree_root, &root->root_key, path,
  7621. NULL, NULL);
  7622. if (ret < 0) {
  7623. btrfs_abort_transaction(trans, tree_root, ret);
  7624. err = ret;
  7625. goto out_end_trans;
  7626. } else if (ret > 0) {
  7627. /* if we fail to delete the orphan item this time
  7628. * around, it'll get picked up the next time.
  7629. *
  7630. * The most common failure here is just -ENOENT.
  7631. */
  7632. btrfs_del_orphan_item(trans, tree_root,
  7633. root->root_key.objectid);
  7634. }
  7635. }
  7636. if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
  7637. btrfs_add_dropped_root(trans, root);
  7638. } else {
  7639. free_extent_buffer(root->node);
  7640. free_extent_buffer(root->commit_root);
  7641. btrfs_put_fs_root(root);
  7642. }
  7643. root_dropped = true;
  7644. out_end_trans:
  7645. btrfs_end_transaction_throttle(trans, tree_root);
  7646. out_free:
  7647. kfree(wc);
  7648. btrfs_free_path(path);
  7649. out:
  7650. /*
  7651. * So if we need to stop dropping the snapshot for whatever reason we
  7652. * need to make sure to add it back to the dead root list so that we
  7653. * keep trying to do the work later. This also cleans up roots if we
  7654. * don't have it in the radix (like when we recover after a power fail
  7655. * or unmount) so we don't leak memory.
  7656. */
  7657. if (!for_reloc && root_dropped == false)
  7658. btrfs_add_dead_root(root);
  7659. if (err && err != -EAGAIN)
  7660. btrfs_std_error(root->fs_info, err);
  7661. return err;
  7662. }
  7663. /*
  7664. * drop subtree rooted at tree block 'node'.
  7665. *
  7666. * NOTE: this function will unlock and release tree block 'node'
  7667. * only used by relocation code
  7668. */
  7669. int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
  7670. struct btrfs_root *root,
  7671. struct extent_buffer *node,
  7672. struct extent_buffer *parent)
  7673. {
  7674. struct btrfs_path *path;
  7675. struct walk_control *wc;
  7676. int level;
  7677. int parent_level;
  7678. int ret = 0;
  7679. int wret;
  7680. BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
  7681. path = btrfs_alloc_path();
  7682. if (!path)
  7683. return -ENOMEM;
  7684. wc = kzalloc(sizeof(*wc), GFP_NOFS);
  7685. if (!wc) {
  7686. btrfs_free_path(path);
  7687. return -ENOMEM;
  7688. }
  7689. btrfs_assert_tree_locked(parent);
  7690. parent_level = btrfs_header_level(parent);
  7691. extent_buffer_get(parent);
  7692. path->nodes[parent_level] = parent;
  7693. path->slots[parent_level] = btrfs_header_nritems(parent);
  7694. btrfs_assert_tree_locked(node);
  7695. level = btrfs_header_level(node);
  7696. path->nodes[level] = node;
  7697. path->slots[level] = 0;
  7698. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7699. wc->refs[parent_level] = 1;
  7700. wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  7701. wc->level = level;
  7702. wc->shared_level = -1;
  7703. wc->stage = DROP_REFERENCE;
  7704. wc->update_ref = 0;
  7705. wc->keep_locks = 1;
  7706. wc->for_reloc = 1;
  7707. wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
  7708. while (1) {
  7709. wret = walk_down_tree(trans, root, path, wc);
  7710. if (wret < 0) {
  7711. ret = wret;
  7712. break;
  7713. }
  7714. wret = walk_up_tree(trans, root, path, wc, parent_level);
  7715. if (wret < 0)
  7716. ret = wret;
  7717. if (wret != 0)
  7718. break;
  7719. }
  7720. kfree(wc);
  7721. btrfs_free_path(path);
  7722. return ret;
  7723. }
  7724. static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
  7725. {
  7726. u64 num_devices;
  7727. u64 stripped;
  7728. /*
  7729. * if restripe for this chunk_type is on pick target profile and
  7730. * return, otherwise do the usual balance
  7731. */
  7732. stripped = get_restripe_target(root->fs_info, flags);
  7733. if (stripped)
  7734. return extended_to_chunk(stripped);
  7735. num_devices = root->fs_info->fs_devices->rw_devices;
  7736. stripped = BTRFS_BLOCK_GROUP_RAID0 |
  7737. BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
  7738. BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
  7739. if (num_devices == 1) {
  7740. stripped |= BTRFS_BLOCK_GROUP_DUP;
  7741. stripped = flags & ~stripped;
  7742. /* turn raid0 into single device chunks */
  7743. if (flags & BTRFS_BLOCK_GROUP_RAID0)
  7744. return stripped;
  7745. /* turn mirroring into duplication */
  7746. if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
  7747. BTRFS_BLOCK_GROUP_RAID10))
  7748. return stripped | BTRFS_BLOCK_GROUP_DUP;
  7749. } else {
  7750. /* they already had raid on here, just return */
  7751. if (flags & stripped)
  7752. return flags;
  7753. stripped |= BTRFS_BLOCK_GROUP_DUP;
  7754. stripped = flags & ~stripped;
  7755. /* switch duplicated blocks with raid1 */
  7756. if (flags & BTRFS_BLOCK_GROUP_DUP)
  7757. return stripped | BTRFS_BLOCK_GROUP_RAID1;
  7758. /* this is drive concat, leave it alone */
  7759. }
  7760. return flags;
  7761. }
  7762. static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
  7763. {
  7764. struct btrfs_space_info *sinfo = cache->space_info;
  7765. u64 num_bytes;
  7766. u64 min_allocable_bytes;
  7767. int ret = -ENOSPC;
  7768. /*
  7769. * We need some metadata space and system metadata space for
  7770. * allocating chunks in some corner cases until we force to set
  7771. * it to be readonly.
  7772. */
  7773. if ((sinfo->flags &
  7774. (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
  7775. !force)
  7776. min_allocable_bytes = 1 * 1024 * 1024;
  7777. else
  7778. min_allocable_bytes = 0;
  7779. spin_lock(&sinfo->lock);
  7780. spin_lock(&cache->lock);
  7781. if (cache->ro) {
  7782. cache->ro++;
  7783. ret = 0;
  7784. goto out;
  7785. }
  7786. num_bytes = cache->key.offset - cache->reserved - cache->pinned -
  7787. cache->bytes_super - btrfs_block_group_used(&cache->item);
  7788. if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
  7789. sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
  7790. min_allocable_bytes <= sinfo->total_bytes) {
  7791. sinfo->bytes_readonly += num_bytes;
  7792. cache->ro++;
  7793. list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
  7794. ret = 0;
  7795. }
  7796. out:
  7797. spin_unlock(&cache->lock);
  7798. spin_unlock(&sinfo->lock);
  7799. return ret;
  7800. }
  7801. int btrfs_inc_block_group_ro(struct btrfs_root *root,
  7802. struct btrfs_block_group_cache *cache)
  7803. {
  7804. struct btrfs_trans_handle *trans;
  7805. u64 alloc_flags;
  7806. int ret;
  7807. again:
  7808. trans = btrfs_join_transaction(root);
  7809. if (IS_ERR(trans))
  7810. return PTR_ERR(trans);
  7811. /*
  7812. * we're not allowed to set block groups readonly after the dirty
  7813. * block groups cache has started writing. If it already started,
  7814. * back off and let this transaction commit
  7815. */
  7816. mutex_lock(&root->fs_info->ro_block_group_mutex);
  7817. if (trans->transaction->dirty_bg_run) {
  7818. u64 transid = trans->transid;
  7819. mutex_unlock(&root->fs_info->ro_block_group_mutex);
  7820. btrfs_end_transaction(trans, root);
  7821. ret = btrfs_wait_for_commit(root, transid);
  7822. if (ret)
  7823. return ret;
  7824. goto again;
  7825. }
  7826. /*
  7827. * if we are changing raid levels, try to allocate a corresponding
  7828. * block group with the new raid level.
  7829. */
  7830. alloc_flags = update_block_group_flags(root, cache->flags);
  7831. if (alloc_flags != cache->flags) {
  7832. ret = do_chunk_alloc(trans, root, alloc_flags,
  7833. CHUNK_ALLOC_FORCE);
  7834. /*
  7835. * ENOSPC is allowed here, we may have enough space
  7836. * already allocated at the new raid level to
  7837. * carry on
  7838. */
  7839. if (ret == -ENOSPC)
  7840. ret = 0;
  7841. if (ret < 0)
  7842. goto out;
  7843. }
  7844. ret = inc_block_group_ro(cache, 0);
  7845. if (!ret)
  7846. goto out;
  7847. alloc_flags = get_alloc_profile(root, cache->space_info->flags);
  7848. ret = do_chunk_alloc(trans, root, alloc_flags,
  7849. CHUNK_ALLOC_FORCE);
  7850. if (ret < 0)
  7851. goto out;
  7852. ret = inc_block_group_ro(cache, 0);
  7853. out:
  7854. if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
  7855. alloc_flags = update_block_group_flags(root, cache->flags);
  7856. lock_chunks(root->fs_info->chunk_root);
  7857. check_system_chunk(trans, root, alloc_flags);
  7858. unlock_chunks(root->fs_info->chunk_root);
  7859. }
  7860. mutex_unlock(&root->fs_info->ro_block_group_mutex);
  7861. btrfs_end_transaction(trans, root);
  7862. return ret;
  7863. }
  7864. int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
  7865. struct btrfs_root *root, u64 type)
  7866. {
  7867. u64 alloc_flags = get_alloc_profile(root, type);
  7868. return do_chunk_alloc(trans, root, alloc_flags,
  7869. CHUNK_ALLOC_FORCE);
  7870. }
  7871. /*
  7872. * helper to account the unused space of all the readonly block group in the
  7873. * space_info. takes mirrors into account.
  7874. */
  7875. u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
  7876. {
  7877. struct btrfs_block_group_cache *block_group;
  7878. u64 free_bytes = 0;
  7879. int factor;
  7880. /* It's df, we don't care if it's racey */
  7881. if (list_empty(&sinfo->ro_bgs))
  7882. return 0;
  7883. spin_lock(&sinfo->lock);
  7884. list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
  7885. spin_lock(&block_group->lock);
  7886. if (!block_group->ro) {
  7887. spin_unlock(&block_group->lock);
  7888. continue;
  7889. }
  7890. if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
  7891. BTRFS_BLOCK_GROUP_RAID10 |
  7892. BTRFS_BLOCK_GROUP_DUP))
  7893. factor = 2;
  7894. else
  7895. factor = 1;
  7896. free_bytes += (block_group->key.offset -
  7897. btrfs_block_group_used(&block_group->item)) *
  7898. factor;
  7899. spin_unlock(&block_group->lock);
  7900. }
  7901. spin_unlock(&sinfo->lock);
  7902. return free_bytes;
  7903. }
  7904. void btrfs_dec_block_group_ro(struct btrfs_root *root,
  7905. struct btrfs_block_group_cache *cache)
  7906. {
  7907. struct btrfs_space_info *sinfo = cache->space_info;
  7908. u64 num_bytes;
  7909. BUG_ON(!cache->ro);
  7910. spin_lock(&sinfo->lock);
  7911. spin_lock(&cache->lock);
  7912. if (!--cache->ro) {
  7913. num_bytes = cache->key.offset - cache->reserved -
  7914. cache->pinned - cache->bytes_super -
  7915. btrfs_block_group_used(&cache->item);
  7916. sinfo->bytes_readonly -= num_bytes;
  7917. list_del_init(&cache->ro_list);
  7918. }
  7919. spin_unlock(&cache->lock);
  7920. spin_unlock(&sinfo->lock);
  7921. }
  7922. /*
  7923. * checks to see if its even possible to relocate this block group.
  7924. *
  7925. * @return - -1 if it's not a good idea to relocate this block group, 0 if its
  7926. * ok to go ahead and try.
  7927. */
  7928. int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
  7929. {
  7930. struct btrfs_block_group_cache *block_group;
  7931. struct btrfs_space_info *space_info;
  7932. struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
  7933. struct btrfs_device *device;
  7934. struct btrfs_trans_handle *trans;
  7935. u64 min_free;
  7936. u64 dev_min = 1;
  7937. u64 dev_nr = 0;
  7938. u64 target;
  7939. int index;
  7940. int full = 0;
  7941. int ret = 0;
  7942. block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
  7943. /* odd, couldn't find the block group, leave it alone */
  7944. if (!block_group)
  7945. return -1;
  7946. min_free = btrfs_block_group_used(&block_group->item);
  7947. /* no bytes used, we're good */
  7948. if (!min_free)
  7949. goto out;
  7950. space_info = block_group->space_info;
  7951. spin_lock(&space_info->lock);
  7952. full = space_info->full;
  7953. /*
  7954. * if this is the last block group we have in this space, we can't
  7955. * relocate it unless we're able to allocate a new chunk below.
  7956. *
  7957. * Otherwise, we need to make sure we have room in the space to handle
  7958. * all of the extents from this block group. If we can, we're good
  7959. */
  7960. if ((space_info->total_bytes != block_group->key.offset) &&
  7961. (space_info->bytes_used + space_info->bytes_reserved +
  7962. space_info->bytes_pinned + space_info->bytes_readonly +
  7963. min_free < space_info->total_bytes)) {
  7964. spin_unlock(&space_info->lock);
  7965. goto out;
  7966. }
  7967. spin_unlock(&space_info->lock);
  7968. /*
  7969. * ok we don't have enough space, but maybe we have free space on our
  7970. * devices to allocate new chunks for relocation, so loop through our
  7971. * alloc devices and guess if we have enough space. if this block
  7972. * group is going to be restriped, run checks against the target
  7973. * profile instead of the current one.
  7974. */
  7975. ret = -1;
  7976. /*
  7977. * index:
  7978. * 0: raid10
  7979. * 1: raid1
  7980. * 2: dup
  7981. * 3: raid0
  7982. * 4: single
  7983. */
  7984. target = get_restripe_target(root->fs_info, block_group->flags);
  7985. if (target) {
  7986. index = __get_raid_index(extended_to_chunk(target));
  7987. } else {
  7988. /*
  7989. * this is just a balance, so if we were marked as full
  7990. * we know there is no space for a new chunk
  7991. */
  7992. if (full)
  7993. goto out;
  7994. index = get_block_group_index(block_group);
  7995. }
  7996. if (index == BTRFS_RAID_RAID10) {
  7997. dev_min = 4;
  7998. /* Divide by 2 */
  7999. min_free >>= 1;
  8000. } else if (index == BTRFS_RAID_RAID1) {
  8001. dev_min = 2;
  8002. } else if (index == BTRFS_RAID_DUP) {
  8003. /* Multiply by 2 */
  8004. min_free <<= 1;
  8005. } else if (index == BTRFS_RAID_RAID0) {
  8006. dev_min = fs_devices->rw_devices;
  8007. min_free = div64_u64(min_free, dev_min);
  8008. }
  8009. /* We need to do this so that we can look at pending chunks */
  8010. trans = btrfs_join_transaction(root);
  8011. if (IS_ERR(trans)) {
  8012. ret = PTR_ERR(trans);
  8013. goto out;
  8014. }
  8015. mutex_lock(&root->fs_info->chunk_mutex);
  8016. list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
  8017. u64 dev_offset;
  8018. /*
  8019. * check to make sure we can actually find a chunk with enough
  8020. * space to fit our block group in.
  8021. */
  8022. if (device->total_bytes > device->bytes_used + min_free &&
  8023. !device->is_tgtdev_for_dev_replace) {
  8024. ret = find_free_dev_extent(trans, device, min_free,
  8025. &dev_offset, NULL);
  8026. if (!ret)
  8027. dev_nr++;
  8028. if (dev_nr >= dev_min)
  8029. break;
  8030. ret = -1;
  8031. }
  8032. }
  8033. mutex_unlock(&root->fs_info->chunk_mutex);
  8034. btrfs_end_transaction(trans, root);
  8035. out:
  8036. btrfs_put_block_group(block_group);
  8037. return ret;
  8038. }
  8039. static int find_first_block_group(struct btrfs_root *root,
  8040. struct btrfs_path *path, struct btrfs_key *key)
  8041. {
  8042. int ret = 0;
  8043. struct btrfs_key found_key;
  8044. struct extent_buffer *leaf;
  8045. int slot;
  8046. ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
  8047. if (ret < 0)
  8048. goto out;
  8049. while (1) {
  8050. slot = path->slots[0];
  8051. leaf = path->nodes[0];
  8052. if (slot >= btrfs_header_nritems(leaf)) {
  8053. ret = btrfs_next_leaf(root, path);
  8054. if (ret == 0)
  8055. continue;
  8056. if (ret < 0)
  8057. goto out;
  8058. break;
  8059. }
  8060. btrfs_item_key_to_cpu(leaf, &found_key, slot);
  8061. if (found_key.objectid >= key->objectid &&
  8062. found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
  8063. ret = 0;
  8064. goto out;
  8065. }
  8066. path->slots[0]++;
  8067. }
  8068. out:
  8069. return ret;
  8070. }
  8071. void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
  8072. {
  8073. struct btrfs_block_group_cache *block_group;
  8074. u64 last = 0;
  8075. while (1) {
  8076. struct inode *inode;
  8077. block_group = btrfs_lookup_first_block_group(info, last);
  8078. while (block_group) {
  8079. spin_lock(&block_group->lock);
  8080. if (block_group->iref)
  8081. break;
  8082. spin_unlock(&block_group->lock);
  8083. block_group = next_block_group(info->tree_root,
  8084. block_group);
  8085. }
  8086. if (!block_group) {
  8087. if (last == 0)
  8088. break;
  8089. last = 0;
  8090. continue;
  8091. }
  8092. inode = block_group->inode;
  8093. block_group->iref = 0;
  8094. block_group->inode = NULL;
  8095. spin_unlock(&block_group->lock);
  8096. iput(inode);
  8097. last = block_group->key.objectid + block_group->key.offset;
  8098. btrfs_put_block_group(block_group);
  8099. }
  8100. }
  8101. int btrfs_free_block_groups(struct btrfs_fs_info *info)
  8102. {
  8103. struct btrfs_block_group_cache *block_group;
  8104. struct btrfs_space_info *space_info;
  8105. struct btrfs_caching_control *caching_ctl;
  8106. struct rb_node *n;
  8107. down_write(&info->commit_root_sem);
  8108. while (!list_empty(&info->caching_block_groups)) {
  8109. caching_ctl = list_entry(info->caching_block_groups.next,
  8110. struct btrfs_caching_control, list);
  8111. list_del(&caching_ctl->list);
  8112. put_caching_control(caching_ctl);
  8113. }
  8114. up_write(&info->commit_root_sem);
  8115. spin_lock(&info->unused_bgs_lock);
  8116. while (!list_empty(&info->unused_bgs)) {
  8117. block_group = list_first_entry(&info->unused_bgs,
  8118. struct btrfs_block_group_cache,
  8119. bg_list);
  8120. list_del_init(&block_group->bg_list);
  8121. btrfs_put_block_group(block_group);
  8122. }
  8123. spin_unlock(&info->unused_bgs_lock);
  8124. spin_lock(&info->block_group_cache_lock);
  8125. while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
  8126. block_group = rb_entry(n, struct btrfs_block_group_cache,
  8127. cache_node);
  8128. rb_erase(&block_group->cache_node,
  8129. &info->block_group_cache_tree);
  8130. RB_CLEAR_NODE(&block_group->cache_node);
  8131. spin_unlock(&info->block_group_cache_lock);
  8132. down_write(&block_group->space_info->groups_sem);
  8133. list_del(&block_group->list);
  8134. up_write(&block_group->space_info->groups_sem);
  8135. if (block_group->cached == BTRFS_CACHE_STARTED)
  8136. wait_block_group_cache_done(block_group);
  8137. /*
  8138. * We haven't cached this block group, which means we could
  8139. * possibly have excluded extents on this block group.
  8140. */
  8141. if (block_group->cached == BTRFS_CACHE_NO ||
  8142. block_group->cached == BTRFS_CACHE_ERROR)
  8143. free_excluded_extents(info->extent_root, block_group);
  8144. btrfs_remove_free_space_cache(block_group);
  8145. btrfs_put_block_group(block_group);
  8146. spin_lock(&info->block_group_cache_lock);
  8147. }
  8148. spin_unlock(&info->block_group_cache_lock);
  8149. /* now that all the block groups are freed, go through and
  8150. * free all the space_info structs. This is only called during
  8151. * the final stages of unmount, and so we know nobody is
  8152. * using them. We call synchronize_rcu() once before we start,
  8153. * just to be on the safe side.
  8154. */
  8155. synchronize_rcu();
  8156. release_global_block_rsv(info);
  8157. while (!list_empty(&info->space_info)) {
  8158. int i;
  8159. space_info = list_entry(info->space_info.next,
  8160. struct btrfs_space_info,
  8161. list);
  8162. if (btrfs_test_opt(info->tree_root, ENOSPC_DEBUG)) {
  8163. if (WARN_ON(space_info->bytes_pinned > 0 ||
  8164. space_info->bytes_reserved > 0 ||
  8165. space_info->bytes_may_use > 0)) {
  8166. dump_space_info(space_info, 0, 0);
  8167. }
  8168. }
  8169. list_del(&space_info->list);
  8170. for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
  8171. struct kobject *kobj;
  8172. kobj = space_info->block_group_kobjs[i];
  8173. space_info->block_group_kobjs[i] = NULL;
  8174. if (kobj) {
  8175. kobject_del(kobj);
  8176. kobject_put(kobj);
  8177. }
  8178. }
  8179. kobject_del(&space_info->kobj);
  8180. kobject_put(&space_info->kobj);
  8181. }
  8182. return 0;
  8183. }
  8184. static void __link_block_group(struct btrfs_space_info *space_info,
  8185. struct btrfs_block_group_cache *cache)
  8186. {
  8187. int index = get_block_group_index(cache);
  8188. bool first = false;
  8189. down_write(&space_info->groups_sem);
  8190. if (list_empty(&space_info->block_groups[index]))
  8191. first = true;
  8192. list_add_tail(&cache->list, &space_info->block_groups[index]);
  8193. up_write(&space_info->groups_sem);
  8194. if (first) {
  8195. struct raid_kobject *rkobj;
  8196. int ret;
  8197. rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
  8198. if (!rkobj)
  8199. goto out_err;
  8200. rkobj->raid_type = index;
  8201. kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
  8202. ret = kobject_add(&rkobj->kobj, &space_info->kobj,
  8203. "%s", get_raid_name(index));
  8204. if (ret) {
  8205. kobject_put(&rkobj->kobj);
  8206. goto out_err;
  8207. }
  8208. space_info->block_group_kobjs[index] = &rkobj->kobj;
  8209. }
  8210. return;
  8211. out_err:
  8212. pr_warn("BTRFS: failed to add kobject for block cache. ignoring.\n");
  8213. }
  8214. static struct btrfs_block_group_cache *
  8215. btrfs_create_block_group_cache(struct btrfs_root *root, u64 start, u64 size)
  8216. {
  8217. struct btrfs_block_group_cache *cache;
  8218. cache = kzalloc(sizeof(*cache), GFP_NOFS);
  8219. if (!cache)
  8220. return NULL;
  8221. cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
  8222. GFP_NOFS);
  8223. if (!cache->free_space_ctl) {
  8224. kfree(cache);
  8225. return NULL;
  8226. }
  8227. cache->key.objectid = start;
  8228. cache->key.offset = size;
  8229. cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
  8230. cache->sectorsize = root->sectorsize;
  8231. cache->fs_info = root->fs_info;
  8232. cache->full_stripe_len = btrfs_full_stripe_len(root,
  8233. &root->fs_info->mapping_tree,
  8234. start);
  8235. atomic_set(&cache->count, 1);
  8236. spin_lock_init(&cache->lock);
  8237. init_rwsem(&cache->data_rwsem);
  8238. INIT_LIST_HEAD(&cache->list);
  8239. INIT_LIST_HEAD(&cache->cluster_list);
  8240. INIT_LIST_HEAD(&cache->bg_list);
  8241. INIT_LIST_HEAD(&cache->ro_list);
  8242. INIT_LIST_HEAD(&cache->dirty_list);
  8243. INIT_LIST_HEAD(&cache->io_list);
  8244. btrfs_init_free_space_ctl(cache);
  8245. atomic_set(&cache->trimming, 0);
  8246. return cache;
  8247. }
  8248. int btrfs_read_block_groups(struct btrfs_root *root)
  8249. {
  8250. struct btrfs_path *path;
  8251. int ret;
  8252. struct btrfs_block_group_cache *cache;
  8253. struct btrfs_fs_info *info = root->fs_info;
  8254. struct btrfs_space_info *space_info;
  8255. struct btrfs_key key;
  8256. struct btrfs_key found_key;
  8257. struct extent_buffer *leaf;
  8258. int need_clear = 0;
  8259. u64 cache_gen;
  8260. root = info->extent_root;
  8261. key.objectid = 0;
  8262. key.offset = 0;
  8263. key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
  8264. path = btrfs_alloc_path();
  8265. if (!path)
  8266. return -ENOMEM;
  8267. path->reada = 1;
  8268. cache_gen = btrfs_super_cache_generation(root->fs_info->super_copy);
  8269. if (btrfs_test_opt(root, SPACE_CACHE) &&
  8270. btrfs_super_generation(root->fs_info->super_copy) != cache_gen)
  8271. need_clear = 1;
  8272. if (btrfs_test_opt(root, CLEAR_CACHE))
  8273. need_clear = 1;
  8274. while (1) {
  8275. ret = find_first_block_group(root, path, &key);
  8276. if (ret > 0)
  8277. break;
  8278. if (ret != 0)
  8279. goto error;
  8280. leaf = path->nodes[0];
  8281. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  8282. cache = btrfs_create_block_group_cache(root, found_key.objectid,
  8283. found_key.offset);
  8284. if (!cache) {
  8285. ret = -ENOMEM;
  8286. goto error;
  8287. }
  8288. if (need_clear) {
  8289. /*
  8290. * When we mount with old space cache, we need to
  8291. * set BTRFS_DC_CLEAR and set dirty flag.
  8292. *
  8293. * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
  8294. * truncate the old free space cache inode and
  8295. * setup a new one.
  8296. * b) Setting 'dirty flag' makes sure that we flush
  8297. * the new space cache info onto disk.
  8298. */
  8299. if (btrfs_test_opt(root, SPACE_CACHE))
  8300. cache->disk_cache_state = BTRFS_DC_CLEAR;
  8301. }
  8302. read_extent_buffer(leaf, &cache->item,
  8303. btrfs_item_ptr_offset(leaf, path->slots[0]),
  8304. sizeof(cache->item));
  8305. cache->flags = btrfs_block_group_flags(&cache->item);
  8306. key.objectid = found_key.objectid + found_key.offset;
  8307. btrfs_release_path(path);
  8308. /*
  8309. * We need to exclude the super stripes now so that the space
  8310. * info has super bytes accounted for, otherwise we'll think
  8311. * we have more space than we actually do.
  8312. */
  8313. ret = exclude_super_stripes(root, cache);
  8314. if (ret) {
  8315. /*
  8316. * We may have excluded something, so call this just in
  8317. * case.
  8318. */
  8319. free_excluded_extents(root, cache);
  8320. btrfs_put_block_group(cache);
  8321. goto error;
  8322. }
  8323. /*
  8324. * check for two cases, either we are full, and therefore
  8325. * don't need to bother with the caching work since we won't
  8326. * find any space, or we are empty, and we can just add all
  8327. * the space in and be done with it. This saves us _alot_ of
  8328. * time, particularly in the full case.
  8329. */
  8330. if (found_key.offset == btrfs_block_group_used(&cache->item)) {
  8331. cache->last_byte_to_unpin = (u64)-1;
  8332. cache->cached = BTRFS_CACHE_FINISHED;
  8333. free_excluded_extents(root, cache);
  8334. } else if (btrfs_block_group_used(&cache->item) == 0) {
  8335. cache->last_byte_to_unpin = (u64)-1;
  8336. cache->cached = BTRFS_CACHE_FINISHED;
  8337. add_new_free_space(cache, root->fs_info,
  8338. found_key.objectid,
  8339. found_key.objectid +
  8340. found_key.offset);
  8341. free_excluded_extents(root, cache);
  8342. }
  8343. ret = btrfs_add_block_group_cache(root->fs_info, cache);
  8344. if (ret) {
  8345. btrfs_remove_free_space_cache(cache);
  8346. btrfs_put_block_group(cache);
  8347. goto error;
  8348. }
  8349. ret = update_space_info(info, cache->flags, found_key.offset,
  8350. btrfs_block_group_used(&cache->item),
  8351. &space_info);
  8352. if (ret) {
  8353. btrfs_remove_free_space_cache(cache);
  8354. spin_lock(&info->block_group_cache_lock);
  8355. rb_erase(&cache->cache_node,
  8356. &info->block_group_cache_tree);
  8357. RB_CLEAR_NODE(&cache->cache_node);
  8358. spin_unlock(&info->block_group_cache_lock);
  8359. btrfs_put_block_group(cache);
  8360. goto error;
  8361. }
  8362. cache->space_info = space_info;
  8363. spin_lock(&cache->space_info->lock);
  8364. cache->space_info->bytes_readonly += cache->bytes_super;
  8365. spin_unlock(&cache->space_info->lock);
  8366. __link_block_group(space_info, cache);
  8367. set_avail_alloc_bits(root->fs_info, cache->flags);
  8368. if (btrfs_chunk_readonly(root, cache->key.objectid)) {
  8369. inc_block_group_ro(cache, 1);
  8370. } else if (btrfs_block_group_used(&cache->item) == 0) {
  8371. spin_lock(&info->unused_bgs_lock);
  8372. /* Should always be true but just in case. */
  8373. if (list_empty(&cache->bg_list)) {
  8374. btrfs_get_block_group(cache);
  8375. list_add_tail(&cache->bg_list,
  8376. &info->unused_bgs);
  8377. }
  8378. spin_unlock(&info->unused_bgs_lock);
  8379. }
  8380. }
  8381. list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
  8382. if (!(get_alloc_profile(root, space_info->flags) &
  8383. (BTRFS_BLOCK_GROUP_RAID10 |
  8384. BTRFS_BLOCK_GROUP_RAID1 |
  8385. BTRFS_BLOCK_GROUP_RAID5 |
  8386. BTRFS_BLOCK_GROUP_RAID6 |
  8387. BTRFS_BLOCK_GROUP_DUP)))
  8388. continue;
  8389. /*
  8390. * avoid allocating from un-mirrored block group if there are
  8391. * mirrored block groups.
  8392. */
  8393. list_for_each_entry(cache,
  8394. &space_info->block_groups[BTRFS_RAID_RAID0],
  8395. list)
  8396. inc_block_group_ro(cache, 1);
  8397. list_for_each_entry(cache,
  8398. &space_info->block_groups[BTRFS_RAID_SINGLE],
  8399. list)
  8400. inc_block_group_ro(cache, 1);
  8401. }
  8402. init_global_block_rsv(info);
  8403. ret = 0;
  8404. error:
  8405. btrfs_free_path(path);
  8406. return ret;
  8407. }
  8408. void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
  8409. struct btrfs_root *root)
  8410. {
  8411. struct btrfs_block_group_cache *block_group, *tmp;
  8412. struct btrfs_root *extent_root = root->fs_info->extent_root;
  8413. struct btrfs_block_group_item item;
  8414. struct btrfs_key key;
  8415. int ret = 0;
  8416. bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
  8417. trans->can_flush_pending_bgs = false;
  8418. list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
  8419. if (ret)
  8420. goto next;
  8421. spin_lock(&block_group->lock);
  8422. memcpy(&item, &block_group->item, sizeof(item));
  8423. memcpy(&key, &block_group->key, sizeof(key));
  8424. spin_unlock(&block_group->lock);
  8425. ret = btrfs_insert_item(trans, extent_root, &key, &item,
  8426. sizeof(item));
  8427. if (ret)
  8428. btrfs_abort_transaction(trans, extent_root, ret);
  8429. ret = btrfs_finish_chunk_alloc(trans, extent_root,
  8430. key.objectid, key.offset);
  8431. if (ret)
  8432. btrfs_abort_transaction(trans, extent_root, ret);
  8433. next:
  8434. list_del_init(&block_group->bg_list);
  8435. }
  8436. trans->can_flush_pending_bgs = can_flush_pending_bgs;
  8437. }
  8438. int btrfs_make_block_group(struct btrfs_trans_handle *trans,
  8439. struct btrfs_root *root, u64 bytes_used,
  8440. u64 type, u64 chunk_objectid, u64 chunk_offset,
  8441. u64 size)
  8442. {
  8443. int ret;
  8444. struct btrfs_root *extent_root;
  8445. struct btrfs_block_group_cache *cache;
  8446. extent_root = root->fs_info->extent_root;
  8447. btrfs_set_log_full_commit(root->fs_info, trans);
  8448. cache = btrfs_create_block_group_cache(root, chunk_offset, size);
  8449. if (!cache)
  8450. return -ENOMEM;
  8451. btrfs_set_block_group_used(&cache->item, bytes_used);
  8452. btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
  8453. btrfs_set_block_group_flags(&cache->item, type);
  8454. cache->flags = type;
  8455. cache->last_byte_to_unpin = (u64)-1;
  8456. cache->cached = BTRFS_CACHE_FINISHED;
  8457. ret = exclude_super_stripes(root, cache);
  8458. if (ret) {
  8459. /*
  8460. * We may have excluded something, so call this just in
  8461. * case.
  8462. */
  8463. free_excluded_extents(root, cache);
  8464. btrfs_put_block_group(cache);
  8465. return ret;
  8466. }
  8467. add_new_free_space(cache, root->fs_info, chunk_offset,
  8468. chunk_offset + size);
  8469. free_excluded_extents(root, cache);
  8470. /*
  8471. * Call to ensure the corresponding space_info object is created and
  8472. * assigned to our block group, but don't update its counters just yet.
  8473. * We want our bg to be added to the rbtree with its ->space_info set.
  8474. */
  8475. ret = update_space_info(root->fs_info, cache->flags, 0, 0,
  8476. &cache->space_info);
  8477. if (ret) {
  8478. btrfs_remove_free_space_cache(cache);
  8479. btrfs_put_block_group(cache);
  8480. return ret;
  8481. }
  8482. ret = btrfs_add_block_group_cache(root->fs_info, cache);
  8483. if (ret) {
  8484. btrfs_remove_free_space_cache(cache);
  8485. btrfs_put_block_group(cache);
  8486. return ret;
  8487. }
  8488. /*
  8489. * Now that our block group has its ->space_info set and is inserted in
  8490. * the rbtree, update the space info's counters.
  8491. */
  8492. ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
  8493. &cache->space_info);
  8494. if (ret) {
  8495. btrfs_remove_free_space_cache(cache);
  8496. spin_lock(&root->fs_info->block_group_cache_lock);
  8497. rb_erase(&cache->cache_node,
  8498. &root->fs_info->block_group_cache_tree);
  8499. RB_CLEAR_NODE(&cache->cache_node);
  8500. spin_unlock(&root->fs_info->block_group_cache_lock);
  8501. btrfs_put_block_group(cache);
  8502. return ret;
  8503. }
  8504. update_global_block_rsv(root->fs_info);
  8505. spin_lock(&cache->space_info->lock);
  8506. cache->space_info->bytes_readonly += cache->bytes_super;
  8507. spin_unlock(&cache->space_info->lock);
  8508. __link_block_group(cache->space_info, cache);
  8509. list_add_tail(&cache->bg_list, &trans->new_bgs);
  8510. set_avail_alloc_bits(extent_root->fs_info, type);
  8511. return 0;
  8512. }
  8513. static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
  8514. {
  8515. u64 extra_flags = chunk_to_extended(flags) &
  8516. BTRFS_EXTENDED_PROFILE_MASK;
  8517. write_seqlock(&fs_info->profiles_lock);
  8518. if (flags & BTRFS_BLOCK_GROUP_DATA)
  8519. fs_info->avail_data_alloc_bits &= ~extra_flags;
  8520. if (flags & BTRFS_BLOCK_GROUP_METADATA)
  8521. fs_info->avail_metadata_alloc_bits &= ~extra_flags;
  8522. if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
  8523. fs_info->avail_system_alloc_bits &= ~extra_flags;
  8524. write_sequnlock(&fs_info->profiles_lock);
  8525. }
  8526. int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
  8527. struct btrfs_root *root, u64 group_start,
  8528. struct extent_map *em)
  8529. {
  8530. struct btrfs_path *path;
  8531. struct btrfs_block_group_cache *block_group;
  8532. struct btrfs_free_cluster *cluster;
  8533. struct btrfs_root *tree_root = root->fs_info->tree_root;
  8534. struct btrfs_key key;
  8535. struct inode *inode;
  8536. struct kobject *kobj = NULL;
  8537. int ret;
  8538. int index;
  8539. int factor;
  8540. struct btrfs_caching_control *caching_ctl = NULL;
  8541. bool remove_em;
  8542. root = root->fs_info->extent_root;
  8543. block_group = btrfs_lookup_block_group(root->fs_info, group_start);
  8544. BUG_ON(!block_group);
  8545. BUG_ON(!block_group->ro);
  8546. /*
  8547. * Free the reserved super bytes from this block group before
  8548. * remove it.
  8549. */
  8550. free_excluded_extents(root, block_group);
  8551. memcpy(&key, &block_group->key, sizeof(key));
  8552. index = get_block_group_index(block_group);
  8553. if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
  8554. BTRFS_BLOCK_GROUP_RAID1 |
  8555. BTRFS_BLOCK_GROUP_RAID10))
  8556. factor = 2;
  8557. else
  8558. factor = 1;
  8559. /* make sure this block group isn't part of an allocation cluster */
  8560. cluster = &root->fs_info->data_alloc_cluster;
  8561. spin_lock(&cluster->refill_lock);
  8562. btrfs_return_cluster_to_free_space(block_group, cluster);
  8563. spin_unlock(&cluster->refill_lock);
  8564. /*
  8565. * make sure this block group isn't part of a metadata
  8566. * allocation cluster
  8567. */
  8568. cluster = &root->fs_info->meta_alloc_cluster;
  8569. spin_lock(&cluster->refill_lock);
  8570. btrfs_return_cluster_to_free_space(block_group, cluster);
  8571. spin_unlock(&cluster->refill_lock);
  8572. path = btrfs_alloc_path();
  8573. if (!path) {
  8574. ret = -ENOMEM;
  8575. goto out;
  8576. }
  8577. /*
  8578. * get the inode first so any iput calls done for the io_list
  8579. * aren't the final iput (no unlinks allowed now)
  8580. */
  8581. inode = lookup_free_space_inode(tree_root, block_group, path);
  8582. mutex_lock(&trans->transaction->cache_write_mutex);
  8583. /*
  8584. * make sure our free spache cache IO is done before remove the
  8585. * free space inode
  8586. */
  8587. spin_lock(&trans->transaction->dirty_bgs_lock);
  8588. if (!list_empty(&block_group->io_list)) {
  8589. list_del_init(&block_group->io_list);
  8590. WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
  8591. spin_unlock(&trans->transaction->dirty_bgs_lock);
  8592. btrfs_wait_cache_io(root, trans, block_group,
  8593. &block_group->io_ctl, path,
  8594. block_group->key.objectid);
  8595. btrfs_put_block_group(block_group);
  8596. spin_lock(&trans->transaction->dirty_bgs_lock);
  8597. }
  8598. if (!list_empty(&block_group->dirty_list)) {
  8599. list_del_init(&block_group->dirty_list);
  8600. btrfs_put_block_group(block_group);
  8601. }
  8602. spin_unlock(&trans->transaction->dirty_bgs_lock);
  8603. mutex_unlock(&trans->transaction->cache_write_mutex);
  8604. if (!IS_ERR(inode)) {
  8605. ret = btrfs_orphan_add(trans, inode);
  8606. if (ret) {
  8607. btrfs_add_delayed_iput(inode);
  8608. goto out;
  8609. }
  8610. clear_nlink(inode);
  8611. /* One for the block groups ref */
  8612. spin_lock(&block_group->lock);
  8613. if (block_group->iref) {
  8614. block_group->iref = 0;
  8615. block_group->inode = NULL;
  8616. spin_unlock(&block_group->lock);
  8617. iput(inode);
  8618. } else {
  8619. spin_unlock(&block_group->lock);
  8620. }
  8621. /* One for our lookup ref */
  8622. btrfs_add_delayed_iput(inode);
  8623. }
  8624. key.objectid = BTRFS_FREE_SPACE_OBJECTID;
  8625. key.offset = block_group->key.objectid;
  8626. key.type = 0;
  8627. ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
  8628. if (ret < 0)
  8629. goto out;
  8630. if (ret > 0)
  8631. btrfs_release_path(path);
  8632. if (ret == 0) {
  8633. ret = btrfs_del_item(trans, tree_root, path);
  8634. if (ret)
  8635. goto out;
  8636. btrfs_release_path(path);
  8637. }
  8638. spin_lock(&root->fs_info->block_group_cache_lock);
  8639. rb_erase(&block_group->cache_node,
  8640. &root->fs_info->block_group_cache_tree);
  8641. RB_CLEAR_NODE(&block_group->cache_node);
  8642. if (root->fs_info->first_logical_byte == block_group->key.objectid)
  8643. root->fs_info->first_logical_byte = (u64)-1;
  8644. spin_unlock(&root->fs_info->block_group_cache_lock);
  8645. down_write(&block_group->space_info->groups_sem);
  8646. /*
  8647. * we must use list_del_init so people can check to see if they
  8648. * are still on the list after taking the semaphore
  8649. */
  8650. list_del_init(&block_group->list);
  8651. if (list_empty(&block_group->space_info->block_groups[index])) {
  8652. kobj = block_group->space_info->block_group_kobjs[index];
  8653. block_group->space_info->block_group_kobjs[index] = NULL;
  8654. clear_avail_alloc_bits(root->fs_info, block_group->flags);
  8655. }
  8656. up_write(&block_group->space_info->groups_sem);
  8657. if (kobj) {
  8658. kobject_del(kobj);
  8659. kobject_put(kobj);
  8660. }
  8661. if (block_group->has_caching_ctl)
  8662. caching_ctl = get_caching_control(block_group);
  8663. if (block_group->cached == BTRFS_CACHE_STARTED)
  8664. wait_block_group_cache_done(block_group);
  8665. if (block_group->has_caching_ctl) {
  8666. down_write(&root->fs_info->commit_root_sem);
  8667. if (!caching_ctl) {
  8668. struct btrfs_caching_control *ctl;
  8669. list_for_each_entry(ctl,
  8670. &root->fs_info->caching_block_groups, list)
  8671. if (ctl->block_group == block_group) {
  8672. caching_ctl = ctl;
  8673. atomic_inc(&caching_ctl->count);
  8674. break;
  8675. }
  8676. }
  8677. if (caching_ctl)
  8678. list_del_init(&caching_ctl->list);
  8679. up_write(&root->fs_info->commit_root_sem);
  8680. if (caching_ctl) {
  8681. /* Once for the caching bgs list and once for us. */
  8682. put_caching_control(caching_ctl);
  8683. put_caching_control(caching_ctl);
  8684. }
  8685. }
  8686. spin_lock(&trans->transaction->dirty_bgs_lock);
  8687. if (!list_empty(&block_group->dirty_list)) {
  8688. WARN_ON(1);
  8689. }
  8690. if (!list_empty(&block_group->io_list)) {
  8691. WARN_ON(1);
  8692. }
  8693. spin_unlock(&trans->transaction->dirty_bgs_lock);
  8694. btrfs_remove_free_space_cache(block_group);
  8695. spin_lock(&block_group->space_info->lock);
  8696. list_del_init(&block_group->ro_list);
  8697. if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
  8698. WARN_ON(block_group->space_info->total_bytes
  8699. < block_group->key.offset);
  8700. WARN_ON(block_group->space_info->bytes_readonly
  8701. < block_group->key.offset);
  8702. WARN_ON(block_group->space_info->disk_total
  8703. < block_group->key.offset * factor);
  8704. }
  8705. block_group->space_info->total_bytes -= block_group->key.offset;
  8706. block_group->space_info->bytes_readonly -= block_group->key.offset;
  8707. block_group->space_info->disk_total -= block_group->key.offset * factor;
  8708. spin_unlock(&block_group->space_info->lock);
  8709. memcpy(&key, &block_group->key, sizeof(key));
  8710. lock_chunks(root);
  8711. if (!list_empty(&em->list)) {
  8712. /* We're in the transaction->pending_chunks list. */
  8713. free_extent_map(em);
  8714. }
  8715. spin_lock(&block_group->lock);
  8716. block_group->removed = 1;
  8717. /*
  8718. * At this point trimming can't start on this block group, because we
  8719. * removed the block group from the tree fs_info->block_group_cache_tree
  8720. * so no one can't find it anymore and even if someone already got this
  8721. * block group before we removed it from the rbtree, they have already
  8722. * incremented block_group->trimming - if they didn't, they won't find
  8723. * any free space entries because we already removed them all when we
  8724. * called btrfs_remove_free_space_cache().
  8725. *
  8726. * And we must not remove the extent map from the fs_info->mapping_tree
  8727. * to prevent the same logical address range and physical device space
  8728. * ranges from being reused for a new block group. This is because our
  8729. * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
  8730. * completely transactionless, so while it is trimming a range the
  8731. * currently running transaction might finish and a new one start,
  8732. * allowing for new block groups to be created that can reuse the same
  8733. * physical device locations unless we take this special care.
  8734. *
  8735. * There may also be an implicit trim operation if the file system
  8736. * is mounted with -odiscard. The same protections must remain
  8737. * in place until the extents have been discarded completely when
  8738. * the transaction commit has completed.
  8739. */
  8740. remove_em = (atomic_read(&block_group->trimming) == 0);
  8741. /*
  8742. * Make sure a trimmer task always sees the em in the pinned_chunks list
  8743. * if it sees block_group->removed == 1 (needs to lock block_group->lock
  8744. * before checking block_group->removed).
  8745. */
  8746. if (!remove_em) {
  8747. /*
  8748. * Our em might be in trans->transaction->pending_chunks which
  8749. * is protected by fs_info->chunk_mutex ([lock|unlock]_chunks),
  8750. * and so is the fs_info->pinned_chunks list.
  8751. *
  8752. * So at this point we must be holding the chunk_mutex to avoid
  8753. * any races with chunk allocation (more specifically at
  8754. * volumes.c:contains_pending_extent()), to ensure it always
  8755. * sees the em, either in the pending_chunks list or in the
  8756. * pinned_chunks list.
  8757. */
  8758. list_move_tail(&em->list, &root->fs_info->pinned_chunks);
  8759. }
  8760. spin_unlock(&block_group->lock);
  8761. if (remove_em) {
  8762. struct extent_map_tree *em_tree;
  8763. em_tree = &root->fs_info->mapping_tree.map_tree;
  8764. write_lock(&em_tree->lock);
  8765. /*
  8766. * The em might be in the pending_chunks list, so make sure the
  8767. * chunk mutex is locked, since remove_extent_mapping() will
  8768. * delete us from that list.
  8769. */
  8770. remove_extent_mapping(em_tree, em);
  8771. write_unlock(&em_tree->lock);
  8772. /* once for the tree */
  8773. free_extent_map(em);
  8774. }
  8775. unlock_chunks(root);
  8776. btrfs_put_block_group(block_group);
  8777. btrfs_put_block_group(block_group);
  8778. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  8779. if (ret > 0)
  8780. ret = -EIO;
  8781. if (ret < 0)
  8782. goto out;
  8783. ret = btrfs_del_item(trans, root, path);
  8784. out:
  8785. btrfs_free_path(path);
  8786. return ret;
  8787. }
  8788. /*
  8789. * Process the unused_bgs list and remove any that don't have any allocated
  8790. * space inside of them.
  8791. */
  8792. void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
  8793. {
  8794. struct btrfs_block_group_cache *block_group;
  8795. struct btrfs_space_info *space_info;
  8796. struct btrfs_root *root = fs_info->extent_root;
  8797. struct btrfs_trans_handle *trans;
  8798. int ret = 0;
  8799. if (!fs_info->open)
  8800. return;
  8801. spin_lock(&fs_info->unused_bgs_lock);
  8802. while (!list_empty(&fs_info->unused_bgs)) {
  8803. u64 start, end;
  8804. int trimming;
  8805. block_group = list_first_entry(&fs_info->unused_bgs,
  8806. struct btrfs_block_group_cache,
  8807. bg_list);
  8808. space_info = block_group->space_info;
  8809. list_del_init(&block_group->bg_list);
  8810. if (ret || btrfs_mixed_space_info(space_info)) {
  8811. btrfs_put_block_group(block_group);
  8812. continue;
  8813. }
  8814. spin_unlock(&fs_info->unused_bgs_lock);
  8815. mutex_lock(&root->fs_info->delete_unused_bgs_mutex);
  8816. /* Don't want to race with allocators so take the groups_sem */
  8817. down_write(&space_info->groups_sem);
  8818. spin_lock(&block_group->lock);
  8819. if (block_group->reserved ||
  8820. btrfs_block_group_used(&block_group->item) ||
  8821. block_group->ro) {
  8822. /*
  8823. * We want to bail if we made new allocations or have
  8824. * outstanding allocations in this block group. We do
  8825. * the ro check in case balance is currently acting on
  8826. * this block group.
  8827. */
  8828. spin_unlock(&block_group->lock);
  8829. up_write(&space_info->groups_sem);
  8830. goto next;
  8831. }
  8832. spin_unlock(&block_group->lock);
  8833. /* We don't want to force the issue, only flip if it's ok. */
  8834. ret = inc_block_group_ro(block_group, 0);
  8835. up_write(&space_info->groups_sem);
  8836. if (ret < 0) {
  8837. ret = 0;
  8838. goto next;
  8839. }
  8840. /*
  8841. * Want to do this before we do anything else so we can recover
  8842. * properly if we fail to join the transaction.
  8843. */
  8844. /* 1 for btrfs_orphan_reserve_metadata() */
  8845. trans = btrfs_start_transaction(root, 1);
  8846. if (IS_ERR(trans)) {
  8847. btrfs_dec_block_group_ro(root, block_group);
  8848. ret = PTR_ERR(trans);
  8849. goto next;
  8850. }
  8851. /*
  8852. * We could have pending pinned extents for this block group,
  8853. * just delete them, we don't care about them anymore.
  8854. */
  8855. start = block_group->key.objectid;
  8856. end = start + block_group->key.offset - 1;
  8857. /*
  8858. * Hold the unused_bg_unpin_mutex lock to avoid racing with
  8859. * btrfs_finish_extent_commit(). If we are at transaction N,
  8860. * another task might be running finish_extent_commit() for the
  8861. * previous transaction N - 1, and have seen a range belonging
  8862. * to the block group in freed_extents[] before we were able to
  8863. * clear the whole block group range from freed_extents[]. This
  8864. * means that task can lookup for the block group after we
  8865. * unpinned it from freed_extents[] and removed it, leading to
  8866. * a BUG_ON() at btrfs_unpin_extent_range().
  8867. */
  8868. mutex_lock(&fs_info->unused_bg_unpin_mutex);
  8869. ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
  8870. EXTENT_DIRTY, GFP_NOFS);
  8871. if (ret) {
  8872. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  8873. btrfs_dec_block_group_ro(root, block_group);
  8874. goto end_trans;
  8875. }
  8876. ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
  8877. EXTENT_DIRTY, GFP_NOFS);
  8878. if (ret) {
  8879. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  8880. btrfs_dec_block_group_ro(root, block_group);
  8881. goto end_trans;
  8882. }
  8883. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  8884. /* Reset pinned so btrfs_put_block_group doesn't complain */
  8885. spin_lock(&space_info->lock);
  8886. spin_lock(&block_group->lock);
  8887. space_info->bytes_pinned -= block_group->pinned;
  8888. space_info->bytes_readonly += block_group->pinned;
  8889. percpu_counter_add(&space_info->total_bytes_pinned,
  8890. -block_group->pinned);
  8891. block_group->pinned = 0;
  8892. spin_unlock(&block_group->lock);
  8893. spin_unlock(&space_info->lock);
  8894. /* DISCARD can flip during remount */
  8895. trimming = btrfs_test_opt(root, DISCARD);
  8896. /* Implicit trim during transaction commit. */
  8897. if (trimming)
  8898. btrfs_get_block_group_trimming(block_group);
  8899. /*
  8900. * Btrfs_remove_chunk will abort the transaction if things go
  8901. * horribly wrong.
  8902. */
  8903. ret = btrfs_remove_chunk(trans, root,
  8904. block_group->key.objectid);
  8905. if (ret) {
  8906. if (trimming)
  8907. btrfs_put_block_group_trimming(block_group);
  8908. goto end_trans;
  8909. }
  8910. /*
  8911. * If we're not mounted with -odiscard, we can just forget
  8912. * about this block group. Otherwise we'll need to wait
  8913. * until transaction commit to do the actual discard.
  8914. */
  8915. if (trimming) {
  8916. WARN_ON(!list_empty(&block_group->bg_list));
  8917. spin_lock(&trans->transaction->deleted_bgs_lock);
  8918. list_move(&block_group->bg_list,
  8919. &trans->transaction->deleted_bgs);
  8920. spin_unlock(&trans->transaction->deleted_bgs_lock);
  8921. btrfs_get_block_group(block_group);
  8922. }
  8923. end_trans:
  8924. btrfs_end_transaction(trans, root);
  8925. next:
  8926. mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
  8927. btrfs_put_block_group(block_group);
  8928. spin_lock(&fs_info->unused_bgs_lock);
  8929. }
  8930. spin_unlock(&fs_info->unused_bgs_lock);
  8931. }
  8932. int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
  8933. {
  8934. struct btrfs_space_info *space_info;
  8935. struct btrfs_super_block *disk_super;
  8936. u64 features;
  8937. u64 flags;
  8938. int mixed = 0;
  8939. int ret;
  8940. disk_super = fs_info->super_copy;
  8941. if (!btrfs_super_root(disk_super))
  8942. return 1;
  8943. features = btrfs_super_incompat_flags(disk_super);
  8944. if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
  8945. mixed = 1;
  8946. flags = BTRFS_BLOCK_GROUP_SYSTEM;
  8947. ret = update_space_info(fs_info, flags, 0, 0, &space_info);
  8948. if (ret)
  8949. goto out;
  8950. if (mixed) {
  8951. flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
  8952. ret = update_space_info(fs_info, flags, 0, 0, &space_info);
  8953. } else {
  8954. flags = BTRFS_BLOCK_GROUP_METADATA;
  8955. ret = update_space_info(fs_info, flags, 0, 0, &space_info);
  8956. if (ret)
  8957. goto out;
  8958. flags = BTRFS_BLOCK_GROUP_DATA;
  8959. ret = update_space_info(fs_info, flags, 0, 0, &space_info);
  8960. }
  8961. out:
  8962. return ret;
  8963. }
  8964. int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
  8965. {
  8966. return unpin_extent_range(root, start, end, false);
  8967. }
  8968. /*
  8969. * It used to be that old block groups would be left around forever.
  8970. * Iterating over them would be enough to trim unused space. Since we
  8971. * now automatically remove them, we also need to iterate over unallocated
  8972. * space.
  8973. *
  8974. * We don't want a transaction for this since the discard may take a
  8975. * substantial amount of time. We don't require that a transaction be
  8976. * running, but we do need to take a running transaction into account
  8977. * to ensure that we're not discarding chunks that were released in
  8978. * the current transaction.
  8979. *
  8980. * Holding the chunks lock will prevent other threads from allocating
  8981. * or releasing chunks, but it won't prevent a running transaction
  8982. * from committing and releasing the memory that the pending chunks
  8983. * list head uses. For that, we need to take a reference to the
  8984. * transaction.
  8985. */
  8986. static int btrfs_trim_free_extents(struct btrfs_device *device,
  8987. u64 minlen, u64 *trimmed)
  8988. {
  8989. u64 start = 0, len = 0;
  8990. int ret;
  8991. *trimmed = 0;
  8992. /* Not writeable = nothing to do. */
  8993. if (!device->writeable)
  8994. return 0;
  8995. /* No free space = nothing to do. */
  8996. if (device->total_bytes <= device->bytes_used)
  8997. return 0;
  8998. ret = 0;
  8999. while (1) {
  9000. struct btrfs_fs_info *fs_info = device->dev_root->fs_info;
  9001. struct btrfs_transaction *trans;
  9002. u64 bytes;
  9003. ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
  9004. if (ret)
  9005. return ret;
  9006. down_read(&fs_info->commit_root_sem);
  9007. spin_lock(&fs_info->trans_lock);
  9008. trans = fs_info->running_transaction;
  9009. if (trans)
  9010. atomic_inc(&trans->use_count);
  9011. spin_unlock(&fs_info->trans_lock);
  9012. ret = find_free_dev_extent_start(trans, device, minlen, start,
  9013. &start, &len);
  9014. if (trans)
  9015. btrfs_put_transaction(trans);
  9016. if (ret) {
  9017. up_read(&fs_info->commit_root_sem);
  9018. mutex_unlock(&fs_info->chunk_mutex);
  9019. if (ret == -ENOSPC)
  9020. ret = 0;
  9021. break;
  9022. }
  9023. ret = btrfs_issue_discard(device->bdev, start, len, &bytes);
  9024. up_read(&fs_info->commit_root_sem);
  9025. mutex_unlock(&fs_info->chunk_mutex);
  9026. if (ret)
  9027. break;
  9028. start += len;
  9029. *trimmed += bytes;
  9030. if (fatal_signal_pending(current)) {
  9031. ret = -ERESTARTSYS;
  9032. break;
  9033. }
  9034. cond_resched();
  9035. }
  9036. return ret;
  9037. }
  9038. int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
  9039. {
  9040. struct btrfs_fs_info *fs_info = root->fs_info;
  9041. struct btrfs_block_group_cache *cache = NULL;
  9042. struct btrfs_device *device;
  9043. struct list_head *devices;
  9044. u64 group_trimmed;
  9045. u64 start;
  9046. u64 end;
  9047. u64 trimmed = 0;
  9048. u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
  9049. int ret = 0;
  9050. /*
  9051. * try to trim all FS space, our block group may start from non-zero.
  9052. */
  9053. if (range->len == total_bytes)
  9054. cache = btrfs_lookup_first_block_group(fs_info, range->start);
  9055. else
  9056. cache = btrfs_lookup_block_group(fs_info, range->start);
  9057. while (cache) {
  9058. if (cache->key.objectid >= (range->start + range->len)) {
  9059. btrfs_put_block_group(cache);
  9060. break;
  9061. }
  9062. start = max(range->start, cache->key.objectid);
  9063. end = min(range->start + range->len,
  9064. cache->key.objectid + cache->key.offset);
  9065. if (end - start >= range->minlen) {
  9066. if (!block_group_cache_done(cache)) {
  9067. ret = cache_block_group(cache, 0);
  9068. if (ret) {
  9069. btrfs_put_block_group(cache);
  9070. break;
  9071. }
  9072. ret = wait_block_group_cache_done(cache);
  9073. if (ret) {
  9074. btrfs_put_block_group(cache);
  9075. break;
  9076. }
  9077. }
  9078. ret = btrfs_trim_block_group(cache,
  9079. &group_trimmed,
  9080. start,
  9081. end,
  9082. range->minlen);
  9083. trimmed += group_trimmed;
  9084. if (ret) {
  9085. btrfs_put_block_group(cache);
  9086. break;
  9087. }
  9088. }
  9089. cache = next_block_group(fs_info->tree_root, cache);
  9090. }
  9091. mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
  9092. devices = &root->fs_info->fs_devices->alloc_list;
  9093. list_for_each_entry(device, devices, dev_alloc_list) {
  9094. ret = btrfs_trim_free_extents(device, range->minlen,
  9095. &group_trimmed);
  9096. if (ret)
  9097. break;
  9098. trimmed += group_trimmed;
  9099. }
  9100. mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
  9101. range->len = trimmed;
  9102. return ret;
  9103. }
  9104. /*
  9105. * btrfs_{start,end}_write_no_snapshoting() are similar to
  9106. * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
  9107. * data into the page cache through nocow before the subvolume is snapshoted,
  9108. * but flush the data into disk after the snapshot creation, or to prevent
  9109. * operations while snapshoting is ongoing and that cause the snapshot to be
  9110. * inconsistent (writes followed by expanding truncates for example).
  9111. */
  9112. void btrfs_end_write_no_snapshoting(struct btrfs_root *root)
  9113. {
  9114. percpu_counter_dec(&root->subv_writers->counter);
  9115. /*
  9116. * Make sure counter is updated before we wake up
  9117. * waiters.
  9118. */
  9119. smp_mb();
  9120. if (waitqueue_active(&root->subv_writers->wait))
  9121. wake_up(&root->subv_writers->wait);
  9122. }
  9123. int btrfs_start_write_no_snapshoting(struct btrfs_root *root)
  9124. {
  9125. if (atomic_read(&root->will_be_snapshoted))
  9126. return 0;
  9127. percpu_counter_inc(&root->subv_writers->counter);
  9128. /*
  9129. * Make sure counter is updated before we check for snapshot creation.
  9130. */
  9131. smp_mb();
  9132. if (atomic_read(&root->will_be_snapshoted)) {
  9133. btrfs_end_write_no_snapshoting(root);
  9134. return 0;
  9135. }
  9136. return 1;
  9137. }