extent-tree.c 300 KB

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