extent-tree.c 280 KB

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