extent-tree.c 287 KB

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