extent-tree.c 287 KB

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