extent-tree.c 303 KB

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