extent-tree.c 293 KB

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