volumes.c 193 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2007 Oracle. All rights reserved.
  4. */
  5. #include <linux/sched.h>
  6. #include <linux/bio.h>
  7. #include <linux/slab.h>
  8. #include <linux/buffer_head.h>
  9. #include <linux/blkdev.h>
  10. #include <linux/iocontext.h>
  11. #include <linux/capability.h>
  12. #include <linux/ratelimit.h>
  13. #include <linux/kthread.h>
  14. #include <linux/raid/pq.h>
  15. #include <linux/semaphore.h>
  16. #include <linux/uuid.h>
  17. #include <linux/list_sort.h>
  18. #include <asm/div64.h>
  19. #include "ctree.h"
  20. #include "extent_map.h"
  21. #include "disk-io.h"
  22. #include "transaction.h"
  23. #include "print-tree.h"
  24. #include "volumes.h"
  25. #include "raid56.h"
  26. #include "async-thread.h"
  27. #include "check-integrity.h"
  28. #include "rcu-string.h"
  29. #include "math.h"
  30. #include "dev-replace.h"
  31. #include "sysfs.h"
  32. const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
  33. [BTRFS_RAID_RAID10] = {
  34. .sub_stripes = 2,
  35. .dev_stripes = 1,
  36. .devs_max = 0, /* 0 == as many as possible */
  37. .devs_min = 4,
  38. .tolerated_failures = 1,
  39. .devs_increment = 2,
  40. .ncopies = 2,
  41. .raid_name = "raid10",
  42. .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
  43. .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
  44. },
  45. [BTRFS_RAID_RAID1] = {
  46. .sub_stripes = 1,
  47. .dev_stripes = 1,
  48. .devs_max = 2,
  49. .devs_min = 2,
  50. .tolerated_failures = 1,
  51. .devs_increment = 2,
  52. .ncopies = 2,
  53. .raid_name = "raid1",
  54. .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
  55. .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
  56. },
  57. [BTRFS_RAID_DUP] = {
  58. .sub_stripes = 1,
  59. .dev_stripes = 2,
  60. .devs_max = 1,
  61. .devs_min = 1,
  62. .tolerated_failures = 0,
  63. .devs_increment = 1,
  64. .ncopies = 2,
  65. .raid_name = "dup",
  66. .bg_flag = BTRFS_BLOCK_GROUP_DUP,
  67. .mindev_error = 0,
  68. },
  69. [BTRFS_RAID_RAID0] = {
  70. .sub_stripes = 1,
  71. .dev_stripes = 1,
  72. .devs_max = 0,
  73. .devs_min = 2,
  74. .tolerated_failures = 0,
  75. .devs_increment = 1,
  76. .ncopies = 1,
  77. .raid_name = "raid0",
  78. .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
  79. .mindev_error = 0,
  80. },
  81. [BTRFS_RAID_SINGLE] = {
  82. .sub_stripes = 1,
  83. .dev_stripes = 1,
  84. .devs_max = 1,
  85. .devs_min = 1,
  86. .tolerated_failures = 0,
  87. .devs_increment = 1,
  88. .ncopies = 1,
  89. .raid_name = "single",
  90. .bg_flag = 0,
  91. .mindev_error = 0,
  92. },
  93. [BTRFS_RAID_RAID5] = {
  94. .sub_stripes = 1,
  95. .dev_stripes = 1,
  96. .devs_max = 0,
  97. .devs_min = 2,
  98. .tolerated_failures = 1,
  99. .devs_increment = 1,
  100. .ncopies = 2,
  101. .raid_name = "raid5",
  102. .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
  103. .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
  104. },
  105. [BTRFS_RAID_RAID6] = {
  106. .sub_stripes = 1,
  107. .dev_stripes = 1,
  108. .devs_max = 0,
  109. .devs_min = 3,
  110. .tolerated_failures = 2,
  111. .devs_increment = 1,
  112. .ncopies = 3,
  113. .raid_name = "raid6",
  114. .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
  115. .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
  116. },
  117. };
  118. const char *get_raid_name(enum btrfs_raid_types type)
  119. {
  120. if (type >= BTRFS_NR_RAID_TYPES)
  121. return NULL;
  122. return btrfs_raid_array[type].raid_name;
  123. }
  124. static int init_first_rw_device(struct btrfs_trans_handle *trans,
  125. struct btrfs_fs_info *fs_info);
  126. static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
  127. static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
  128. static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
  129. static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
  130. static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
  131. enum btrfs_map_op op,
  132. u64 logical, u64 *length,
  133. struct btrfs_bio **bbio_ret,
  134. int mirror_num, int need_raid_map);
  135. /*
  136. * Device locking
  137. * ==============
  138. *
  139. * There are several mutexes that protect manipulation of devices and low-level
  140. * structures like chunks but not block groups, extents or files
  141. *
  142. * uuid_mutex (global lock)
  143. * ------------------------
  144. * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
  145. * the SCAN_DEV ioctl registration or from mount either implicitly (the first
  146. * device) or requested by the device= mount option
  147. *
  148. * the mutex can be very coarse and can cover long-running operations
  149. *
  150. * protects: updates to fs_devices counters like missing devices, rw devices,
  151. * seeding, structure cloning, openning/closing devices at mount/umount time
  152. *
  153. * global::fs_devs - add, remove, updates to the global list
  154. *
  155. * does not protect: manipulation of the fs_devices::devices list!
  156. *
  157. * btrfs_device::name - renames (write side), read is RCU
  158. *
  159. * fs_devices::device_list_mutex (per-fs, with RCU)
  160. * ------------------------------------------------
  161. * protects updates to fs_devices::devices, ie. adding and deleting
  162. *
  163. * simple list traversal with read-only actions can be done with RCU protection
  164. *
  165. * may be used to exclude some operations from running concurrently without any
  166. * modifications to the list (see write_all_supers)
  167. *
  168. * balance_mutex
  169. * -------------
  170. * protects balance structures (status, state) and context accessed from
  171. * several places (internally, ioctl)
  172. *
  173. * chunk_mutex
  174. * -----------
  175. * protects chunks, adding or removing during allocation, trim or when a new
  176. * device is added/removed
  177. *
  178. * cleaner_mutex
  179. * -------------
  180. * a big lock that is held by the cleaner thread and prevents running subvolume
  181. * cleaning together with relocation or delayed iputs
  182. *
  183. *
  184. * Lock nesting
  185. * ============
  186. *
  187. * uuid_mutex
  188. * volume_mutex
  189. * device_list_mutex
  190. * chunk_mutex
  191. * balance_mutex
  192. *
  193. *
  194. * Exclusive operations, BTRFS_FS_EXCL_OP
  195. * ======================================
  196. *
  197. * Maintains the exclusivity of the following operations that apply to the
  198. * whole filesystem and cannot run in parallel.
  199. *
  200. * - Balance (*)
  201. * - Device add
  202. * - Device remove
  203. * - Device replace (*)
  204. * - Resize
  205. *
  206. * The device operations (as above) can be in one of the following states:
  207. *
  208. * - Running state
  209. * - Paused state
  210. * - Completed state
  211. *
  212. * Only device operations marked with (*) can go into the Paused state for the
  213. * following reasons:
  214. *
  215. * - ioctl (only Balance can be Paused through ioctl)
  216. * - filesystem remounted as read-only
  217. * - filesystem unmounted and mounted as read-only
  218. * - system power-cycle and filesystem mounted as read-only
  219. * - filesystem or device errors leading to forced read-only
  220. *
  221. * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
  222. * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
  223. * A device operation in Paused or Running state can be canceled or resumed
  224. * either by ioctl (Balance only) or when remounted as read-write.
  225. * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
  226. * completed.
  227. */
  228. DEFINE_MUTEX(uuid_mutex);
  229. static LIST_HEAD(fs_uuids);
  230. struct list_head *btrfs_get_fs_uuids(void)
  231. {
  232. return &fs_uuids;
  233. }
  234. /*
  235. * alloc_fs_devices - allocate struct btrfs_fs_devices
  236. * @fsid: if not NULL, copy the uuid to fs_devices::fsid
  237. *
  238. * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
  239. * The returned struct is not linked onto any lists and can be destroyed with
  240. * kfree() right away.
  241. */
  242. static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
  243. {
  244. struct btrfs_fs_devices *fs_devs;
  245. fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
  246. if (!fs_devs)
  247. return ERR_PTR(-ENOMEM);
  248. mutex_init(&fs_devs->device_list_mutex);
  249. INIT_LIST_HEAD(&fs_devs->devices);
  250. INIT_LIST_HEAD(&fs_devs->resized_devices);
  251. INIT_LIST_HEAD(&fs_devs->alloc_list);
  252. INIT_LIST_HEAD(&fs_devs->fs_list);
  253. if (fsid)
  254. memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
  255. return fs_devs;
  256. }
  257. void btrfs_free_device(struct btrfs_device *device)
  258. {
  259. rcu_string_free(device->name);
  260. bio_put(device->flush_bio);
  261. kfree(device);
  262. }
  263. static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
  264. {
  265. struct btrfs_device *device;
  266. WARN_ON(fs_devices->opened);
  267. while (!list_empty(&fs_devices->devices)) {
  268. device = list_entry(fs_devices->devices.next,
  269. struct btrfs_device, dev_list);
  270. list_del(&device->dev_list);
  271. btrfs_free_device(device);
  272. }
  273. kfree(fs_devices);
  274. }
  275. static void btrfs_kobject_uevent(struct block_device *bdev,
  276. enum kobject_action action)
  277. {
  278. int ret;
  279. ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
  280. if (ret)
  281. pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
  282. action,
  283. kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
  284. &disk_to_dev(bdev->bd_disk)->kobj);
  285. }
  286. void __exit btrfs_cleanup_fs_uuids(void)
  287. {
  288. struct btrfs_fs_devices *fs_devices;
  289. while (!list_empty(&fs_uuids)) {
  290. fs_devices = list_entry(fs_uuids.next,
  291. struct btrfs_fs_devices, fs_list);
  292. list_del(&fs_devices->fs_list);
  293. free_fs_devices(fs_devices);
  294. }
  295. }
  296. /*
  297. * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
  298. * Returned struct is not linked onto any lists and must be destroyed using
  299. * btrfs_free_device.
  300. */
  301. static struct btrfs_device *__alloc_device(void)
  302. {
  303. struct btrfs_device *dev;
  304. dev = kzalloc(sizeof(*dev), GFP_KERNEL);
  305. if (!dev)
  306. return ERR_PTR(-ENOMEM);
  307. /*
  308. * Preallocate a bio that's always going to be used for flushing device
  309. * barriers and matches the device lifespan
  310. */
  311. dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
  312. if (!dev->flush_bio) {
  313. kfree(dev);
  314. return ERR_PTR(-ENOMEM);
  315. }
  316. INIT_LIST_HEAD(&dev->dev_list);
  317. INIT_LIST_HEAD(&dev->dev_alloc_list);
  318. INIT_LIST_HEAD(&dev->resized_list);
  319. spin_lock_init(&dev->io_lock);
  320. atomic_set(&dev->reada_in_flight, 0);
  321. atomic_set(&dev->dev_stats_ccnt, 0);
  322. btrfs_device_data_ordered_init(dev);
  323. INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
  324. INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
  325. return dev;
  326. }
  327. /*
  328. * Find a device specified by @devid or @uuid in the list of @fs_devices, or
  329. * return NULL.
  330. *
  331. * If devid and uuid are both specified, the match must be exact, otherwise
  332. * only devid is used.
  333. */
  334. static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
  335. u64 devid, const u8 *uuid)
  336. {
  337. struct btrfs_device *dev;
  338. list_for_each_entry(dev, &fs_devices->devices, dev_list) {
  339. if (dev->devid == devid &&
  340. (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
  341. return dev;
  342. }
  343. }
  344. return NULL;
  345. }
  346. static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
  347. {
  348. struct btrfs_fs_devices *fs_devices;
  349. list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
  350. if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
  351. return fs_devices;
  352. }
  353. return NULL;
  354. }
  355. static int
  356. btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
  357. int flush, struct block_device **bdev,
  358. struct buffer_head **bh)
  359. {
  360. int ret;
  361. *bdev = blkdev_get_by_path(device_path, flags, holder);
  362. if (IS_ERR(*bdev)) {
  363. ret = PTR_ERR(*bdev);
  364. goto error;
  365. }
  366. if (flush)
  367. filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
  368. ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
  369. if (ret) {
  370. blkdev_put(*bdev, flags);
  371. goto error;
  372. }
  373. invalidate_bdev(*bdev);
  374. *bh = btrfs_read_dev_super(*bdev);
  375. if (IS_ERR(*bh)) {
  376. ret = PTR_ERR(*bh);
  377. blkdev_put(*bdev, flags);
  378. goto error;
  379. }
  380. return 0;
  381. error:
  382. *bdev = NULL;
  383. *bh = NULL;
  384. return ret;
  385. }
  386. static void requeue_list(struct btrfs_pending_bios *pending_bios,
  387. struct bio *head, struct bio *tail)
  388. {
  389. struct bio *old_head;
  390. old_head = pending_bios->head;
  391. pending_bios->head = head;
  392. if (pending_bios->tail)
  393. tail->bi_next = old_head;
  394. else
  395. pending_bios->tail = tail;
  396. }
  397. /*
  398. * we try to collect pending bios for a device so we don't get a large
  399. * number of procs sending bios down to the same device. This greatly
  400. * improves the schedulers ability to collect and merge the bios.
  401. *
  402. * But, it also turns into a long list of bios to process and that is sure
  403. * to eventually make the worker thread block. The solution here is to
  404. * make some progress and then put this work struct back at the end of
  405. * the list if the block device is congested. This way, multiple devices
  406. * can make progress from a single worker thread.
  407. */
  408. static noinline void run_scheduled_bios(struct btrfs_device *device)
  409. {
  410. struct btrfs_fs_info *fs_info = device->fs_info;
  411. struct bio *pending;
  412. struct backing_dev_info *bdi;
  413. struct btrfs_pending_bios *pending_bios;
  414. struct bio *tail;
  415. struct bio *cur;
  416. int again = 0;
  417. unsigned long num_run;
  418. unsigned long batch_run = 0;
  419. unsigned long last_waited = 0;
  420. int force_reg = 0;
  421. int sync_pending = 0;
  422. struct blk_plug plug;
  423. /*
  424. * this function runs all the bios we've collected for
  425. * a particular device. We don't want to wander off to
  426. * another device without first sending all of these down.
  427. * So, setup a plug here and finish it off before we return
  428. */
  429. blk_start_plug(&plug);
  430. bdi = device->bdev->bd_bdi;
  431. loop:
  432. spin_lock(&device->io_lock);
  433. loop_lock:
  434. num_run = 0;
  435. /* take all the bios off the list at once and process them
  436. * later on (without the lock held). But, remember the
  437. * tail and other pointers so the bios can be properly reinserted
  438. * into the list if we hit congestion
  439. */
  440. if (!force_reg && device->pending_sync_bios.head) {
  441. pending_bios = &device->pending_sync_bios;
  442. force_reg = 1;
  443. } else {
  444. pending_bios = &device->pending_bios;
  445. force_reg = 0;
  446. }
  447. pending = pending_bios->head;
  448. tail = pending_bios->tail;
  449. WARN_ON(pending && !tail);
  450. /*
  451. * if pending was null this time around, no bios need processing
  452. * at all and we can stop. Otherwise it'll loop back up again
  453. * and do an additional check so no bios are missed.
  454. *
  455. * device->running_pending is used to synchronize with the
  456. * schedule_bio code.
  457. */
  458. if (device->pending_sync_bios.head == NULL &&
  459. device->pending_bios.head == NULL) {
  460. again = 0;
  461. device->running_pending = 0;
  462. } else {
  463. again = 1;
  464. device->running_pending = 1;
  465. }
  466. pending_bios->head = NULL;
  467. pending_bios->tail = NULL;
  468. spin_unlock(&device->io_lock);
  469. while (pending) {
  470. rmb();
  471. /* we want to work on both lists, but do more bios on the
  472. * sync list than the regular list
  473. */
  474. if ((num_run > 32 &&
  475. pending_bios != &device->pending_sync_bios &&
  476. device->pending_sync_bios.head) ||
  477. (num_run > 64 && pending_bios == &device->pending_sync_bios &&
  478. device->pending_bios.head)) {
  479. spin_lock(&device->io_lock);
  480. requeue_list(pending_bios, pending, tail);
  481. goto loop_lock;
  482. }
  483. cur = pending;
  484. pending = pending->bi_next;
  485. cur->bi_next = NULL;
  486. BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
  487. /*
  488. * if we're doing the sync list, record that our
  489. * plug has some sync requests on it
  490. *
  491. * If we're doing the regular list and there are
  492. * sync requests sitting around, unplug before
  493. * we add more
  494. */
  495. if (pending_bios == &device->pending_sync_bios) {
  496. sync_pending = 1;
  497. } else if (sync_pending) {
  498. blk_finish_plug(&plug);
  499. blk_start_plug(&plug);
  500. sync_pending = 0;
  501. }
  502. btrfsic_submit_bio(cur);
  503. num_run++;
  504. batch_run++;
  505. cond_resched();
  506. /*
  507. * we made progress, there is more work to do and the bdi
  508. * is now congested. Back off and let other work structs
  509. * run instead
  510. */
  511. if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
  512. fs_info->fs_devices->open_devices > 1) {
  513. struct io_context *ioc;
  514. ioc = current->io_context;
  515. /*
  516. * the main goal here is that we don't want to
  517. * block if we're going to be able to submit
  518. * more requests without blocking.
  519. *
  520. * This code does two great things, it pokes into
  521. * the elevator code from a filesystem _and_
  522. * it makes assumptions about how batching works.
  523. */
  524. if (ioc && ioc->nr_batch_requests > 0 &&
  525. time_before(jiffies, ioc->last_waited + HZ/50UL) &&
  526. (last_waited == 0 ||
  527. ioc->last_waited == last_waited)) {
  528. /*
  529. * we want to go through our batch of
  530. * requests and stop. So, we copy out
  531. * the ioc->last_waited time and test
  532. * against it before looping
  533. */
  534. last_waited = ioc->last_waited;
  535. cond_resched();
  536. continue;
  537. }
  538. spin_lock(&device->io_lock);
  539. requeue_list(pending_bios, pending, tail);
  540. device->running_pending = 1;
  541. spin_unlock(&device->io_lock);
  542. btrfs_queue_work(fs_info->submit_workers,
  543. &device->work);
  544. goto done;
  545. }
  546. }
  547. cond_resched();
  548. if (again)
  549. goto loop;
  550. spin_lock(&device->io_lock);
  551. if (device->pending_bios.head || device->pending_sync_bios.head)
  552. goto loop_lock;
  553. spin_unlock(&device->io_lock);
  554. done:
  555. blk_finish_plug(&plug);
  556. }
  557. static void pending_bios_fn(struct btrfs_work *work)
  558. {
  559. struct btrfs_device *device;
  560. device = container_of(work, struct btrfs_device, work);
  561. run_scheduled_bios(device);
  562. }
  563. /*
  564. * Search and remove all stale (devices which are not mounted) devices.
  565. * When both inputs are NULL, it will search and release all stale devices.
  566. * path: Optional. When provided will it release all unmounted devices
  567. * matching this path only.
  568. * skip_dev: Optional. Will skip this device when searching for the stale
  569. * devices.
  570. */
  571. static void btrfs_free_stale_devices(const char *path,
  572. struct btrfs_device *skip_dev)
  573. {
  574. struct btrfs_fs_devices *fs_devs, *tmp_fs_devs;
  575. struct btrfs_device *dev, *tmp_dev;
  576. list_for_each_entry_safe(fs_devs, tmp_fs_devs, &fs_uuids, fs_list) {
  577. if (fs_devs->opened)
  578. continue;
  579. list_for_each_entry_safe(dev, tmp_dev,
  580. &fs_devs->devices, dev_list) {
  581. int not_found = 0;
  582. if (skip_dev && skip_dev == dev)
  583. continue;
  584. if (path && !dev->name)
  585. continue;
  586. rcu_read_lock();
  587. if (path)
  588. not_found = strcmp(rcu_str_deref(dev->name),
  589. path);
  590. rcu_read_unlock();
  591. if (not_found)
  592. continue;
  593. /* delete the stale device */
  594. if (fs_devs->num_devices == 1) {
  595. btrfs_sysfs_remove_fsid(fs_devs);
  596. list_del(&fs_devs->fs_list);
  597. free_fs_devices(fs_devs);
  598. break;
  599. } else {
  600. fs_devs->num_devices--;
  601. list_del(&dev->dev_list);
  602. btrfs_free_device(dev);
  603. }
  604. }
  605. }
  606. }
  607. static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
  608. struct btrfs_device *device, fmode_t flags,
  609. void *holder)
  610. {
  611. struct request_queue *q;
  612. struct block_device *bdev;
  613. struct buffer_head *bh;
  614. struct btrfs_super_block *disk_super;
  615. u64 devid;
  616. int ret;
  617. if (device->bdev)
  618. return -EINVAL;
  619. if (!device->name)
  620. return -EINVAL;
  621. ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
  622. &bdev, &bh);
  623. if (ret)
  624. return ret;
  625. disk_super = (struct btrfs_super_block *)bh->b_data;
  626. devid = btrfs_stack_device_id(&disk_super->dev_item);
  627. if (devid != device->devid)
  628. goto error_brelse;
  629. if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
  630. goto error_brelse;
  631. device->generation = btrfs_super_generation(disk_super);
  632. if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
  633. clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
  634. fs_devices->seeding = 1;
  635. } else {
  636. if (bdev_read_only(bdev))
  637. clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
  638. else
  639. set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
  640. }
  641. q = bdev_get_queue(bdev);
  642. if (!blk_queue_nonrot(q))
  643. fs_devices->rotating = 1;
  644. device->bdev = bdev;
  645. clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
  646. device->mode = flags;
  647. fs_devices->open_devices++;
  648. if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
  649. device->devid != BTRFS_DEV_REPLACE_DEVID) {
  650. fs_devices->rw_devices++;
  651. list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
  652. }
  653. brelse(bh);
  654. return 0;
  655. error_brelse:
  656. brelse(bh);
  657. blkdev_put(bdev, flags);
  658. return -EINVAL;
  659. }
  660. /*
  661. * Add new device to list of registered devices
  662. *
  663. * Returns:
  664. * device pointer which was just added or updated when successful
  665. * error pointer when failed
  666. */
  667. static noinline struct btrfs_device *device_list_add(const char *path,
  668. struct btrfs_super_block *disk_super)
  669. {
  670. struct btrfs_device *device;
  671. struct btrfs_fs_devices *fs_devices;
  672. struct rcu_string *name;
  673. u64 found_transid = btrfs_super_generation(disk_super);
  674. u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
  675. fs_devices = find_fsid(disk_super->fsid);
  676. if (!fs_devices) {
  677. fs_devices = alloc_fs_devices(disk_super->fsid);
  678. if (IS_ERR(fs_devices))
  679. return ERR_CAST(fs_devices);
  680. list_add(&fs_devices->fs_list, &fs_uuids);
  681. device = NULL;
  682. } else {
  683. device = find_device(fs_devices, devid,
  684. disk_super->dev_item.uuid);
  685. }
  686. if (!device) {
  687. if (fs_devices->opened)
  688. return ERR_PTR(-EBUSY);
  689. device = btrfs_alloc_device(NULL, &devid,
  690. disk_super->dev_item.uuid);
  691. if (IS_ERR(device)) {
  692. /* we can safely leave the fs_devices entry around */
  693. return device;
  694. }
  695. name = rcu_string_strdup(path, GFP_NOFS);
  696. if (!name) {
  697. btrfs_free_device(device);
  698. return ERR_PTR(-ENOMEM);
  699. }
  700. rcu_assign_pointer(device->name, name);
  701. mutex_lock(&fs_devices->device_list_mutex);
  702. list_add_rcu(&device->dev_list, &fs_devices->devices);
  703. fs_devices->num_devices++;
  704. mutex_unlock(&fs_devices->device_list_mutex);
  705. device->fs_devices = fs_devices;
  706. btrfs_free_stale_devices(path, device);
  707. if (disk_super->label[0])
  708. pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
  709. disk_super->label, devid, found_transid, path);
  710. else
  711. pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
  712. disk_super->fsid, devid, found_transid, path);
  713. } else if (!device->name || strcmp(device->name->str, path)) {
  714. /*
  715. * When FS is already mounted.
  716. * 1. If you are here and if the device->name is NULL that
  717. * means this device was missing at time of FS mount.
  718. * 2. If you are here and if the device->name is different
  719. * from 'path' that means either
  720. * a. The same device disappeared and reappeared with
  721. * different name. or
  722. * b. The missing-disk-which-was-replaced, has
  723. * reappeared now.
  724. *
  725. * We must allow 1 and 2a above. But 2b would be a spurious
  726. * and unintentional.
  727. *
  728. * Further in case of 1 and 2a above, the disk at 'path'
  729. * would have missed some transaction when it was away and
  730. * in case of 2a the stale bdev has to be updated as well.
  731. * 2b must not be allowed at all time.
  732. */
  733. /*
  734. * For now, we do allow update to btrfs_fs_device through the
  735. * btrfs dev scan cli after FS has been mounted. We're still
  736. * tracking a problem where systems fail mount by subvolume id
  737. * when we reject replacement on a mounted FS.
  738. */
  739. if (!fs_devices->opened && found_transid < device->generation) {
  740. /*
  741. * That is if the FS is _not_ mounted and if you
  742. * are here, that means there is more than one
  743. * disk with same uuid and devid.We keep the one
  744. * with larger generation number or the last-in if
  745. * generation are equal.
  746. */
  747. return ERR_PTR(-EEXIST);
  748. }
  749. name = rcu_string_strdup(path, GFP_NOFS);
  750. if (!name)
  751. return ERR_PTR(-ENOMEM);
  752. rcu_string_free(device->name);
  753. rcu_assign_pointer(device->name, name);
  754. if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
  755. fs_devices->missing_devices--;
  756. clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
  757. }
  758. }
  759. /*
  760. * Unmount does not free the btrfs_device struct but would zero
  761. * generation along with most of the other members. So just update
  762. * it back. We need it to pick the disk with largest generation
  763. * (as above).
  764. */
  765. if (!fs_devices->opened)
  766. device->generation = found_transid;
  767. fs_devices->total_devices = btrfs_super_num_devices(disk_super);
  768. return device;
  769. }
  770. static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
  771. {
  772. struct btrfs_fs_devices *fs_devices;
  773. struct btrfs_device *device;
  774. struct btrfs_device *orig_dev;
  775. fs_devices = alloc_fs_devices(orig->fsid);
  776. if (IS_ERR(fs_devices))
  777. return fs_devices;
  778. mutex_lock(&orig->device_list_mutex);
  779. fs_devices->total_devices = orig->total_devices;
  780. /* We have held the volume lock, it is safe to get the devices. */
  781. list_for_each_entry(orig_dev, &orig->devices, dev_list) {
  782. struct rcu_string *name;
  783. device = btrfs_alloc_device(NULL, &orig_dev->devid,
  784. orig_dev->uuid);
  785. if (IS_ERR(device))
  786. goto error;
  787. /*
  788. * This is ok to do without rcu read locked because we hold the
  789. * uuid mutex so nothing we touch in here is going to disappear.
  790. */
  791. if (orig_dev->name) {
  792. name = rcu_string_strdup(orig_dev->name->str,
  793. GFP_KERNEL);
  794. if (!name) {
  795. btrfs_free_device(device);
  796. goto error;
  797. }
  798. rcu_assign_pointer(device->name, name);
  799. }
  800. list_add(&device->dev_list, &fs_devices->devices);
  801. device->fs_devices = fs_devices;
  802. fs_devices->num_devices++;
  803. }
  804. mutex_unlock(&orig->device_list_mutex);
  805. return fs_devices;
  806. error:
  807. mutex_unlock(&orig->device_list_mutex);
  808. free_fs_devices(fs_devices);
  809. return ERR_PTR(-ENOMEM);
  810. }
  811. /*
  812. * After we have read the system tree and know devids belonging to
  813. * this filesystem, remove the device which does not belong there.
  814. */
  815. void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
  816. {
  817. struct btrfs_device *device, *next;
  818. struct btrfs_device *latest_dev = NULL;
  819. mutex_lock(&uuid_mutex);
  820. again:
  821. /* This is the initialized path, it is safe to release the devices. */
  822. list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
  823. if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
  824. &device->dev_state)) {
  825. if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
  826. &device->dev_state) &&
  827. (!latest_dev ||
  828. device->generation > latest_dev->generation)) {
  829. latest_dev = device;
  830. }
  831. continue;
  832. }
  833. if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
  834. /*
  835. * In the first step, keep the device which has
  836. * the correct fsid and the devid that is used
  837. * for the dev_replace procedure.
  838. * In the second step, the dev_replace state is
  839. * read from the device tree and it is known
  840. * whether the procedure is really active or
  841. * not, which means whether this device is
  842. * used or whether it should be removed.
  843. */
  844. if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
  845. &device->dev_state)) {
  846. continue;
  847. }
  848. }
  849. if (device->bdev) {
  850. blkdev_put(device->bdev, device->mode);
  851. device->bdev = NULL;
  852. fs_devices->open_devices--;
  853. }
  854. if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
  855. list_del_init(&device->dev_alloc_list);
  856. clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
  857. if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
  858. &device->dev_state))
  859. fs_devices->rw_devices--;
  860. }
  861. list_del_init(&device->dev_list);
  862. fs_devices->num_devices--;
  863. btrfs_free_device(device);
  864. }
  865. if (fs_devices->seed) {
  866. fs_devices = fs_devices->seed;
  867. goto again;
  868. }
  869. fs_devices->latest_bdev = latest_dev->bdev;
  870. mutex_unlock(&uuid_mutex);
  871. }
  872. static void free_device_rcu(struct rcu_head *head)
  873. {
  874. struct btrfs_device *device;
  875. device = container_of(head, struct btrfs_device, rcu);
  876. btrfs_free_device(device);
  877. }
  878. static void btrfs_close_bdev(struct btrfs_device *device)
  879. {
  880. if (!device->bdev)
  881. return;
  882. if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
  883. sync_blockdev(device->bdev);
  884. invalidate_bdev(device->bdev);
  885. }
  886. blkdev_put(device->bdev, device->mode);
  887. }
  888. static void btrfs_prepare_close_one_device(struct btrfs_device *device)
  889. {
  890. struct btrfs_fs_devices *fs_devices = device->fs_devices;
  891. struct btrfs_device *new_device;
  892. struct rcu_string *name;
  893. if (device->bdev)
  894. fs_devices->open_devices--;
  895. if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
  896. device->devid != BTRFS_DEV_REPLACE_DEVID) {
  897. list_del_init(&device->dev_alloc_list);
  898. fs_devices->rw_devices--;
  899. }
  900. if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
  901. fs_devices->missing_devices--;
  902. new_device = btrfs_alloc_device(NULL, &device->devid,
  903. device->uuid);
  904. BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
  905. /* Safe because we are under uuid_mutex */
  906. if (device->name) {
  907. name = rcu_string_strdup(device->name->str, GFP_NOFS);
  908. BUG_ON(!name); /* -ENOMEM */
  909. rcu_assign_pointer(new_device->name, name);
  910. }
  911. list_replace_rcu(&device->dev_list, &new_device->dev_list);
  912. new_device->fs_devices = device->fs_devices;
  913. }
  914. static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
  915. {
  916. struct btrfs_device *device, *tmp;
  917. struct list_head pending_put;
  918. INIT_LIST_HEAD(&pending_put);
  919. if (--fs_devices->opened > 0)
  920. return 0;
  921. mutex_lock(&fs_devices->device_list_mutex);
  922. list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
  923. btrfs_prepare_close_one_device(device);
  924. list_add(&device->dev_list, &pending_put);
  925. }
  926. mutex_unlock(&fs_devices->device_list_mutex);
  927. /*
  928. * btrfs_show_devname() is using the device_list_mutex,
  929. * sometimes call to blkdev_put() leads vfs calling
  930. * into this func. So do put outside of device_list_mutex,
  931. * as of now.
  932. */
  933. while (!list_empty(&pending_put)) {
  934. device = list_first_entry(&pending_put,
  935. struct btrfs_device, dev_list);
  936. list_del(&device->dev_list);
  937. btrfs_close_bdev(device);
  938. call_rcu(&device->rcu, free_device_rcu);
  939. }
  940. WARN_ON(fs_devices->open_devices);
  941. WARN_ON(fs_devices->rw_devices);
  942. fs_devices->opened = 0;
  943. fs_devices->seeding = 0;
  944. return 0;
  945. }
  946. int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
  947. {
  948. struct btrfs_fs_devices *seed_devices = NULL;
  949. int ret;
  950. mutex_lock(&uuid_mutex);
  951. ret = close_fs_devices(fs_devices);
  952. if (!fs_devices->opened) {
  953. seed_devices = fs_devices->seed;
  954. fs_devices->seed = NULL;
  955. }
  956. mutex_unlock(&uuid_mutex);
  957. while (seed_devices) {
  958. fs_devices = seed_devices;
  959. seed_devices = fs_devices->seed;
  960. close_fs_devices(fs_devices);
  961. free_fs_devices(fs_devices);
  962. }
  963. return ret;
  964. }
  965. static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
  966. fmode_t flags, void *holder)
  967. {
  968. struct btrfs_device *device;
  969. struct btrfs_device *latest_dev = NULL;
  970. int ret = 0;
  971. flags |= FMODE_EXCL;
  972. list_for_each_entry(device, &fs_devices->devices, dev_list) {
  973. /* Just open everything we can; ignore failures here */
  974. if (btrfs_open_one_device(fs_devices, device, flags, holder))
  975. continue;
  976. if (!latest_dev ||
  977. device->generation > latest_dev->generation)
  978. latest_dev = device;
  979. }
  980. if (fs_devices->open_devices == 0) {
  981. ret = -EINVAL;
  982. goto out;
  983. }
  984. fs_devices->opened = 1;
  985. fs_devices->latest_bdev = latest_dev->bdev;
  986. fs_devices->total_rw_bytes = 0;
  987. out:
  988. return ret;
  989. }
  990. static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
  991. {
  992. struct btrfs_device *dev1, *dev2;
  993. dev1 = list_entry(a, struct btrfs_device, dev_list);
  994. dev2 = list_entry(b, struct btrfs_device, dev_list);
  995. if (dev1->devid < dev2->devid)
  996. return -1;
  997. else if (dev1->devid > dev2->devid)
  998. return 1;
  999. return 0;
  1000. }
  1001. int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
  1002. fmode_t flags, void *holder)
  1003. {
  1004. int ret;
  1005. mutex_lock(&fs_devices->device_list_mutex);
  1006. if (fs_devices->opened) {
  1007. fs_devices->opened++;
  1008. ret = 0;
  1009. } else {
  1010. list_sort(NULL, &fs_devices->devices, devid_cmp);
  1011. ret = open_fs_devices(fs_devices, flags, holder);
  1012. }
  1013. mutex_unlock(&fs_devices->device_list_mutex);
  1014. return ret;
  1015. }
  1016. static void btrfs_release_disk_super(struct page *page)
  1017. {
  1018. kunmap(page);
  1019. put_page(page);
  1020. }
  1021. static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
  1022. struct page **page,
  1023. struct btrfs_super_block **disk_super)
  1024. {
  1025. void *p;
  1026. pgoff_t index;
  1027. /* make sure our super fits in the device */
  1028. if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
  1029. return 1;
  1030. /* make sure our super fits in the page */
  1031. if (sizeof(**disk_super) > PAGE_SIZE)
  1032. return 1;
  1033. /* make sure our super doesn't straddle pages on disk */
  1034. index = bytenr >> PAGE_SHIFT;
  1035. if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
  1036. return 1;
  1037. /* pull in the page with our super */
  1038. *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
  1039. index, GFP_KERNEL);
  1040. if (IS_ERR_OR_NULL(*page))
  1041. return 1;
  1042. p = kmap(*page);
  1043. /* align our pointer to the offset of the super block */
  1044. *disk_super = p + (bytenr & ~PAGE_MASK);
  1045. if (btrfs_super_bytenr(*disk_super) != bytenr ||
  1046. btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
  1047. btrfs_release_disk_super(*page);
  1048. return 1;
  1049. }
  1050. if ((*disk_super)->label[0] &&
  1051. (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
  1052. (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
  1053. return 0;
  1054. }
  1055. /*
  1056. * Look for a btrfs signature on a device. This may be called out of the mount path
  1057. * and we are not allowed to call set_blocksize during the scan. The superblock
  1058. * is read via pagecache
  1059. */
  1060. int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
  1061. struct btrfs_fs_devices **fs_devices_ret)
  1062. {
  1063. struct btrfs_super_block *disk_super;
  1064. struct btrfs_device *device;
  1065. struct block_device *bdev;
  1066. struct page *page;
  1067. int ret = 0;
  1068. u64 bytenr;
  1069. /*
  1070. * we would like to check all the supers, but that would make
  1071. * a btrfs mount succeed after a mkfs from a different FS.
  1072. * So, we need to add a special mount option to scan for
  1073. * later supers, using BTRFS_SUPER_MIRROR_MAX instead
  1074. */
  1075. bytenr = btrfs_sb_offset(0);
  1076. flags |= FMODE_EXCL;
  1077. bdev = blkdev_get_by_path(path, flags, holder);
  1078. if (IS_ERR(bdev))
  1079. return PTR_ERR(bdev);
  1080. if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
  1081. ret = -EINVAL;
  1082. goto error_bdev_put;
  1083. }
  1084. mutex_lock(&uuid_mutex);
  1085. device = device_list_add(path, disk_super);
  1086. if (IS_ERR(device))
  1087. ret = PTR_ERR(device);
  1088. else
  1089. *fs_devices_ret = device->fs_devices;
  1090. mutex_unlock(&uuid_mutex);
  1091. btrfs_release_disk_super(page);
  1092. error_bdev_put:
  1093. blkdev_put(bdev, flags);
  1094. return ret;
  1095. }
  1096. /* helper to account the used device space in the range */
  1097. int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
  1098. u64 end, u64 *length)
  1099. {
  1100. struct btrfs_key key;
  1101. struct btrfs_root *root = device->fs_info->dev_root;
  1102. struct btrfs_dev_extent *dev_extent;
  1103. struct btrfs_path *path;
  1104. u64 extent_end;
  1105. int ret;
  1106. int slot;
  1107. struct extent_buffer *l;
  1108. *length = 0;
  1109. if (start >= device->total_bytes ||
  1110. test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
  1111. return 0;
  1112. path = btrfs_alloc_path();
  1113. if (!path)
  1114. return -ENOMEM;
  1115. path->reada = READA_FORWARD;
  1116. key.objectid = device->devid;
  1117. key.offset = start;
  1118. key.type = BTRFS_DEV_EXTENT_KEY;
  1119. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  1120. if (ret < 0)
  1121. goto out;
  1122. if (ret > 0) {
  1123. ret = btrfs_previous_item(root, path, key.objectid, key.type);
  1124. if (ret < 0)
  1125. goto out;
  1126. }
  1127. while (1) {
  1128. l = path->nodes[0];
  1129. slot = path->slots[0];
  1130. if (slot >= btrfs_header_nritems(l)) {
  1131. ret = btrfs_next_leaf(root, path);
  1132. if (ret == 0)
  1133. continue;
  1134. if (ret < 0)
  1135. goto out;
  1136. break;
  1137. }
  1138. btrfs_item_key_to_cpu(l, &key, slot);
  1139. if (key.objectid < device->devid)
  1140. goto next;
  1141. if (key.objectid > device->devid)
  1142. break;
  1143. if (key.type != BTRFS_DEV_EXTENT_KEY)
  1144. goto next;
  1145. dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
  1146. extent_end = key.offset + btrfs_dev_extent_length(l,
  1147. dev_extent);
  1148. if (key.offset <= start && extent_end > end) {
  1149. *length = end - start + 1;
  1150. break;
  1151. } else if (key.offset <= start && extent_end > start)
  1152. *length += extent_end - start;
  1153. else if (key.offset > start && extent_end <= end)
  1154. *length += extent_end - key.offset;
  1155. else if (key.offset > start && key.offset <= end) {
  1156. *length += end - key.offset + 1;
  1157. break;
  1158. } else if (key.offset > end)
  1159. break;
  1160. next:
  1161. path->slots[0]++;
  1162. }
  1163. ret = 0;
  1164. out:
  1165. btrfs_free_path(path);
  1166. return ret;
  1167. }
  1168. static int contains_pending_extent(struct btrfs_transaction *transaction,
  1169. struct btrfs_device *device,
  1170. u64 *start, u64 len)
  1171. {
  1172. struct btrfs_fs_info *fs_info = device->fs_info;
  1173. struct extent_map *em;
  1174. struct list_head *search_list = &fs_info->pinned_chunks;
  1175. int ret = 0;
  1176. u64 physical_start = *start;
  1177. if (transaction)
  1178. search_list = &transaction->pending_chunks;
  1179. again:
  1180. list_for_each_entry(em, search_list, list) {
  1181. struct map_lookup *map;
  1182. int i;
  1183. map = em->map_lookup;
  1184. for (i = 0; i < map->num_stripes; i++) {
  1185. u64 end;
  1186. if (map->stripes[i].dev != device)
  1187. continue;
  1188. if (map->stripes[i].physical >= physical_start + len ||
  1189. map->stripes[i].physical + em->orig_block_len <=
  1190. physical_start)
  1191. continue;
  1192. /*
  1193. * Make sure that while processing the pinned list we do
  1194. * not override our *start with a lower value, because
  1195. * we can have pinned chunks that fall within this
  1196. * device hole and that have lower physical addresses
  1197. * than the pending chunks we processed before. If we
  1198. * do not take this special care we can end up getting
  1199. * 2 pending chunks that start at the same physical
  1200. * device offsets because the end offset of a pinned
  1201. * chunk can be equal to the start offset of some
  1202. * pending chunk.
  1203. */
  1204. end = map->stripes[i].physical + em->orig_block_len;
  1205. if (end > *start) {
  1206. *start = end;
  1207. ret = 1;
  1208. }
  1209. }
  1210. }
  1211. if (search_list != &fs_info->pinned_chunks) {
  1212. search_list = &fs_info->pinned_chunks;
  1213. goto again;
  1214. }
  1215. return ret;
  1216. }
  1217. /*
  1218. * find_free_dev_extent_start - find free space in the specified device
  1219. * @device: the device which we search the free space in
  1220. * @num_bytes: the size of the free space that we need
  1221. * @search_start: the position from which to begin the search
  1222. * @start: store the start of the free space.
  1223. * @len: the size of the free space. that we find, or the size
  1224. * of the max free space if we don't find suitable free space
  1225. *
  1226. * this uses a pretty simple search, the expectation is that it is
  1227. * called very infrequently and that a given device has a small number
  1228. * of extents
  1229. *
  1230. * @start is used to store the start of the free space if we find. But if we
  1231. * don't find suitable free space, it will be used to store the start position
  1232. * of the max free space.
  1233. *
  1234. * @len is used to store the size of the free space that we find.
  1235. * But if we don't find suitable free space, it is used to store the size of
  1236. * the max free space.
  1237. */
  1238. int find_free_dev_extent_start(struct btrfs_transaction *transaction,
  1239. struct btrfs_device *device, u64 num_bytes,
  1240. u64 search_start, u64 *start, u64 *len)
  1241. {
  1242. struct btrfs_fs_info *fs_info = device->fs_info;
  1243. struct btrfs_root *root = fs_info->dev_root;
  1244. struct btrfs_key key;
  1245. struct btrfs_dev_extent *dev_extent;
  1246. struct btrfs_path *path;
  1247. u64 hole_size;
  1248. u64 max_hole_start;
  1249. u64 max_hole_size;
  1250. u64 extent_end;
  1251. u64 search_end = device->total_bytes;
  1252. int ret;
  1253. int slot;
  1254. struct extent_buffer *l;
  1255. /*
  1256. * We don't want to overwrite the superblock on the drive nor any area
  1257. * used by the boot loader (grub for example), so we make sure to start
  1258. * at an offset of at least 1MB.
  1259. */
  1260. search_start = max_t(u64, search_start, SZ_1M);
  1261. path = btrfs_alloc_path();
  1262. if (!path)
  1263. return -ENOMEM;
  1264. max_hole_start = search_start;
  1265. max_hole_size = 0;
  1266. again:
  1267. if (search_start >= search_end ||
  1268. test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
  1269. ret = -ENOSPC;
  1270. goto out;
  1271. }
  1272. path->reada = READA_FORWARD;
  1273. path->search_commit_root = 1;
  1274. path->skip_locking = 1;
  1275. key.objectid = device->devid;
  1276. key.offset = search_start;
  1277. key.type = BTRFS_DEV_EXTENT_KEY;
  1278. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  1279. if (ret < 0)
  1280. goto out;
  1281. if (ret > 0) {
  1282. ret = btrfs_previous_item(root, path, key.objectid, key.type);
  1283. if (ret < 0)
  1284. goto out;
  1285. }
  1286. while (1) {
  1287. l = path->nodes[0];
  1288. slot = path->slots[0];
  1289. if (slot >= btrfs_header_nritems(l)) {
  1290. ret = btrfs_next_leaf(root, path);
  1291. if (ret == 0)
  1292. continue;
  1293. if (ret < 0)
  1294. goto out;
  1295. break;
  1296. }
  1297. btrfs_item_key_to_cpu(l, &key, slot);
  1298. if (key.objectid < device->devid)
  1299. goto next;
  1300. if (key.objectid > device->devid)
  1301. break;
  1302. if (key.type != BTRFS_DEV_EXTENT_KEY)
  1303. goto next;
  1304. if (key.offset > search_start) {
  1305. hole_size = key.offset - search_start;
  1306. /*
  1307. * Have to check before we set max_hole_start, otherwise
  1308. * we could end up sending back this offset anyway.
  1309. */
  1310. if (contains_pending_extent(transaction, device,
  1311. &search_start,
  1312. hole_size)) {
  1313. if (key.offset >= search_start) {
  1314. hole_size = key.offset - search_start;
  1315. } else {
  1316. WARN_ON_ONCE(1);
  1317. hole_size = 0;
  1318. }
  1319. }
  1320. if (hole_size > max_hole_size) {
  1321. max_hole_start = search_start;
  1322. max_hole_size = hole_size;
  1323. }
  1324. /*
  1325. * If this free space is greater than which we need,
  1326. * it must be the max free space that we have found
  1327. * until now, so max_hole_start must point to the start
  1328. * of this free space and the length of this free space
  1329. * is stored in max_hole_size. Thus, we return
  1330. * max_hole_start and max_hole_size and go back to the
  1331. * caller.
  1332. */
  1333. if (hole_size >= num_bytes) {
  1334. ret = 0;
  1335. goto out;
  1336. }
  1337. }
  1338. dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
  1339. extent_end = key.offset + btrfs_dev_extent_length(l,
  1340. dev_extent);
  1341. if (extent_end > search_start)
  1342. search_start = extent_end;
  1343. next:
  1344. path->slots[0]++;
  1345. cond_resched();
  1346. }
  1347. /*
  1348. * At this point, search_start should be the end of
  1349. * allocated dev extents, and when shrinking the device,
  1350. * search_end may be smaller than search_start.
  1351. */
  1352. if (search_end > search_start) {
  1353. hole_size = search_end - search_start;
  1354. if (contains_pending_extent(transaction, device, &search_start,
  1355. hole_size)) {
  1356. btrfs_release_path(path);
  1357. goto again;
  1358. }
  1359. if (hole_size > max_hole_size) {
  1360. max_hole_start = search_start;
  1361. max_hole_size = hole_size;
  1362. }
  1363. }
  1364. /* See above. */
  1365. if (max_hole_size < num_bytes)
  1366. ret = -ENOSPC;
  1367. else
  1368. ret = 0;
  1369. out:
  1370. btrfs_free_path(path);
  1371. *start = max_hole_start;
  1372. if (len)
  1373. *len = max_hole_size;
  1374. return ret;
  1375. }
  1376. int find_free_dev_extent(struct btrfs_trans_handle *trans,
  1377. struct btrfs_device *device, u64 num_bytes,
  1378. u64 *start, u64 *len)
  1379. {
  1380. /* FIXME use last free of some kind */
  1381. return find_free_dev_extent_start(trans->transaction, device,
  1382. num_bytes, 0, start, len);
  1383. }
  1384. static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
  1385. struct btrfs_device *device,
  1386. u64 start, u64 *dev_extent_len)
  1387. {
  1388. struct btrfs_fs_info *fs_info = device->fs_info;
  1389. struct btrfs_root *root = fs_info->dev_root;
  1390. int ret;
  1391. struct btrfs_path *path;
  1392. struct btrfs_key key;
  1393. struct btrfs_key found_key;
  1394. struct extent_buffer *leaf = NULL;
  1395. struct btrfs_dev_extent *extent = NULL;
  1396. path = btrfs_alloc_path();
  1397. if (!path)
  1398. return -ENOMEM;
  1399. key.objectid = device->devid;
  1400. key.offset = start;
  1401. key.type = BTRFS_DEV_EXTENT_KEY;
  1402. again:
  1403. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1404. if (ret > 0) {
  1405. ret = btrfs_previous_item(root, path, key.objectid,
  1406. BTRFS_DEV_EXTENT_KEY);
  1407. if (ret)
  1408. goto out;
  1409. leaf = path->nodes[0];
  1410. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  1411. extent = btrfs_item_ptr(leaf, path->slots[0],
  1412. struct btrfs_dev_extent);
  1413. BUG_ON(found_key.offset > start || found_key.offset +
  1414. btrfs_dev_extent_length(leaf, extent) < start);
  1415. key = found_key;
  1416. btrfs_release_path(path);
  1417. goto again;
  1418. } else if (ret == 0) {
  1419. leaf = path->nodes[0];
  1420. extent = btrfs_item_ptr(leaf, path->slots[0],
  1421. struct btrfs_dev_extent);
  1422. } else {
  1423. btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
  1424. goto out;
  1425. }
  1426. *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
  1427. ret = btrfs_del_item(trans, root, path);
  1428. if (ret) {
  1429. btrfs_handle_fs_error(fs_info, ret,
  1430. "Failed to remove dev extent item");
  1431. } else {
  1432. set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
  1433. }
  1434. out:
  1435. btrfs_free_path(path);
  1436. return ret;
  1437. }
  1438. static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
  1439. struct btrfs_device *device,
  1440. u64 chunk_offset, u64 start, u64 num_bytes)
  1441. {
  1442. int ret;
  1443. struct btrfs_path *path;
  1444. struct btrfs_fs_info *fs_info = device->fs_info;
  1445. struct btrfs_root *root = fs_info->dev_root;
  1446. struct btrfs_dev_extent *extent;
  1447. struct extent_buffer *leaf;
  1448. struct btrfs_key key;
  1449. WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
  1450. WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
  1451. path = btrfs_alloc_path();
  1452. if (!path)
  1453. return -ENOMEM;
  1454. key.objectid = device->devid;
  1455. key.offset = start;
  1456. key.type = BTRFS_DEV_EXTENT_KEY;
  1457. ret = btrfs_insert_empty_item(trans, root, path, &key,
  1458. sizeof(*extent));
  1459. if (ret)
  1460. goto out;
  1461. leaf = path->nodes[0];
  1462. extent = btrfs_item_ptr(leaf, path->slots[0],
  1463. struct btrfs_dev_extent);
  1464. btrfs_set_dev_extent_chunk_tree(leaf, extent,
  1465. BTRFS_CHUNK_TREE_OBJECTID);
  1466. btrfs_set_dev_extent_chunk_objectid(leaf, extent,
  1467. BTRFS_FIRST_CHUNK_TREE_OBJECTID);
  1468. btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
  1469. btrfs_set_dev_extent_length(leaf, extent, num_bytes);
  1470. btrfs_mark_buffer_dirty(leaf);
  1471. out:
  1472. btrfs_free_path(path);
  1473. return ret;
  1474. }
  1475. static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
  1476. {
  1477. struct extent_map_tree *em_tree;
  1478. struct extent_map *em;
  1479. struct rb_node *n;
  1480. u64 ret = 0;
  1481. em_tree = &fs_info->mapping_tree.map_tree;
  1482. read_lock(&em_tree->lock);
  1483. n = rb_last(&em_tree->map);
  1484. if (n) {
  1485. em = rb_entry(n, struct extent_map, rb_node);
  1486. ret = em->start + em->len;
  1487. }
  1488. read_unlock(&em_tree->lock);
  1489. return ret;
  1490. }
  1491. static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
  1492. u64 *devid_ret)
  1493. {
  1494. int ret;
  1495. struct btrfs_key key;
  1496. struct btrfs_key found_key;
  1497. struct btrfs_path *path;
  1498. path = btrfs_alloc_path();
  1499. if (!path)
  1500. return -ENOMEM;
  1501. key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
  1502. key.type = BTRFS_DEV_ITEM_KEY;
  1503. key.offset = (u64)-1;
  1504. ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
  1505. if (ret < 0)
  1506. goto error;
  1507. BUG_ON(ret == 0); /* Corruption */
  1508. ret = btrfs_previous_item(fs_info->chunk_root, path,
  1509. BTRFS_DEV_ITEMS_OBJECTID,
  1510. BTRFS_DEV_ITEM_KEY);
  1511. if (ret) {
  1512. *devid_ret = 1;
  1513. } else {
  1514. btrfs_item_key_to_cpu(path->nodes[0], &found_key,
  1515. path->slots[0]);
  1516. *devid_ret = found_key.offset + 1;
  1517. }
  1518. ret = 0;
  1519. error:
  1520. btrfs_free_path(path);
  1521. return ret;
  1522. }
  1523. /*
  1524. * the device information is stored in the chunk root
  1525. * the btrfs_device struct should be fully filled in
  1526. */
  1527. static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
  1528. struct btrfs_fs_info *fs_info,
  1529. struct btrfs_device *device)
  1530. {
  1531. struct btrfs_root *root = fs_info->chunk_root;
  1532. int ret;
  1533. struct btrfs_path *path;
  1534. struct btrfs_dev_item *dev_item;
  1535. struct extent_buffer *leaf;
  1536. struct btrfs_key key;
  1537. unsigned long ptr;
  1538. path = btrfs_alloc_path();
  1539. if (!path)
  1540. return -ENOMEM;
  1541. key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
  1542. key.type = BTRFS_DEV_ITEM_KEY;
  1543. key.offset = device->devid;
  1544. ret = btrfs_insert_empty_item(trans, root, path, &key,
  1545. sizeof(*dev_item));
  1546. if (ret)
  1547. goto out;
  1548. leaf = path->nodes[0];
  1549. dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
  1550. btrfs_set_device_id(leaf, dev_item, device->devid);
  1551. btrfs_set_device_generation(leaf, dev_item, 0);
  1552. btrfs_set_device_type(leaf, dev_item, device->type);
  1553. btrfs_set_device_io_align(leaf, dev_item, device->io_align);
  1554. btrfs_set_device_io_width(leaf, dev_item, device->io_width);
  1555. btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
  1556. btrfs_set_device_total_bytes(leaf, dev_item,
  1557. btrfs_device_get_disk_total_bytes(device));
  1558. btrfs_set_device_bytes_used(leaf, dev_item,
  1559. btrfs_device_get_bytes_used(device));
  1560. btrfs_set_device_group(leaf, dev_item, 0);
  1561. btrfs_set_device_seek_speed(leaf, dev_item, 0);
  1562. btrfs_set_device_bandwidth(leaf, dev_item, 0);
  1563. btrfs_set_device_start_offset(leaf, dev_item, 0);
  1564. ptr = btrfs_device_uuid(dev_item);
  1565. write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
  1566. ptr = btrfs_device_fsid(dev_item);
  1567. write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
  1568. btrfs_mark_buffer_dirty(leaf);
  1569. ret = 0;
  1570. out:
  1571. btrfs_free_path(path);
  1572. return ret;
  1573. }
  1574. /*
  1575. * Function to update ctime/mtime for a given device path.
  1576. * Mainly used for ctime/mtime based probe like libblkid.
  1577. */
  1578. static void update_dev_time(const char *path_name)
  1579. {
  1580. struct file *filp;
  1581. filp = filp_open(path_name, O_RDWR, 0);
  1582. if (IS_ERR(filp))
  1583. return;
  1584. file_update_time(filp);
  1585. filp_close(filp, NULL);
  1586. }
  1587. static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
  1588. struct btrfs_device *device)
  1589. {
  1590. struct btrfs_root *root = fs_info->chunk_root;
  1591. int ret;
  1592. struct btrfs_path *path;
  1593. struct btrfs_key key;
  1594. struct btrfs_trans_handle *trans;
  1595. path = btrfs_alloc_path();
  1596. if (!path)
  1597. return -ENOMEM;
  1598. trans = btrfs_start_transaction(root, 0);
  1599. if (IS_ERR(trans)) {
  1600. btrfs_free_path(path);
  1601. return PTR_ERR(trans);
  1602. }
  1603. key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
  1604. key.type = BTRFS_DEV_ITEM_KEY;
  1605. key.offset = device->devid;
  1606. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1607. if (ret) {
  1608. if (ret > 0)
  1609. ret = -ENOENT;
  1610. btrfs_abort_transaction(trans, ret);
  1611. btrfs_end_transaction(trans);
  1612. goto out;
  1613. }
  1614. ret = btrfs_del_item(trans, root, path);
  1615. if (ret) {
  1616. btrfs_abort_transaction(trans, ret);
  1617. btrfs_end_transaction(trans);
  1618. }
  1619. out:
  1620. btrfs_free_path(path);
  1621. if (!ret)
  1622. ret = btrfs_commit_transaction(trans);
  1623. return ret;
  1624. }
  1625. /*
  1626. * Verify that @num_devices satisfies the RAID profile constraints in the whole
  1627. * filesystem. It's up to the caller to adjust that number regarding eg. device
  1628. * replace.
  1629. */
  1630. static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
  1631. u64 num_devices)
  1632. {
  1633. u64 all_avail;
  1634. unsigned seq;
  1635. int i;
  1636. do {
  1637. seq = read_seqbegin(&fs_info->profiles_lock);
  1638. all_avail = fs_info->avail_data_alloc_bits |
  1639. fs_info->avail_system_alloc_bits |
  1640. fs_info->avail_metadata_alloc_bits;
  1641. } while (read_seqretry(&fs_info->profiles_lock, seq));
  1642. for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
  1643. if (!(all_avail & btrfs_raid_array[i].bg_flag))
  1644. continue;
  1645. if (num_devices < btrfs_raid_array[i].devs_min) {
  1646. int ret = btrfs_raid_array[i].mindev_error;
  1647. if (ret)
  1648. return ret;
  1649. }
  1650. }
  1651. return 0;
  1652. }
  1653. static struct btrfs_device * btrfs_find_next_active_device(
  1654. struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
  1655. {
  1656. struct btrfs_device *next_device;
  1657. list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
  1658. if (next_device != device &&
  1659. !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
  1660. && next_device->bdev)
  1661. return next_device;
  1662. }
  1663. return NULL;
  1664. }
  1665. /*
  1666. * Helper function to check if the given device is part of s_bdev / latest_bdev
  1667. * and replace it with the provided or the next active device, in the context
  1668. * where this function called, there should be always be another device (or
  1669. * this_dev) which is active.
  1670. */
  1671. void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
  1672. struct btrfs_device *device, struct btrfs_device *this_dev)
  1673. {
  1674. struct btrfs_device *next_device;
  1675. if (this_dev)
  1676. next_device = this_dev;
  1677. else
  1678. next_device = btrfs_find_next_active_device(fs_info->fs_devices,
  1679. device);
  1680. ASSERT(next_device);
  1681. if (fs_info->sb->s_bdev &&
  1682. (fs_info->sb->s_bdev == device->bdev))
  1683. fs_info->sb->s_bdev = next_device->bdev;
  1684. if (fs_info->fs_devices->latest_bdev == device->bdev)
  1685. fs_info->fs_devices->latest_bdev = next_device->bdev;
  1686. }
  1687. int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
  1688. u64 devid)
  1689. {
  1690. struct btrfs_device *device;
  1691. struct btrfs_fs_devices *cur_devices;
  1692. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  1693. u64 num_devices;
  1694. int ret = 0;
  1695. mutex_lock(&uuid_mutex);
  1696. num_devices = fs_devices->num_devices;
  1697. btrfs_dev_replace_read_lock(&fs_info->dev_replace);
  1698. if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
  1699. WARN_ON(num_devices < 1);
  1700. num_devices--;
  1701. }
  1702. btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
  1703. ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
  1704. if (ret)
  1705. goto out;
  1706. ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
  1707. &device);
  1708. if (ret)
  1709. goto out;
  1710. if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
  1711. ret = BTRFS_ERROR_DEV_TGT_REPLACE;
  1712. goto out;
  1713. }
  1714. if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
  1715. fs_info->fs_devices->rw_devices == 1) {
  1716. ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
  1717. goto out;
  1718. }
  1719. if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
  1720. mutex_lock(&fs_info->chunk_mutex);
  1721. list_del_init(&device->dev_alloc_list);
  1722. device->fs_devices->rw_devices--;
  1723. mutex_unlock(&fs_info->chunk_mutex);
  1724. }
  1725. mutex_unlock(&uuid_mutex);
  1726. ret = btrfs_shrink_device(device, 0);
  1727. mutex_lock(&uuid_mutex);
  1728. if (ret)
  1729. goto error_undo;
  1730. /*
  1731. * TODO: the superblock still includes this device in its num_devices
  1732. * counter although write_all_supers() is not locked out. This
  1733. * could give a filesystem state which requires a degraded mount.
  1734. */
  1735. ret = btrfs_rm_dev_item(fs_info, device);
  1736. if (ret)
  1737. goto error_undo;
  1738. clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
  1739. btrfs_scrub_cancel_dev(fs_info, device);
  1740. /*
  1741. * the device list mutex makes sure that we don't change
  1742. * the device list while someone else is writing out all
  1743. * the device supers. Whoever is writing all supers, should
  1744. * lock the device list mutex before getting the number of
  1745. * devices in the super block (super_copy). Conversely,
  1746. * whoever updates the number of devices in the super block
  1747. * (super_copy) should hold the device list mutex.
  1748. */
  1749. /*
  1750. * In normal cases the cur_devices == fs_devices. But in case
  1751. * of deleting a seed device, the cur_devices should point to
  1752. * its own fs_devices listed under the fs_devices->seed.
  1753. */
  1754. cur_devices = device->fs_devices;
  1755. mutex_lock(&fs_devices->device_list_mutex);
  1756. list_del_rcu(&device->dev_list);
  1757. cur_devices->num_devices--;
  1758. cur_devices->total_devices--;
  1759. if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
  1760. cur_devices->missing_devices--;
  1761. btrfs_assign_next_active_device(fs_info, device, NULL);
  1762. if (device->bdev) {
  1763. cur_devices->open_devices--;
  1764. /* remove sysfs entry */
  1765. btrfs_sysfs_rm_device_link(fs_devices, device);
  1766. }
  1767. num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
  1768. btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
  1769. mutex_unlock(&fs_devices->device_list_mutex);
  1770. /*
  1771. * at this point, the device is zero sized and detached from
  1772. * the devices list. All that's left is to zero out the old
  1773. * supers and free the device.
  1774. */
  1775. if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
  1776. btrfs_scratch_superblocks(device->bdev, device->name->str);
  1777. btrfs_close_bdev(device);
  1778. call_rcu(&device->rcu, free_device_rcu);
  1779. if (cur_devices->open_devices == 0) {
  1780. while (fs_devices) {
  1781. if (fs_devices->seed == cur_devices) {
  1782. fs_devices->seed = cur_devices->seed;
  1783. break;
  1784. }
  1785. fs_devices = fs_devices->seed;
  1786. }
  1787. cur_devices->seed = NULL;
  1788. close_fs_devices(cur_devices);
  1789. free_fs_devices(cur_devices);
  1790. }
  1791. out:
  1792. mutex_unlock(&uuid_mutex);
  1793. return ret;
  1794. error_undo:
  1795. if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
  1796. mutex_lock(&fs_info->chunk_mutex);
  1797. list_add(&device->dev_alloc_list,
  1798. &fs_devices->alloc_list);
  1799. device->fs_devices->rw_devices++;
  1800. mutex_unlock(&fs_info->chunk_mutex);
  1801. }
  1802. goto out;
  1803. }
  1804. void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
  1805. struct btrfs_device *srcdev)
  1806. {
  1807. struct btrfs_fs_devices *fs_devices;
  1808. lockdep_assert_held(&fs_info->fs_devices->device_list_mutex);
  1809. /*
  1810. * in case of fs with no seed, srcdev->fs_devices will point
  1811. * to fs_devices of fs_info. However when the dev being replaced is
  1812. * a seed dev it will point to the seed's local fs_devices. In short
  1813. * srcdev will have its correct fs_devices in both the cases.
  1814. */
  1815. fs_devices = srcdev->fs_devices;
  1816. list_del_rcu(&srcdev->dev_list);
  1817. list_del(&srcdev->dev_alloc_list);
  1818. fs_devices->num_devices--;
  1819. if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
  1820. fs_devices->missing_devices--;
  1821. if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
  1822. fs_devices->rw_devices--;
  1823. if (srcdev->bdev)
  1824. fs_devices->open_devices--;
  1825. }
  1826. void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
  1827. struct btrfs_device *srcdev)
  1828. {
  1829. struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
  1830. if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
  1831. /* zero out the old super if it is writable */
  1832. btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
  1833. }
  1834. btrfs_close_bdev(srcdev);
  1835. call_rcu(&srcdev->rcu, free_device_rcu);
  1836. /* if this is no devs we rather delete the fs_devices */
  1837. if (!fs_devices->num_devices) {
  1838. struct btrfs_fs_devices *tmp_fs_devices;
  1839. /*
  1840. * On a mounted FS, num_devices can't be zero unless it's a
  1841. * seed. In case of a seed device being replaced, the replace
  1842. * target added to the sprout FS, so there will be no more
  1843. * device left under the seed FS.
  1844. */
  1845. ASSERT(fs_devices->seeding);
  1846. tmp_fs_devices = fs_info->fs_devices;
  1847. while (tmp_fs_devices) {
  1848. if (tmp_fs_devices->seed == fs_devices) {
  1849. tmp_fs_devices->seed = fs_devices->seed;
  1850. break;
  1851. }
  1852. tmp_fs_devices = tmp_fs_devices->seed;
  1853. }
  1854. fs_devices->seed = NULL;
  1855. close_fs_devices(fs_devices);
  1856. free_fs_devices(fs_devices);
  1857. }
  1858. }
  1859. void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
  1860. struct btrfs_device *tgtdev)
  1861. {
  1862. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  1863. WARN_ON(!tgtdev);
  1864. mutex_lock(&fs_devices->device_list_mutex);
  1865. btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
  1866. if (tgtdev->bdev)
  1867. fs_devices->open_devices--;
  1868. fs_devices->num_devices--;
  1869. btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
  1870. list_del_rcu(&tgtdev->dev_list);
  1871. mutex_unlock(&fs_devices->device_list_mutex);
  1872. /*
  1873. * The update_dev_time() with in btrfs_scratch_superblocks()
  1874. * may lead to a call to btrfs_show_devname() which will try
  1875. * to hold device_list_mutex. And here this device
  1876. * is already out of device list, so we don't have to hold
  1877. * the device_list_mutex lock.
  1878. */
  1879. btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
  1880. btrfs_close_bdev(tgtdev);
  1881. call_rcu(&tgtdev->rcu, free_device_rcu);
  1882. }
  1883. static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
  1884. const char *device_path,
  1885. struct btrfs_device **device)
  1886. {
  1887. int ret = 0;
  1888. struct btrfs_super_block *disk_super;
  1889. u64 devid;
  1890. u8 *dev_uuid;
  1891. struct block_device *bdev;
  1892. struct buffer_head *bh;
  1893. *device = NULL;
  1894. ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
  1895. fs_info->bdev_holder, 0, &bdev, &bh);
  1896. if (ret)
  1897. return ret;
  1898. disk_super = (struct btrfs_super_block *)bh->b_data;
  1899. devid = btrfs_stack_device_id(&disk_super->dev_item);
  1900. dev_uuid = disk_super->dev_item.uuid;
  1901. *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
  1902. brelse(bh);
  1903. if (!*device)
  1904. ret = -ENOENT;
  1905. blkdev_put(bdev, FMODE_READ);
  1906. return ret;
  1907. }
  1908. int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
  1909. const char *device_path,
  1910. struct btrfs_device **device)
  1911. {
  1912. *device = NULL;
  1913. if (strcmp(device_path, "missing") == 0) {
  1914. struct list_head *devices;
  1915. struct btrfs_device *tmp;
  1916. devices = &fs_info->fs_devices->devices;
  1917. list_for_each_entry(tmp, devices, dev_list) {
  1918. if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
  1919. &tmp->dev_state) && !tmp->bdev) {
  1920. *device = tmp;
  1921. break;
  1922. }
  1923. }
  1924. if (!*device)
  1925. return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
  1926. return 0;
  1927. } else {
  1928. return btrfs_find_device_by_path(fs_info, device_path, device);
  1929. }
  1930. }
  1931. /*
  1932. * Lookup a device given by device id, or the path if the id is 0.
  1933. */
  1934. int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
  1935. const char *devpath,
  1936. struct btrfs_device **device)
  1937. {
  1938. int ret;
  1939. if (devid) {
  1940. ret = 0;
  1941. *device = btrfs_find_device(fs_info, devid, NULL, NULL);
  1942. if (!*device)
  1943. ret = -ENOENT;
  1944. } else {
  1945. if (!devpath || !devpath[0])
  1946. return -EINVAL;
  1947. ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
  1948. device);
  1949. }
  1950. return ret;
  1951. }
  1952. /*
  1953. * does all the dirty work required for changing file system's UUID.
  1954. */
  1955. static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
  1956. {
  1957. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  1958. struct btrfs_fs_devices *old_devices;
  1959. struct btrfs_fs_devices *seed_devices;
  1960. struct btrfs_super_block *disk_super = fs_info->super_copy;
  1961. struct btrfs_device *device;
  1962. u64 super_flags;
  1963. lockdep_assert_held(&uuid_mutex);
  1964. if (!fs_devices->seeding)
  1965. return -EINVAL;
  1966. seed_devices = alloc_fs_devices(NULL);
  1967. if (IS_ERR(seed_devices))
  1968. return PTR_ERR(seed_devices);
  1969. old_devices = clone_fs_devices(fs_devices);
  1970. if (IS_ERR(old_devices)) {
  1971. kfree(seed_devices);
  1972. return PTR_ERR(old_devices);
  1973. }
  1974. list_add(&old_devices->fs_list, &fs_uuids);
  1975. memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
  1976. seed_devices->opened = 1;
  1977. INIT_LIST_HEAD(&seed_devices->devices);
  1978. INIT_LIST_HEAD(&seed_devices->alloc_list);
  1979. mutex_init(&seed_devices->device_list_mutex);
  1980. mutex_lock(&fs_info->fs_devices->device_list_mutex);
  1981. list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
  1982. synchronize_rcu);
  1983. list_for_each_entry(device, &seed_devices->devices, dev_list)
  1984. device->fs_devices = seed_devices;
  1985. mutex_lock(&fs_info->chunk_mutex);
  1986. list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
  1987. mutex_unlock(&fs_info->chunk_mutex);
  1988. fs_devices->seeding = 0;
  1989. fs_devices->num_devices = 0;
  1990. fs_devices->open_devices = 0;
  1991. fs_devices->missing_devices = 0;
  1992. fs_devices->rotating = 0;
  1993. fs_devices->seed = seed_devices;
  1994. generate_random_uuid(fs_devices->fsid);
  1995. memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
  1996. memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
  1997. mutex_unlock(&fs_info->fs_devices->device_list_mutex);
  1998. super_flags = btrfs_super_flags(disk_super) &
  1999. ~BTRFS_SUPER_FLAG_SEEDING;
  2000. btrfs_set_super_flags(disk_super, super_flags);
  2001. return 0;
  2002. }
  2003. /*
  2004. * Store the expected generation for seed devices in device items.
  2005. */
  2006. static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
  2007. struct btrfs_fs_info *fs_info)
  2008. {
  2009. struct btrfs_root *root = fs_info->chunk_root;
  2010. struct btrfs_path *path;
  2011. struct extent_buffer *leaf;
  2012. struct btrfs_dev_item *dev_item;
  2013. struct btrfs_device *device;
  2014. struct btrfs_key key;
  2015. u8 fs_uuid[BTRFS_FSID_SIZE];
  2016. u8 dev_uuid[BTRFS_UUID_SIZE];
  2017. u64 devid;
  2018. int ret;
  2019. path = btrfs_alloc_path();
  2020. if (!path)
  2021. return -ENOMEM;
  2022. key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
  2023. key.offset = 0;
  2024. key.type = BTRFS_DEV_ITEM_KEY;
  2025. while (1) {
  2026. ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
  2027. if (ret < 0)
  2028. goto error;
  2029. leaf = path->nodes[0];
  2030. next_slot:
  2031. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  2032. ret = btrfs_next_leaf(root, path);
  2033. if (ret > 0)
  2034. break;
  2035. if (ret < 0)
  2036. goto error;
  2037. leaf = path->nodes[0];
  2038. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  2039. btrfs_release_path(path);
  2040. continue;
  2041. }
  2042. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  2043. if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
  2044. key.type != BTRFS_DEV_ITEM_KEY)
  2045. break;
  2046. dev_item = btrfs_item_ptr(leaf, path->slots[0],
  2047. struct btrfs_dev_item);
  2048. devid = btrfs_device_id(leaf, dev_item);
  2049. read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
  2050. BTRFS_UUID_SIZE);
  2051. read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
  2052. BTRFS_FSID_SIZE);
  2053. device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
  2054. BUG_ON(!device); /* Logic error */
  2055. if (device->fs_devices->seeding) {
  2056. btrfs_set_device_generation(leaf, dev_item,
  2057. device->generation);
  2058. btrfs_mark_buffer_dirty(leaf);
  2059. }
  2060. path->slots[0]++;
  2061. goto next_slot;
  2062. }
  2063. ret = 0;
  2064. error:
  2065. btrfs_free_path(path);
  2066. return ret;
  2067. }
  2068. int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
  2069. {
  2070. struct btrfs_root *root = fs_info->dev_root;
  2071. struct request_queue *q;
  2072. struct btrfs_trans_handle *trans;
  2073. struct btrfs_device *device;
  2074. struct block_device *bdev;
  2075. struct list_head *devices;
  2076. struct super_block *sb = fs_info->sb;
  2077. struct rcu_string *name;
  2078. u64 tmp;
  2079. int seeding_dev = 0;
  2080. int ret = 0;
  2081. bool unlocked = false;
  2082. if (sb_rdonly(sb) && !fs_info->fs_devices->seeding)
  2083. return -EROFS;
  2084. bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
  2085. fs_info->bdev_holder);
  2086. if (IS_ERR(bdev))
  2087. return PTR_ERR(bdev);
  2088. if (fs_info->fs_devices->seeding) {
  2089. seeding_dev = 1;
  2090. down_write(&sb->s_umount);
  2091. mutex_lock(&uuid_mutex);
  2092. }
  2093. filemap_write_and_wait(bdev->bd_inode->i_mapping);
  2094. devices = &fs_info->fs_devices->devices;
  2095. mutex_lock(&fs_info->fs_devices->device_list_mutex);
  2096. list_for_each_entry(device, devices, dev_list) {
  2097. if (device->bdev == bdev) {
  2098. ret = -EEXIST;
  2099. mutex_unlock(
  2100. &fs_info->fs_devices->device_list_mutex);
  2101. goto error;
  2102. }
  2103. }
  2104. mutex_unlock(&fs_info->fs_devices->device_list_mutex);
  2105. device = btrfs_alloc_device(fs_info, NULL, NULL);
  2106. if (IS_ERR(device)) {
  2107. /* we can safely leave the fs_devices entry around */
  2108. ret = PTR_ERR(device);
  2109. goto error;
  2110. }
  2111. name = rcu_string_strdup(device_path, GFP_KERNEL);
  2112. if (!name) {
  2113. ret = -ENOMEM;
  2114. goto error_free_device;
  2115. }
  2116. rcu_assign_pointer(device->name, name);
  2117. trans = btrfs_start_transaction(root, 0);
  2118. if (IS_ERR(trans)) {
  2119. ret = PTR_ERR(trans);
  2120. goto error_free_device;
  2121. }
  2122. q = bdev_get_queue(bdev);
  2123. set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
  2124. device->generation = trans->transid;
  2125. device->io_width = fs_info->sectorsize;
  2126. device->io_align = fs_info->sectorsize;
  2127. device->sector_size = fs_info->sectorsize;
  2128. device->total_bytes = round_down(i_size_read(bdev->bd_inode),
  2129. fs_info->sectorsize);
  2130. device->disk_total_bytes = device->total_bytes;
  2131. device->commit_total_bytes = device->total_bytes;
  2132. device->fs_info = fs_info;
  2133. device->bdev = bdev;
  2134. set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
  2135. clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
  2136. device->mode = FMODE_EXCL;
  2137. device->dev_stats_valid = 1;
  2138. set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
  2139. if (seeding_dev) {
  2140. sb->s_flags &= ~SB_RDONLY;
  2141. ret = btrfs_prepare_sprout(fs_info);
  2142. if (ret) {
  2143. btrfs_abort_transaction(trans, ret);
  2144. goto error_trans;
  2145. }
  2146. }
  2147. device->fs_devices = fs_info->fs_devices;
  2148. mutex_lock(&fs_info->fs_devices->device_list_mutex);
  2149. mutex_lock(&fs_info->chunk_mutex);
  2150. list_add_rcu(&device->dev_list, &fs_info->fs_devices->devices);
  2151. list_add(&device->dev_alloc_list,
  2152. &fs_info->fs_devices->alloc_list);
  2153. fs_info->fs_devices->num_devices++;
  2154. fs_info->fs_devices->open_devices++;
  2155. fs_info->fs_devices->rw_devices++;
  2156. fs_info->fs_devices->total_devices++;
  2157. fs_info->fs_devices->total_rw_bytes += device->total_bytes;
  2158. atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
  2159. if (!blk_queue_nonrot(q))
  2160. fs_info->fs_devices->rotating = 1;
  2161. tmp = btrfs_super_total_bytes(fs_info->super_copy);
  2162. btrfs_set_super_total_bytes(fs_info->super_copy,
  2163. round_down(tmp + device->total_bytes, fs_info->sectorsize));
  2164. tmp = btrfs_super_num_devices(fs_info->super_copy);
  2165. btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
  2166. /* add sysfs device entry */
  2167. btrfs_sysfs_add_device_link(fs_info->fs_devices, device);
  2168. /*
  2169. * we've got more storage, clear any full flags on the space
  2170. * infos
  2171. */
  2172. btrfs_clear_space_info_full(fs_info);
  2173. mutex_unlock(&fs_info->chunk_mutex);
  2174. mutex_unlock(&fs_info->fs_devices->device_list_mutex);
  2175. if (seeding_dev) {
  2176. mutex_lock(&fs_info->chunk_mutex);
  2177. ret = init_first_rw_device(trans, fs_info);
  2178. mutex_unlock(&fs_info->chunk_mutex);
  2179. if (ret) {
  2180. btrfs_abort_transaction(trans, ret);
  2181. goto error_sysfs;
  2182. }
  2183. }
  2184. ret = btrfs_add_dev_item(trans, fs_info, device);
  2185. if (ret) {
  2186. btrfs_abort_transaction(trans, ret);
  2187. goto error_sysfs;
  2188. }
  2189. if (seeding_dev) {
  2190. char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
  2191. ret = btrfs_finish_sprout(trans, fs_info);
  2192. if (ret) {
  2193. btrfs_abort_transaction(trans, ret);
  2194. goto error_sysfs;
  2195. }
  2196. /* Sprouting would change fsid of the mounted root,
  2197. * so rename the fsid on the sysfs
  2198. */
  2199. snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
  2200. fs_info->fsid);
  2201. if (kobject_rename(&fs_info->fs_devices->fsid_kobj, fsid_buf))
  2202. btrfs_warn(fs_info,
  2203. "sysfs: failed to create fsid for sprout");
  2204. }
  2205. ret = btrfs_commit_transaction(trans);
  2206. if (seeding_dev) {
  2207. mutex_unlock(&uuid_mutex);
  2208. up_write(&sb->s_umount);
  2209. unlocked = true;
  2210. if (ret) /* transaction commit */
  2211. return ret;
  2212. ret = btrfs_relocate_sys_chunks(fs_info);
  2213. if (ret < 0)
  2214. btrfs_handle_fs_error(fs_info, ret,
  2215. "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
  2216. trans = btrfs_attach_transaction(root);
  2217. if (IS_ERR(trans)) {
  2218. if (PTR_ERR(trans) == -ENOENT)
  2219. return 0;
  2220. ret = PTR_ERR(trans);
  2221. trans = NULL;
  2222. goto error_sysfs;
  2223. }
  2224. ret = btrfs_commit_transaction(trans);
  2225. }
  2226. /* Update ctime/mtime for libblkid */
  2227. update_dev_time(device_path);
  2228. return ret;
  2229. error_sysfs:
  2230. btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
  2231. error_trans:
  2232. if (seeding_dev)
  2233. sb->s_flags |= SB_RDONLY;
  2234. if (trans)
  2235. btrfs_end_transaction(trans);
  2236. error_free_device:
  2237. btrfs_free_device(device);
  2238. error:
  2239. blkdev_put(bdev, FMODE_EXCL);
  2240. if (seeding_dev && !unlocked) {
  2241. mutex_unlock(&uuid_mutex);
  2242. up_write(&sb->s_umount);
  2243. }
  2244. return ret;
  2245. }
  2246. static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
  2247. struct btrfs_device *device)
  2248. {
  2249. int ret;
  2250. struct btrfs_path *path;
  2251. struct btrfs_root *root = device->fs_info->chunk_root;
  2252. struct btrfs_dev_item *dev_item;
  2253. struct extent_buffer *leaf;
  2254. struct btrfs_key key;
  2255. path = btrfs_alloc_path();
  2256. if (!path)
  2257. return -ENOMEM;
  2258. key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
  2259. key.type = BTRFS_DEV_ITEM_KEY;
  2260. key.offset = device->devid;
  2261. ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
  2262. if (ret < 0)
  2263. goto out;
  2264. if (ret > 0) {
  2265. ret = -ENOENT;
  2266. goto out;
  2267. }
  2268. leaf = path->nodes[0];
  2269. dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
  2270. btrfs_set_device_id(leaf, dev_item, device->devid);
  2271. btrfs_set_device_type(leaf, dev_item, device->type);
  2272. btrfs_set_device_io_align(leaf, dev_item, device->io_align);
  2273. btrfs_set_device_io_width(leaf, dev_item, device->io_width);
  2274. btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
  2275. btrfs_set_device_total_bytes(leaf, dev_item,
  2276. btrfs_device_get_disk_total_bytes(device));
  2277. btrfs_set_device_bytes_used(leaf, dev_item,
  2278. btrfs_device_get_bytes_used(device));
  2279. btrfs_mark_buffer_dirty(leaf);
  2280. out:
  2281. btrfs_free_path(path);
  2282. return ret;
  2283. }
  2284. int btrfs_grow_device(struct btrfs_trans_handle *trans,
  2285. struct btrfs_device *device, u64 new_size)
  2286. {
  2287. struct btrfs_fs_info *fs_info = device->fs_info;
  2288. struct btrfs_super_block *super_copy = fs_info->super_copy;
  2289. struct btrfs_fs_devices *fs_devices;
  2290. u64 old_total;
  2291. u64 diff;
  2292. if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
  2293. return -EACCES;
  2294. new_size = round_down(new_size, fs_info->sectorsize);
  2295. mutex_lock(&fs_info->chunk_mutex);
  2296. old_total = btrfs_super_total_bytes(super_copy);
  2297. diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
  2298. if (new_size <= device->total_bytes ||
  2299. test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
  2300. mutex_unlock(&fs_info->chunk_mutex);
  2301. return -EINVAL;
  2302. }
  2303. fs_devices = fs_info->fs_devices;
  2304. btrfs_set_super_total_bytes(super_copy,
  2305. round_down(old_total + diff, fs_info->sectorsize));
  2306. device->fs_devices->total_rw_bytes += diff;
  2307. btrfs_device_set_total_bytes(device, new_size);
  2308. btrfs_device_set_disk_total_bytes(device, new_size);
  2309. btrfs_clear_space_info_full(device->fs_info);
  2310. if (list_empty(&device->resized_list))
  2311. list_add_tail(&device->resized_list,
  2312. &fs_devices->resized_devices);
  2313. mutex_unlock(&fs_info->chunk_mutex);
  2314. return btrfs_update_device(trans, device);
  2315. }
  2316. static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
  2317. struct btrfs_fs_info *fs_info, u64 chunk_offset)
  2318. {
  2319. struct btrfs_root *root = fs_info->chunk_root;
  2320. int ret;
  2321. struct btrfs_path *path;
  2322. struct btrfs_key key;
  2323. path = btrfs_alloc_path();
  2324. if (!path)
  2325. return -ENOMEM;
  2326. key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
  2327. key.offset = chunk_offset;
  2328. key.type = BTRFS_CHUNK_ITEM_KEY;
  2329. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  2330. if (ret < 0)
  2331. goto out;
  2332. else if (ret > 0) { /* Logic error or corruption */
  2333. btrfs_handle_fs_error(fs_info, -ENOENT,
  2334. "Failed lookup while freeing chunk.");
  2335. ret = -ENOENT;
  2336. goto out;
  2337. }
  2338. ret = btrfs_del_item(trans, root, path);
  2339. if (ret < 0)
  2340. btrfs_handle_fs_error(fs_info, ret,
  2341. "Failed to delete chunk item.");
  2342. out:
  2343. btrfs_free_path(path);
  2344. return ret;
  2345. }
  2346. static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
  2347. {
  2348. struct btrfs_super_block *super_copy = fs_info->super_copy;
  2349. struct btrfs_disk_key *disk_key;
  2350. struct btrfs_chunk *chunk;
  2351. u8 *ptr;
  2352. int ret = 0;
  2353. u32 num_stripes;
  2354. u32 array_size;
  2355. u32 len = 0;
  2356. u32 cur;
  2357. struct btrfs_key key;
  2358. mutex_lock(&fs_info->chunk_mutex);
  2359. array_size = btrfs_super_sys_array_size(super_copy);
  2360. ptr = super_copy->sys_chunk_array;
  2361. cur = 0;
  2362. while (cur < array_size) {
  2363. disk_key = (struct btrfs_disk_key *)ptr;
  2364. btrfs_disk_key_to_cpu(&key, disk_key);
  2365. len = sizeof(*disk_key);
  2366. if (key.type == BTRFS_CHUNK_ITEM_KEY) {
  2367. chunk = (struct btrfs_chunk *)(ptr + len);
  2368. num_stripes = btrfs_stack_chunk_num_stripes(chunk);
  2369. len += btrfs_chunk_item_size(num_stripes);
  2370. } else {
  2371. ret = -EIO;
  2372. break;
  2373. }
  2374. if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
  2375. key.offset == chunk_offset) {
  2376. memmove(ptr, ptr + len, array_size - (cur + len));
  2377. array_size -= len;
  2378. btrfs_set_super_sys_array_size(super_copy, array_size);
  2379. } else {
  2380. ptr += len;
  2381. cur += len;
  2382. }
  2383. }
  2384. mutex_unlock(&fs_info->chunk_mutex);
  2385. return ret;
  2386. }
  2387. static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
  2388. u64 logical, u64 length)
  2389. {
  2390. struct extent_map_tree *em_tree;
  2391. struct extent_map *em;
  2392. em_tree = &fs_info->mapping_tree.map_tree;
  2393. read_lock(&em_tree->lock);
  2394. em = lookup_extent_mapping(em_tree, logical, length);
  2395. read_unlock(&em_tree->lock);
  2396. if (!em) {
  2397. btrfs_crit(fs_info, "unable to find logical %llu length %llu",
  2398. logical, length);
  2399. return ERR_PTR(-EINVAL);
  2400. }
  2401. if (em->start > logical || em->start + em->len < logical) {
  2402. btrfs_crit(fs_info,
  2403. "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
  2404. logical, length, em->start, em->start + em->len);
  2405. free_extent_map(em);
  2406. return ERR_PTR(-EINVAL);
  2407. }
  2408. /* callers are responsible for dropping em's ref. */
  2409. return em;
  2410. }
  2411. int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
  2412. struct btrfs_fs_info *fs_info, u64 chunk_offset)
  2413. {
  2414. struct extent_map *em;
  2415. struct map_lookup *map;
  2416. u64 dev_extent_len = 0;
  2417. int i, ret = 0;
  2418. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  2419. em = get_chunk_map(fs_info, chunk_offset, 1);
  2420. if (IS_ERR(em)) {
  2421. /*
  2422. * This is a logic error, but we don't want to just rely on the
  2423. * user having built with ASSERT enabled, so if ASSERT doesn't
  2424. * do anything we still error out.
  2425. */
  2426. ASSERT(0);
  2427. return PTR_ERR(em);
  2428. }
  2429. map = em->map_lookup;
  2430. mutex_lock(&fs_info->chunk_mutex);
  2431. check_system_chunk(trans, fs_info, map->type);
  2432. mutex_unlock(&fs_info->chunk_mutex);
  2433. /*
  2434. * Take the device list mutex to prevent races with the final phase of
  2435. * a device replace operation that replaces the device object associated
  2436. * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
  2437. */
  2438. mutex_lock(&fs_devices->device_list_mutex);
  2439. for (i = 0; i < map->num_stripes; i++) {
  2440. struct btrfs_device *device = map->stripes[i].dev;
  2441. ret = btrfs_free_dev_extent(trans, device,
  2442. map->stripes[i].physical,
  2443. &dev_extent_len);
  2444. if (ret) {
  2445. mutex_unlock(&fs_devices->device_list_mutex);
  2446. btrfs_abort_transaction(trans, ret);
  2447. goto out;
  2448. }
  2449. if (device->bytes_used > 0) {
  2450. mutex_lock(&fs_info->chunk_mutex);
  2451. btrfs_device_set_bytes_used(device,
  2452. device->bytes_used - dev_extent_len);
  2453. atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
  2454. btrfs_clear_space_info_full(fs_info);
  2455. mutex_unlock(&fs_info->chunk_mutex);
  2456. }
  2457. if (map->stripes[i].dev) {
  2458. ret = btrfs_update_device(trans, map->stripes[i].dev);
  2459. if (ret) {
  2460. mutex_unlock(&fs_devices->device_list_mutex);
  2461. btrfs_abort_transaction(trans, ret);
  2462. goto out;
  2463. }
  2464. }
  2465. }
  2466. mutex_unlock(&fs_devices->device_list_mutex);
  2467. ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
  2468. if (ret) {
  2469. btrfs_abort_transaction(trans, ret);
  2470. goto out;
  2471. }
  2472. trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
  2473. if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
  2474. ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
  2475. if (ret) {
  2476. btrfs_abort_transaction(trans, ret);
  2477. goto out;
  2478. }
  2479. }
  2480. ret = btrfs_remove_block_group(trans, fs_info, chunk_offset, em);
  2481. if (ret) {
  2482. btrfs_abort_transaction(trans, ret);
  2483. goto out;
  2484. }
  2485. out:
  2486. /* once for us */
  2487. free_extent_map(em);
  2488. return ret;
  2489. }
  2490. static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
  2491. {
  2492. struct btrfs_root *root = fs_info->chunk_root;
  2493. struct btrfs_trans_handle *trans;
  2494. int ret;
  2495. /*
  2496. * Prevent races with automatic removal of unused block groups.
  2497. * After we relocate and before we remove the chunk with offset
  2498. * chunk_offset, automatic removal of the block group can kick in,
  2499. * resulting in a failure when calling btrfs_remove_chunk() below.
  2500. *
  2501. * Make sure to acquire this mutex before doing a tree search (dev
  2502. * or chunk trees) to find chunks. Otherwise the cleaner kthread might
  2503. * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
  2504. * we release the path used to search the chunk/dev tree and before
  2505. * the current task acquires this mutex and calls us.
  2506. */
  2507. lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
  2508. ret = btrfs_can_relocate(fs_info, chunk_offset);
  2509. if (ret)
  2510. return -ENOSPC;
  2511. /* step one, relocate all the extents inside this chunk */
  2512. btrfs_scrub_pause(fs_info);
  2513. ret = btrfs_relocate_block_group(fs_info, chunk_offset);
  2514. btrfs_scrub_continue(fs_info);
  2515. if (ret)
  2516. return ret;
  2517. /*
  2518. * We add the kobjects here (and after forcing data chunk creation)
  2519. * since relocation is the only place we'll create chunks of a new
  2520. * type at runtime. The only place where we'll remove the last
  2521. * chunk of a type is the call immediately below this one. Even
  2522. * so, we're protected against races with the cleaner thread since
  2523. * we're covered by the delete_unused_bgs_mutex.
  2524. */
  2525. btrfs_add_raid_kobjects(fs_info);
  2526. trans = btrfs_start_trans_remove_block_group(root->fs_info,
  2527. chunk_offset);
  2528. if (IS_ERR(trans)) {
  2529. ret = PTR_ERR(trans);
  2530. btrfs_handle_fs_error(root->fs_info, ret, NULL);
  2531. return ret;
  2532. }
  2533. /*
  2534. * step two, delete the device extents and the
  2535. * chunk tree entries
  2536. */
  2537. ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
  2538. btrfs_end_transaction(trans);
  2539. return ret;
  2540. }
  2541. static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
  2542. {
  2543. struct btrfs_root *chunk_root = fs_info->chunk_root;
  2544. struct btrfs_path *path;
  2545. struct extent_buffer *leaf;
  2546. struct btrfs_chunk *chunk;
  2547. struct btrfs_key key;
  2548. struct btrfs_key found_key;
  2549. u64 chunk_type;
  2550. bool retried = false;
  2551. int failed = 0;
  2552. int ret;
  2553. path = btrfs_alloc_path();
  2554. if (!path)
  2555. return -ENOMEM;
  2556. again:
  2557. key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
  2558. key.offset = (u64)-1;
  2559. key.type = BTRFS_CHUNK_ITEM_KEY;
  2560. while (1) {
  2561. mutex_lock(&fs_info->delete_unused_bgs_mutex);
  2562. ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
  2563. if (ret < 0) {
  2564. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  2565. goto error;
  2566. }
  2567. BUG_ON(ret == 0); /* Corruption */
  2568. ret = btrfs_previous_item(chunk_root, path, key.objectid,
  2569. key.type);
  2570. if (ret)
  2571. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  2572. if (ret < 0)
  2573. goto error;
  2574. if (ret > 0)
  2575. break;
  2576. leaf = path->nodes[0];
  2577. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  2578. chunk = btrfs_item_ptr(leaf, path->slots[0],
  2579. struct btrfs_chunk);
  2580. chunk_type = btrfs_chunk_type(leaf, chunk);
  2581. btrfs_release_path(path);
  2582. if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
  2583. ret = btrfs_relocate_chunk(fs_info, found_key.offset);
  2584. if (ret == -ENOSPC)
  2585. failed++;
  2586. else
  2587. BUG_ON(ret);
  2588. }
  2589. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  2590. if (found_key.offset == 0)
  2591. break;
  2592. key.offset = found_key.offset - 1;
  2593. }
  2594. ret = 0;
  2595. if (failed && !retried) {
  2596. failed = 0;
  2597. retried = true;
  2598. goto again;
  2599. } else if (WARN_ON(failed && retried)) {
  2600. ret = -ENOSPC;
  2601. }
  2602. error:
  2603. btrfs_free_path(path);
  2604. return ret;
  2605. }
  2606. /*
  2607. * return 1 : allocate a data chunk successfully,
  2608. * return <0: errors during allocating a data chunk,
  2609. * return 0 : no need to allocate a data chunk.
  2610. */
  2611. static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
  2612. u64 chunk_offset)
  2613. {
  2614. struct btrfs_block_group_cache *cache;
  2615. u64 bytes_used;
  2616. u64 chunk_type;
  2617. cache = btrfs_lookup_block_group(fs_info, chunk_offset);
  2618. ASSERT(cache);
  2619. chunk_type = cache->flags;
  2620. btrfs_put_block_group(cache);
  2621. if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
  2622. spin_lock(&fs_info->data_sinfo->lock);
  2623. bytes_used = fs_info->data_sinfo->bytes_used;
  2624. spin_unlock(&fs_info->data_sinfo->lock);
  2625. if (!bytes_used) {
  2626. struct btrfs_trans_handle *trans;
  2627. int ret;
  2628. trans = btrfs_join_transaction(fs_info->tree_root);
  2629. if (IS_ERR(trans))
  2630. return PTR_ERR(trans);
  2631. ret = btrfs_force_chunk_alloc(trans, fs_info,
  2632. BTRFS_BLOCK_GROUP_DATA);
  2633. btrfs_end_transaction(trans);
  2634. if (ret < 0)
  2635. return ret;
  2636. btrfs_add_raid_kobjects(fs_info);
  2637. return 1;
  2638. }
  2639. }
  2640. return 0;
  2641. }
  2642. static int insert_balance_item(struct btrfs_fs_info *fs_info,
  2643. struct btrfs_balance_control *bctl)
  2644. {
  2645. struct btrfs_root *root = fs_info->tree_root;
  2646. struct btrfs_trans_handle *trans;
  2647. struct btrfs_balance_item *item;
  2648. struct btrfs_disk_balance_args disk_bargs;
  2649. struct btrfs_path *path;
  2650. struct extent_buffer *leaf;
  2651. struct btrfs_key key;
  2652. int ret, err;
  2653. path = btrfs_alloc_path();
  2654. if (!path)
  2655. return -ENOMEM;
  2656. trans = btrfs_start_transaction(root, 0);
  2657. if (IS_ERR(trans)) {
  2658. btrfs_free_path(path);
  2659. return PTR_ERR(trans);
  2660. }
  2661. key.objectid = BTRFS_BALANCE_OBJECTID;
  2662. key.type = BTRFS_TEMPORARY_ITEM_KEY;
  2663. key.offset = 0;
  2664. ret = btrfs_insert_empty_item(trans, root, path, &key,
  2665. sizeof(*item));
  2666. if (ret)
  2667. goto out;
  2668. leaf = path->nodes[0];
  2669. item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
  2670. memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
  2671. btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
  2672. btrfs_set_balance_data(leaf, item, &disk_bargs);
  2673. btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
  2674. btrfs_set_balance_meta(leaf, item, &disk_bargs);
  2675. btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
  2676. btrfs_set_balance_sys(leaf, item, &disk_bargs);
  2677. btrfs_set_balance_flags(leaf, item, bctl->flags);
  2678. btrfs_mark_buffer_dirty(leaf);
  2679. out:
  2680. btrfs_free_path(path);
  2681. err = btrfs_commit_transaction(trans);
  2682. if (err && !ret)
  2683. ret = err;
  2684. return ret;
  2685. }
  2686. static int del_balance_item(struct btrfs_fs_info *fs_info)
  2687. {
  2688. struct btrfs_root *root = fs_info->tree_root;
  2689. struct btrfs_trans_handle *trans;
  2690. struct btrfs_path *path;
  2691. struct btrfs_key key;
  2692. int ret, err;
  2693. path = btrfs_alloc_path();
  2694. if (!path)
  2695. return -ENOMEM;
  2696. trans = btrfs_start_transaction(root, 0);
  2697. if (IS_ERR(trans)) {
  2698. btrfs_free_path(path);
  2699. return PTR_ERR(trans);
  2700. }
  2701. key.objectid = BTRFS_BALANCE_OBJECTID;
  2702. key.type = BTRFS_TEMPORARY_ITEM_KEY;
  2703. key.offset = 0;
  2704. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  2705. if (ret < 0)
  2706. goto out;
  2707. if (ret > 0) {
  2708. ret = -ENOENT;
  2709. goto out;
  2710. }
  2711. ret = btrfs_del_item(trans, root, path);
  2712. out:
  2713. btrfs_free_path(path);
  2714. err = btrfs_commit_transaction(trans);
  2715. if (err && !ret)
  2716. ret = err;
  2717. return ret;
  2718. }
  2719. /*
  2720. * This is a heuristic used to reduce the number of chunks balanced on
  2721. * resume after balance was interrupted.
  2722. */
  2723. static void update_balance_args(struct btrfs_balance_control *bctl)
  2724. {
  2725. /*
  2726. * Turn on soft mode for chunk types that were being converted.
  2727. */
  2728. if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
  2729. bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
  2730. if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
  2731. bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
  2732. if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
  2733. bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
  2734. /*
  2735. * Turn on usage filter if is not already used. The idea is
  2736. * that chunks that we have already balanced should be
  2737. * reasonably full. Don't do it for chunks that are being
  2738. * converted - that will keep us from relocating unconverted
  2739. * (albeit full) chunks.
  2740. */
  2741. if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
  2742. !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
  2743. !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
  2744. bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
  2745. bctl->data.usage = 90;
  2746. }
  2747. if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
  2748. !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
  2749. !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
  2750. bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
  2751. bctl->sys.usage = 90;
  2752. }
  2753. if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
  2754. !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
  2755. !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
  2756. bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
  2757. bctl->meta.usage = 90;
  2758. }
  2759. }
  2760. /*
  2761. * Clear the balance status in fs_info and delete the balance item from disk.
  2762. */
  2763. static void reset_balance_state(struct btrfs_fs_info *fs_info)
  2764. {
  2765. struct btrfs_balance_control *bctl = fs_info->balance_ctl;
  2766. int ret;
  2767. BUG_ON(!fs_info->balance_ctl);
  2768. spin_lock(&fs_info->balance_lock);
  2769. fs_info->balance_ctl = NULL;
  2770. spin_unlock(&fs_info->balance_lock);
  2771. kfree(bctl);
  2772. ret = del_balance_item(fs_info);
  2773. if (ret)
  2774. btrfs_handle_fs_error(fs_info, ret, NULL);
  2775. }
  2776. /*
  2777. * Balance filters. Return 1 if chunk should be filtered out
  2778. * (should not be balanced).
  2779. */
  2780. static int chunk_profiles_filter(u64 chunk_type,
  2781. struct btrfs_balance_args *bargs)
  2782. {
  2783. chunk_type = chunk_to_extended(chunk_type) &
  2784. BTRFS_EXTENDED_PROFILE_MASK;
  2785. if (bargs->profiles & chunk_type)
  2786. return 0;
  2787. return 1;
  2788. }
  2789. static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
  2790. struct btrfs_balance_args *bargs)
  2791. {
  2792. struct btrfs_block_group_cache *cache;
  2793. u64 chunk_used;
  2794. u64 user_thresh_min;
  2795. u64 user_thresh_max;
  2796. int ret = 1;
  2797. cache = btrfs_lookup_block_group(fs_info, chunk_offset);
  2798. chunk_used = btrfs_block_group_used(&cache->item);
  2799. if (bargs->usage_min == 0)
  2800. user_thresh_min = 0;
  2801. else
  2802. user_thresh_min = div_factor_fine(cache->key.offset,
  2803. bargs->usage_min);
  2804. if (bargs->usage_max == 0)
  2805. user_thresh_max = 1;
  2806. else if (bargs->usage_max > 100)
  2807. user_thresh_max = cache->key.offset;
  2808. else
  2809. user_thresh_max = div_factor_fine(cache->key.offset,
  2810. bargs->usage_max);
  2811. if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
  2812. ret = 0;
  2813. btrfs_put_block_group(cache);
  2814. return ret;
  2815. }
  2816. static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
  2817. u64 chunk_offset, struct btrfs_balance_args *bargs)
  2818. {
  2819. struct btrfs_block_group_cache *cache;
  2820. u64 chunk_used, user_thresh;
  2821. int ret = 1;
  2822. cache = btrfs_lookup_block_group(fs_info, chunk_offset);
  2823. chunk_used = btrfs_block_group_used(&cache->item);
  2824. if (bargs->usage_min == 0)
  2825. user_thresh = 1;
  2826. else if (bargs->usage > 100)
  2827. user_thresh = cache->key.offset;
  2828. else
  2829. user_thresh = div_factor_fine(cache->key.offset,
  2830. bargs->usage);
  2831. if (chunk_used < user_thresh)
  2832. ret = 0;
  2833. btrfs_put_block_group(cache);
  2834. return ret;
  2835. }
  2836. static int chunk_devid_filter(struct extent_buffer *leaf,
  2837. struct btrfs_chunk *chunk,
  2838. struct btrfs_balance_args *bargs)
  2839. {
  2840. struct btrfs_stripe *stripe;
  2841. int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
  2842. int i;
  2843. for (i = 0; i < num_stripes; i++) {
  2844. stripe = btrfs_stripe_nr(chunk, i);
  2845. if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
  2846. return 0;
  2847. }
  2848. return 1;
  2849. }
  2850. /* [pstart, pend) */
  2851. static int chunk_drange_filter(struct extent_buffer *leaf,
  2852. struct btrfs_chunk *chunk,
  2853. struct btrfs_balance_args *bargs)
  2854. {
  2855. struct btrfs_stripe *stripe;
  2856. int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
  2857. u64 stripe_offset;
  2858. u64 stripe_length;
  2859. int factor;
  2860. int i;
  2861. if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
  2862. return 0;
  2863. if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
  2864. BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
  2865. factor = num_stripes / 2;
  2866. } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
  2867. factor = num_stripes - 1;
  2868. } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
  2869. factor = num_stripes - 2;
  2870. } else {
  2871. factor = num_stripes;
  2872. }
  2873. for (i = 0; i < num_stripes; i++) {
  2874. stripe = btrfs_stripe_nr(chunk, i);
  2875. if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
  2876. continue;
  2877. stripe_offset = btrfs_stripe_offset(leaf, stripe);
  2878. stripe_length = btrfs_chunk_length(leaf, chunk);
  2879. stripe_length = div_u64(stripe_length, factor);
  2880. if (stripe_offset < bargs->pend &&
  2881. stripe_offset + stripe_length > bargs->pstart)
  2882. return 0;
  2883. }
  2884. return 1;
  2885. }
  2886. /* [vstart, vend) */
  2887. static int chunk_vrange_filter(struct extent_buffer *leaf,
  2888. struct btrfs_chunk *chunk,
  2889. u64 chunk_offset,
  2890. struct btrfs_balance_args *bargs)
  2891. {
  2892. if (chunk_offset < bargs->vend &&
  2893. chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
  2894. /* at least part of the chunk is inside this vrange */
  2895. return 0;
  2896. return 1;
  2897. }
  2898. static int chunk_stripes_range_filter(struct extent_buffer *leaf,
  2899. struct btrfs_chunk *chunk,
  2900. struct btrfs_balance_args *bargs)
  2901. {
  2902. int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
  2903. if (bargs->stripes_min <= num_stripes
  2904. && num_stripes <= bargs->stripes_max)
  2905. return 0;
  2906. return 1;
  2907. }
  2908. static int chunk_soft_convert_filter(u64 chunk_type,
  2909. struct btrfs_balance_args *bargs)
  2910. {
  2911. if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
  2912. return 0;
  2913. chunk_type = chunk_to_extended(chunk_type) &
  2914. BTRFS_EXTENDED_PROFILE_MASK;
  2915. if (bargs->target == chunk_type)
  2916. return 1;
  2917. return 0;
  2918. }
  2919. static int should_balance_chunk(struct btrfs_fs_info *fs_info,
  2920. struct extent_buffer *leaf,
  2921. struct btrfs_chunk *chunk, u64 chunk_offset)
  2922. {
  2923. struct btrfs_balance_control *bctl = fs_info->balance_ctl;
  2924. struct btrfs_balance_args *bargs = NULL;
  2925. u64 chunk_type = btrfs_chunk_type(leaf, chunk);
  2926. /* type filter */
  2927. if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
  2928. (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
  2929. return 0;
  2930. }
  2931. if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
  2932. bargs = &bctl->data;
  2933. else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
  2934. bargs = &bctl->sys;
  2935. else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
  2936. bargs = &bctl->meta;
  2937. /* profiles filter */
  2938. if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
  2939. chunk_profiles_filter(chunk_type, bargs)) {
  2940. return 0;
  2941. }
  2942. /* usage filter */
  2943. if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
  2944. chunk_usage_filter(fs_info, chunk_offset, bargs)) {
  2945. return 0;
  2946. } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
  2947. chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
  2948. return 0;
  2949. }
  2950. /* devid filter */
  2951. if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
  2952. chunk_devid_filter(leaf, chunk, bargs)) {
  2953. return 0;
  2954. }
  2955. /* drange filter, makes sense only with devid filter */
  2956. if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
  2957. chunk_drange_filter(leaf, chunk, bargs)) {
  2958. return 0;
  2959. }
  2960. /* vrange filter */
  2961. if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
  2962. chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
  2963. return 0;
  2964. }
  2965. /* stripes filter */
  2966. if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
  2967. chunk_stripes_range_filter(leaf, chunk, bargs)) {
  2968. return 0;
  2969. }
  2970. /* soft profile changing mode */
  2971. if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
  2972. chunk_soft_convert_filter(chunk_type, bargs)) {
  2973. return 0;
  2974. }
  2975. /*
  2976. * limited by count, must be the last filter
  2977. */
  2978. if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
  2979. if (bargs->limit == 0)
  2980. return 0;
  2981. else
  2982. bargs->limit--;
  2983. } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
  2984. /*
  2985. * Same logic as the 'limit' filter; the minimum cannot be
  2986. * determined here because we do not have the global information
  2987. * about the count of all chunks that satisfy the filters.
  2988. */
  2989. if (bargs->limit_max == 0)
  2990. return 0;
  2991. else
  2992. bargs->limit_max--;
  2993. }
  2994. return 1;
  2995. }
  2996. static int __btrfs_balance(struct btrfs_fs_info *fs_info)
  2997. {
  2998. struct btrfs_balance_control *bctl = fs_info->balance_ctl;
  2999. struct btrfs_root *chunk_root = fs_info->chunk_root;
  3000. struct btrfs_root *dev_root = fs_info->dev_root;
  3001. struct list_head *devices;
  3002. struct btrfs_device *device;
  3003. u64 old_size;
  3004. u64 size_to_free;
  3005. u64 chunk_type;
  3006. struct btrfs_chunk *chunk;
  3007. struct btrfs_path *path = NULL;
  3008. struct btrfs_key key;
  3009. struct btrfs_key found_key;
  3010. struct btrfs_trans_handle *trans;
  3011. struct extent_buffer *leaf;
  3012. int slot;
  3013. int ret;
  3014. int enospc_errors = 0;
  3015. bool counting = true;
  3016. /* The single value limit and min/max limits use the same bytes in the */
  3017. u64 limit_data = bctl->data.limit;
  3018. u64 limit_meta = bctl->meta.limit;
  3019. u64 limit_sys = bctl->sys.limit;
  3020. u32 count_data = 0;
  3021. u32 count_meta = 0;
  3022. u32 count_sys = 0;
  3023. int chunk_reserved = 0;
  3024. /* step one make some room on all the devices */
  3025. devices = &fs_info->fs_devices->devices;
  3026. list_for_each_entry(device, devices, dev_list) {
  3027. old_size = btrfs_device_get_total_bytes(device);
  3028. size_to_free = div_factor(old_size, 1);
  3029. size_to_free = min_t(u64, size_to_free, SZ_1M);
  3030. if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
  3031. btrfs_device_get_total_bytes(device) -
  3032. btrfs_device_get_bytes_used(device) > size_to_free ||
  3033. test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
  3034. continue;
  3035. ret = btrfs_shrink_device(device, old_size - size_to_free);
  3036. if (ret == -ENOSPC)
  3037. break;
  3038. if (ret) {
  3039. /* btrfs_shrink_device never returns ret > 0 */
  3040. WARN_ON(ret > 0);
  3041. goto error;
  3042. }
  3043. trans = btrfs_start_transaction(dev_root, 0);
  3044. if (IS_ERR(trans)) {
  3045. ret = PTR_ERR(trans);
  3046. btrfs_info_in_rcu(fs_info,
  3047. "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
  3048. rcu_str_deref(device->name), ret,
  3049. old_size, old_size - size_to_free);
  3050. goto error;
  3051. }
  3052. ret = btrfs_grow_device(trans, device, old_size);
  3053. if (ret) {
  3054. btrfs_end_transaction(trans);
  3055. /* btrfs_grow_device never returns ret > 0 */
  3056. WARN_ON(ret > 0);
  3057. btrfs_info_in_rcu(fs_info,
  3058. "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
  3059. rcu_str_deref(device->name), ret,
  3060. old_size, old_size - size_to_free);
  3061. goto error;
  3062. }
  3063. btrfs_end_transaction(trans);
  3064. }
  3065. /* step two, relocate all the chunks */
  3066. path = btrfs_alloc_path();
  3067. if (!path) {
  3068. ret = -ENOMEM;
  3069. goto error;
  3070. }
  3071. /* zero out stat counters */
  3072. spin_lock(&fs_info->balance_lock);
  3073. memset(&bctl->stat, 0, sizeof(bctl->stat));
  3074. spin_unlock(&fs_info->balance_lock);
  3075. again:
  3076. if (!counting) {
  3077. /*
  3078. * The single value limit and min/max limits use the same bytes
  3079. * in the
  3080. */
  3081. bctl->data.limit = limit_data;
  3082. bctl->meta.limit = limit_meta;
  3083. bctl->sys.limit = limit_sys;
  3084. }
  3085. key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
  3086. key.offset = (u64)-1;
  3087. key.type = BTRFS_CHUNK_ITEM_KEY;
  3088. while (1) {
  3089. if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
  3090. atomic_read(&fs_info->balance_cancel_req)) {
  3091. ret = -ECANCELED;
  3092. goto error;
  3093. }
  3094. mutex_lock(&fs_info->delete_unused_bgs_mutex);
  3095. ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
  3096. if (ret < 0) {
  3097. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3098. goto error;
  3099. }
  3100. /*
  3101. * this shouldn't happen, it means the last relocate
  3102. * failed
  3103. */
  3104. if (ret == 0)
  3105. BUG(); /* FIXME break ? */
  3106. ret = btrfs_previous_item(chunk_root, path, 0,
  3107. BTRFS_CHUNK_ITEM_KEY);
  3108. if (ret) {
  3109. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3110. ret = 0;
  3111. break;
  3112. }
  3113. leaf = path->nodes[0];
  3114. slot = path->slots[0];
  3115. btrfs_item_key_to_cpu(leaf, &found_key, slot);
  3116. if (found_key.objectid != key.objectid) {
  3117. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3118. break;
  3119. }
  3120. chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
  3121. chunk_type = btrfs_chunk_type(leaf, chunk);
  3122. if (!counting) {
  3123. spin_lock(&fs_info->balance_lock);
  3124. bctl->stat.considered++;
  3125. spin_unlock(&fs_info->balance_lock);
  3126. }
  3127. ret = should_balance_chunk(fs_info, leaf, chunk,
  3128. found_key.offset);
  3129. btrfs_release_path(path);
  3130. if (!ret) {
  3131. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3132. goto loop;
  3133. }
  3134. if (counting) {
  3135. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3136. spin_lock(&fs_info->balance_lock);
  3137. bctl->stat.expected++;
  3138. spin_unlock(&fs_info->balance_lock);
  3139. if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
  3140. count_data++;
  3141. else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
  3142. count_sys++;
  3143. else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
  3144. count_meta++;
  3145. goto loop;
  3146. }
  3147. /*
  3148. * Apply limit_min filter, no need to check if the LIMITS
  3149. * filter is used, limit_min is 0 by default
  3150. */
  3151. if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
  3152. count_data < bctl->data.limit_min)
  3153. || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
  3154. count_meta < bctl->meta.limit_min)
  3155. || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
  3156. count_sys < bctl->sys.limit_min)) {
  3157. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3158. goto loop;
  3159. }
  3160. if (!chunk_reserved) {
  3161. /*
  3162. * We may be relocating the only data chunk we have,
  3163. * which could potentially end up with losing data's
  3164. * raid profile, so lets allocate an empty one in
  3165. * advance.
  3166. */
  3167. ret = btrfs_may_alloc_data_chunk(fs_info,
  3168. found_key.offset);
  3169. if (ret < 0) {
  3170. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3171. goto error;
  3172. } else if (ret == 1) {
  3173. chunk_reserved = 1;
  3174. }
  3175. }
  3176. ret = btrfs_relocate_chunk(fs_info, found_key.offset);
  3177. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3178. if (ret && ret != -ENOSPC)
  3179. goto error;
  3180. if (ret == -ENOSPC) {
  3181. enospc_errors++;
  3182. } else {
  3183. spin_lock(&fs_info->balance_lock);
  3184. bctl->stat.completed++;
  3185. spin_unlock(&fs_info->balance_lock);
  3186. }
  3187. loop:
  3188. if (found_key.offset == 0)
  3189. break;
  3190. key.offset = found_key.offset - 1;
  3191. }
  3192. if (counting) {
  3193. btrfs_release_path(path);
  3194. counting = false;
  3195. goto again;
  3196. }
  3197. error:
  3198. btrfs_free_path(path);
  3199. if (enospc_errors) {
  3200. btrfs_info(fs_info, "%d enospc errors during balance",
  3201. enospc_errors);
  3202. if (!ret)
  3203. ret = -ENOSPC;
  3204. }
  3205. return ret;
  3206. }
  3207. /**
  3208. * alloc_profile_is_valid - see if a given profile is valid and reduced
  3209. * @flags: profile to validate
  3210. * @extended: if true @flags is treated as an extended profile
  3211. */
  3212. static int alloc_profile_is_valid(u64 flags, int extended)
  3213. {
  3214. u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
  3215. BTRFS_BLOCK_GROUP_PROFILE_MASK);
  3216. flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
  3217. /* 1) check that all other bits are zeroed */
  3218. if (flags & ~mask)
  3219. return 0;
  3220. /* 2) see if profile is reduced */
  3221. if (flags == 0)
  3222. return !extended; /* "0" is valid for usual profiles */
  3223. /* true if exactly one bit set */
  3224. return (flags & (flags - 1)) == 0;
  3225. }
  3226. static inline int balance_need_close(struct btrfs_fs_info *fs_info)
  3227. {
  3228. /* cancel requested || normal exit path */
  3229. return atomic_read(&fs_info->balance_cancel_req) ||
  3230. (atomic_read(&fs_info->balance_pause_req) == 0 &&
  3231. atomic_read(&fs_info->balance_cancel_req) == 0);
  3232. }
  3233. /* Non-zero return value signifies invalidity */
  3234. static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
  3235. u64 allowed)
  3236. {
  3237. return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
  3238. (!alloc_profile_is_valid(bctl_arg->target, 1) ||
  3239. (bctl_arg->target & ~allowed)));
  3240. }
  3241. /*
  3242. * Should be called with balance mutexe held
  3243. */
  3244. int btrfs_balance(struct btrfs_fs_info *fs_info,
  3245. struct btrfs_balance_control *bctl,
  3246. struct btrfs_ioctl_balance_args *bargs)
  3247. {
  3248. u64 meta_target, data_target;
  3249. u64 allowed;
  3250. int mixed = 0;
  3251. int ret;
  3252. u64 num_devices;
  3253. unsigned seq;
  3254. if (btrfs_fs_closing(fs_info) ||
  3255. atomic_read(&fs_info->balance_pause_req) ||
  3256. atomic_read(&fs_info->balance_cancel_req)) {
  3257. ret = -EINVAL;
  3258. goto out;
  3259. }
  3260. allowed = btrfs_super_incompat_flags(fs_info->super_copy);
  3261. if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
  3262. mixed = 1;
  3263. /*
  3264. * In case of mixed groups both data and meta should be picked,
  3265. * and identical options should be given for both of them.
  3266. */
  3267. allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
  3268. if (mixed && (bctl->flags & allowed)) {
  3269. if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
  3270. !(bctl->flags & BTRFS_BALANCE_METADATA) ||
  3271. memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
  3272. btrfs_err(fs_info,
  3273. "balance: mixed groups data and metadata options must be the same");
  3274. ret = -EINVAL;
  3275. goto out;
  3276. }
  3277. }
  3278. num_devices = fs_info->fs_devices->num_devices;
  3279. btrfs_dev_replace_read_lock(&fs_info->dev_replace);
  3280. if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
  3281. BUG_ON(num_devices < 1);
  3282. num_devices--;
  3283. }
  3284. btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
  3285. allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
  3286. if (num_devices > 1)
  3287. allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
  3288. if (num_devices > 2)
  3289. allowed |= BTRFS_BLOCK_GROUP_RAID5;
  3290. if (num_devices > 3)
  3291. allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
  3292. BTRFS_BLOCK_GROUP_RAID6);
  3293. if (validate_convert_profile(&bctl->data, allowed)) {
  3294. int index = btrfs_bg_flags_to_raid_index(bctl->data.target);
  3295. btrfs_err(fs_info,
  3296. "balance: invalid convert data profile %s",
  3297. get_raid_name(index));
  3298. ret = -EINVAL;
  3299. goto out;
  3300. }
  3301. if (validate_convert_profile(&bctl->meta, allowed)) {
  3302. int index = btrfs_bg_flags_to_raid_index(bctl->meta.target);
  3303. btrfs_err(fs_info,
  3304. "balance: invalid convert metadata profile %s",
  3305. get_raid_name(index));
  3306. ret = -EINVAL;
  3307. goto out;
  3308. }
  3309. if (validate_convert_profile(&bctl->sys, allowed)) {
  3310. int index = btrfs_bg_flags_to_raid_index(bctl->sys.target);
  3311. btrfs_err(fs_info,
  3312. "balance: invalid convert system profile %s",
  3313. get_raid_name(index));
  3314. ret = -EINVAL;
  3315. goto out;
  3316. }
  3317. /* allow to reduce meta or sys integrity only if force set */
  3318. allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
  3319. BTRFS_BLOCK_GROUP_RAID10 |
  3320. BTRFS_BLOCK_GROUP_RAID5 |
  3321. BTRFS_BLOCK_GROUP_RAID6;
  3322. do {
  3323. seq = read_seqbegin(&fs_info->profiles_lock);
  3324. if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
  3325. (fs_info->avail_system_alloc_bits & allowed) &&
  3326. !(bctl->sys.target & allowed)) ||
  3327. ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
  3328. (fs_info->avail_metadata_alloc_bits & allowed) &&
  3329. !(bctl->meta.target & allowed))) {
  3330. if (bctl->flags & BTRFS_BALANCE_FORCE) {
  3331. btrfs_info(fs_info,
  3332. "balance: force reducing metadata integrity");
  3333. } else {
  3334. btrfs_err(fs_info,
  3335. "balance: reduces metadata integrity, use --force if you want this");
  3336. ret = -EINVAL;
  3337. goto out;
  3338. }
  3339. }
  3340. } while (read_seqretry(&fs_info->profiles_lock, seq));
  3341. /* if we're not converting, the target field is uninitialized */
  3342. meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
  3343. bctl->meta.target : fs_info->avail_metadata_alloc_bits;
  3344. data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
  3345. bctl->data.target : fs_info->avail_data_alloc_bits;
  3346. if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
  3347. btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
  3348. int meta_index = btrfs_bg_flags_to_raid_index(meta_target);
  3349. int data_index = btrfs_bg_flags_to_raid_index(data_target);
  3350. btrfs_warn(fs_info,
  3351. "balance: metadata profile %s has lower redundancy than data profile %s",
  3352. get_raid_name(meta_index), get_raid_name(data_index));
  3353. }
  3354. ret = insert_balance_item(fs_info, bctl);
  3355. if (ret && ret != -EEXIST)
  3356. goto out;
  3357. if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
  3358. BUG_ON(ret == -EEXIST);
  3359. BUG_ON(fs_info->balance_ctl);
  3360. spin_lock(&fs_info->balance_lock);
  3361. fs_info->balance_ctl = bctl;
  3362. spin_unlock(&fs_info->balance_lock);
  3363. } else {
  3364. BUG_ON(ret != -EEXIST);
  3365. spin_lock(&fs_info->balance_lock);
  3366. update_balance_args(bctl);
  3367. spin_unlock(&fs_info->balance_lock);
  3368. }
  3369. ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
  3370. set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
  3371. mutex_unlock(&fs_info->balance_mutex);
  3372. ret = __btrfs_balance(fs_info);
  3373. mutex_lock(&fs_info->balance_mutex);
  3374. clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
  3375. if (bargs) {
  3376. memset(bargs, 0, sizeof(*bargs));
  3377. btrfs_update_ioctl_balance_args(fs_info, bargs);
  3378. }
  3379. if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
  3380. balance_need_close(fs_info)) {
  3381. reset_balance_state(fs_info);
  3382. clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
  3383. }
  3384. wake_up(&fs_info->balance_wait_q);
  3385. return ret;
  3386. out:
  3387. if (bctl->flags & BTRFS_BALANCE_RESUME)
  3388. reset_balance_state(fs_info);
  3389. else
  3390. kfree(bctl);
  3391. clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
  3392. return ret;
  3393. }
  3394. static int balance_kthread(void *data)
  3395. {
  3396. struct btrfs_fs_info *fs_info = data;
  3397. int ret = 0;
  3398. mutex_lock(&fs_info->balance_mutex);
  3399. if (fs_info->balance_ctl) {
  3400. btrfs_info(fs_info, "balance: resuming");
  3401. ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
  3402. }
  3403. mutex_unlock(&fs_info->balance_mutex);
  3404. return ret;
  3405. }
  3406. int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
  3407. {
  3408. struct task_struct *tsk;
  3409. mutex_lock(&fs_info->balance_mutex);
  3410. if (!fs_info->balance_ctl) {
  3411. mutex_unlock(&fs_info->balance_mutex);
  3412. return 0;
  3413. }
  3414. mutex_unlock(&fs_info->balance_mutex);
  3415. if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
  3416. btrfs_info(fs_info, "balance: resume skipped");
  3417. return 0;
  3418. }
  3419. /*
  3420. * A ro->rw remount sequence should continue with the paused balance
  3421. * regardless of who pauses it, system or the user as of now, so set
  3422. * the resume flag.
  3423. */
  3424. spin_lock(&fs_info->balance_lock);
  3425. fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
  3426. spin_unlock(&fs_info->balance_lock);
  3427. tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
  3428. return PTR_ERR_OR_ZERO(tsk);
  3429. }
  3430. int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
  3431. {
  3432. struct btrfs_balance_control *bctl;
  3433. struct btrfs_balance_item *item;
  3434. struct btrfs_disk_balance_args disk_bargs;
  3435. struct btrfs_path *path;
  3436. struct extent_buffer *leaf;
  3437. struct btrfs_key key;
  3438. int ret;
  3439. path = btrfs_alloc_path();
  3440. if (!path)
  3441. return -ENOMEM;
  3442. key.objectid = BTRFS_BALANCE_OBJECTID;
  3443. key.type = BTRFS_TEMPORARY_ITEM_KEY;
  3444. key.offset = 0;
  3445. ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
  3446. if (ret < 0)
  3447. goto out;
  3448. if (ret > 0) { /* ret = -ENOENT; */
  3449. ret = 0;
  3450. goto out;
  3451. }
  3452. bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
  3453. if (!bctl) {
  3454. ret = -ENOMEM;
  3455. goto out;
  3456. }
  3457. leaf = path->nodes[0];
  3458. item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
  3459. bctl->flags = btrfs_balance_flags(leaf, item);
  3460. bctl->flags |= BTRFS_BALANCE_RESUME;
  3461. btrfs_balance_data(leaf, item, &disk_bargs);
  3462. btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
  3463. btrfs_balance_meta(leaf, item, &disk_bargs);
  3464. btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
  3465. btrfs_balance_sys(leaf, item, &disk_bargs);
  3466. btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
  3467. /*
  3468. * This should never happen, as the paused balance state is recovered
  3469. * during mount without any chance of other exclusive ops to collide.
  3470. *
  3471. * This gives the exclusive op status to balance and keeps in paused
  3472. * state until user intervention (cancel or umount). If the ownership
  3473. * cannot be assigned, show a message but do not fail. The balance
  3474. * is in a paused state and must have fs_info::balance_ctl properly
  3475. * set up.
  3476. */
  3477. if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
  3478. btrfs_warn(fs_info,
  3479. "balance: cannot set exclusive op status, resume manually");
  3480. mutex_lock(&fs_info->balance_mutex);
  3481. BUG_ON(fs_info->balance_ctl);
  3482. spin_lock(&fs_info->balance_lock);
  3483. fs_info->balance_ctl = bctl;
  3484. spin_unlock(&fs_info->balance_lock);
  3485. mutex_unlock(&fs_info->balance_mutex);
  3486. out:
  3487. btrfs_free_path(path);
  3488. return ret;
  3489. }
  3490. int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
  3491. {
  3492. int ret = 0;
  3493. mutex_lock(&fs_info->balance_mutex);
  3494. if (!fs_info->balance_ctl) {
  3495. mutex_unlock(&fs_info->balance_mutex);
  3496. return -ENOTCONN;
  3497. }
  3498. if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
  3499. atomic_inc(&fs_info->balance_pause_req);
  3500. mutex_unlock(&fs_info->balance_mutex);
  3501. wait_event(fs_info->balance_wait_q,
  3502. !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
  3503. mutex_lock(&fs_info->balance_mutex);
  3504. /* we are good with balance_ctl ripped off from under us */
  3505. BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
  3506. atomic_dec(&fs_info->balance_pause_req);
  3507. } else {
  3508. ret = -ENOTCONN;
  3509. }
  3510. mutex_unlock(&fs_info->balance_mutex);
  3511. return ret;
  3512. }
  3513. int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
  3514. {
  3515. mutex_lock(&fs_info->balance_mutex);
  3516. if (!fs_info->balance_ctl) {
  3517. mutex_unlock(&fs_info->balance_mutex);
  3518. return -ENOTCONN;
  3519. }
  3520. /*
  3521. * A paused balance with the item stored on disk can be resumed at
  3522. * mount time if the mount is read-write. Otherwise it's still paused
  3523. * and we must not allow cancelling as it deletes the item.
  3524. */
  3525. if (sb_rdonly(fs_info->sb)) {
  3526. mutex_unlock(&fs_info->balance_mutex);
  3527. return -EROFS;
  3528. }
  3529. atomic_inc(&fs_info->balance_cancel_req);
  3530. /*
  3531. * if we are running just wait and return, balance item is
  3532. * deleted in btrfs_balance in this case
  3533. */
  3534. if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
  3535. mutex_unlock(&fs_info->balance_mutex);
  3536. wait_event(fs_info->balance_wait_q,
  3537. !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
  3538. mutex_lock(&fs_info->balance_mutex);
  3539. } else {
  3540. mutex_unlock(&fs_info->balance_mutex);
  3541. /*
  3542. * Lock released to allow other waiters to continue, we'll
  3543. * reexamine the status again.
  3544. */
  3545. mutex_lock(&fs_info->balance_mutex);
  3546. if (fs_info->balance_ctl) {
  3547. reset_balance_state(fs_info);
  3548. clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
  3549. btrfs_info(fs_info, "balance: canceled");
  3550. }
  3551. }
  3552. BUG_ON(fs_info->balance_ctl ||
  3553. test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
  3554. atomic_dec(&fs_info->balance_cancel_req);
  3555. mutex_unlock(&fs_info->balance_mutex);
  3556. return 0;
  3557. }
  3558. static int btrfs_uuid_scan_kthread(void *data)
  3559. {
  3560. struct btrfs_fs_info *fs_info = data;
  3561. struct btrfs_root *root = fs_info->tree_root;
  3562. struct btrfs_key key;
  3563. struct btrfs_path *path = NULL;
  3564. int ret = 0;
  3565. struct extent_buffer *eb;
  3566. int slot;
  3567. struct btrfs_root_item root_item;
  3568. u32 item_size;
  3569. struct btrfs_trans_handle *trans = NULL;
  3570. path = btrfs_alloc_path();
  3571. if (!path) {
  3572. ret = -ENOMEM;
  3573. goto out;
  3574. }
  3575. key.objectid = 0;
  3576. key.type = BTRFS_ROOT_ITEM_KEY;
  3577. key.offset = 0;
  3578. while (1) {
  3579. ret = btrfs_search_forward(root, &key, path,
  3580. BTRFS_OLDEST_GENERATION);
  3581. if (ret) {
  3582. if (ret > 0)
  3583. ret = 0;
  3584. break;
  3585. }
  3586. if (key.type != BTRFS_ROOT_ITEM_KEY ||
  3587. (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
  3588. key.objectid != BTRFS_FS_TREE_OBJECTID) ||
  3589. key.objectid > BTRFS_LAST_FREE_OBJECTID)
  3590. goto skip;
  3591. eb = path->nodes[0];
  3592. slot = path->slots[0];
  3593. item_size = btrfs_item_size_nr(eb, slot);
  3594. if (item_size < sizeof(root_item))
  3595. goto skip;
  3596. read_extent_buffer(eb, &root_item,
  3597. btrfs_item_ptr_offset(eb, slot),
  3598. (int)sizeof(root_item));
  3599. if (btrfs_root_refs(&root_item) == 0)
  3600. goto skip;
  3601. if (!btrfs_is_empty_uuid(root_item.uuid) ||
  3602. !btrfs_is_empty_uuid(root_item.received_uuid)) {
  3603. if (trans)
  3604. goto update_tree;
  3605. btrfs_release_path(path);
  3606. /*
  3607. * 1 - subvol uuid item
  3608. * 1 - received_subvol uuid item
  3609. */
  3610. trans = btrfs_start_transaction(fs_info->uuid_root, 2);
  3611. if (IS_ERR(trans)) {
  3612. ret = PTR_ERR(trans);
  3613. break;
  3614. }
  3615. continue;
  3616. } else {
  3617. goto skip;
  3618. }
  3619. update_tree:
  3620. if (!btrfs_is_empty_uuid(root_item.uuid)) {
  3621. ret = btrfs_uuid_tree_add(trans, root_item.uuid,
  3622. BTRFS_UUID_KEY_SUBVOL,
  3623. key.objectid);
  3624. if (ret < 0) {
  3625. btrfs_warn(fs_info, "uuid_tree_add failed %d",
  3626. ret);
  3627. break;
  3628. }
  3629. }
  3630. if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
  3631. ret = btrfs_uuid_tree_add(trans,
  3632. root_item.received_uuid,
  3633. BTRFS_UUID_KEY_RECEIVED_SUBVOL,
  3634. key.objectid);
  3635. if (ret < 0) {
  3636. btrfs_warn(fs_info, "uuid_tree_add failed %d",
  3637. ret);
  3638. break;
  3639. }
  3640. }
  3641. skip:
  3642. if (trans) {
  3643. ret = btrfs_end_transaction(trans);
  3644. trans = NULL;
  3645. if (ret)
  3646. break;
  3647. }
  3648. btrfs_release_path(path);
  3649. if (key.offset < (u64)-1) {
  3650. key.offset++;
  3651. } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
  3652. key.offset = 0;
  3653. key.type = BTRFS_ROOT_ITEM_KEY;
  3654. } else if (key.objectid < (u64)-1) {
  3655. key.offset = 0;
  3656. key.type = BTRFS_ROOT_ITEM_KEY;
  3657. key.objectid++;
  3658. } else {
  3659. break;
  3660. }
  3661. cond_resched();
  3662. }
  3663. out:
  3664. btrfs_free_path(path);
  3665. if (trans && !IS_ERR(trans))
  3666. btrfs_end_transaction(trans);
  3667. if (ret)
  3668. btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
  3669. else
  3670. set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
  3671. up(&fs_info->uuid_tree_rescan_sem);
  3672. return 0;
  3673. }
  3674. /*
  3675. * Callback for btrfs_uuid_tree_iterate().
  3676. * returns:
  3677. * 0 check succeeded, the entry is not outdated.
  3678. * < 0 if an error occurred.
  3679. * > 0 if the check failed, which means the caller shall remove the entry.
  3680. */
  3681. static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
  3682. u8 *uuid, u8 type, u64 subid)
  3683. {
  3684. struct btrfs_key key;
  3685. int ret = 0;
  3686. struct btrfs_root *subvol_root;
  3687. if (type != BTRFS_UUID_KEY_SUBVOL &&
  3688. type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
  3689. goto out;
  3690. key.objectid = subid;
  3691. key.type = BTRFS_ROOT_ITEM_KEY;
  3692. key.offset = (u64)-1;
  3693. subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
  3694. if (IS_ERR(subvol_root)) {
  3695. ret = PTR_ERR(subvol_root);
  3696. if (ret == -ENOENT)
  3697. ret = 1;
  3698. goto out;
  3699. }
  3700. switch (type) {
  3701. case BTRFS_UUID_KEY_SUBVOL:
  3702. if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
  3703. ret = 1;
  3704. break;
  3705. case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
  3706. if (memcmp(uuid, subvol_root->root_item.received_uuid,
  3707. BTRFS_UUID_SIZE))
  3708. ret = 1;
  3709. break;
  3710. }
  3711. out:
  3712. return ret;
  3713. }
  3714. static int btrfs_uuid_rescan_kthread(void *data)
  3715. {
  3716. struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
  3717. int ret;
  3718. /*
  3719. * 1st step is to iterate through the existing UUID tree and
  3720. * to delete all entries that contain outdated data.
  3721. * 2nd step is to add all missing entries to the UUID tree.
  3722. */
  3723. ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
  3724. if (ret < 0) {
  3725. btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
  3726. up(&fs_info->uuid_tree_rescan_sem);
  3727. return ret;
  3728. }
  3729. return btrfs_uuid_scan_kthread(data);
  3730. }
  3731. int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
  3732. {
  3733. struct btrfs_trans_handle *trans;
  3734. struct btrfs_root *tree_root = fs_info->tree_root;
  3735. struct btrfs_root *uuid_root;
  3736. struct task_struct *task;
  3737. int ret;
  3738. /*
  3739. * 1 - root node
  3740. * 1 - root item
  3741. */
  3742. trans = btrfs_start_transaction(tree_root, 2);
  3743. if (IS_ERR(trans))
  3744. return PTR_ERR(trans);
  3745. uuid_root = btrfs_create_tree(trans, fs_info,
  3746. BTRFS_UUID_TREE_OBJECTID);
  3747. if (IS_ERR(uuid_root)) {
  3748. ret = PTR_ERR(uuid_root);
  3749. btrfs_abort_transaction(trans, ret);
  3750. btrfs_end_transaction(trans);
  3751. return ret;
  3752. }
  3753. fs_info->uuid_root = uuid_root;
  3754. ret = btrfs_commit_transaction(trans);
  3755. if (ret)
  3756. return ret;
  3757. down(&fs_info->uuid_tree_rescan_sem);
  3758. task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
  3759. if (IS_ERR(task)) {
  3760. /* fs_info->update_uuid_tree_gen remains 0 in all error case */
  3761. btrfs_warn(fs_info, "failed to start uuid_scan task");
  3762. up(&fs_info->uuid_tree_rescan_sem);
  3763. return PTR_ERR(task);
  3764. }
  3765. return 0;
  3766. }
  3767. int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
  3768. {
  3769. struct task_struct *task;
  3770. down(&fs_info->uuid_tree_rescan_sem);
  3771. task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
  3772. if (IS_ERR(task)) {
  3773. /* fs_info->update_uuid_tree_gen remains 0 in all error case */
  3774. btrfs_warn(fs_info, "failed to start uuid_rescan task");
  3775. up(&fs_info->uuid_tree_rescan_sem);
  3776. return PTR_ERR(task);
  3777. }
  3778. return 0;
  3779. }
  3780. /*
  3781. * shrinking a device means finding all of the device extents past
  3782. * the new size, and then following the back refs to the chunks.
  3783. * The chunk relocation code actually frees the device extent
  3784. */
  3785. int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
  3786. {
  3787. struct btrfs_fs_info *fs_info = device->fs_info;
  3788. struct btrfs_root *root = fs_info->dev_root;
  3789. struct btrfs_trans_handle *trans;
  3790. struct btrfs_dev_extent *dev_extent = NULL;
  3791. struct btrfs_path *path;
  3792. u64 length;
  3793. u64 chunk_offset;
  3794. int ret;
  3795. int slot;
  3796. int failed = 0;
  3797. bool retried = false;
  3798. bool checked_pending_chunks = false;
  3799. struct extent_buffer *l;
  3800. struct btrfs_key key;
  3801. struct btrfs_super_block *super_copy = fs_info->super_copy;
  3802. u64 old_total = btrfs_super_total_bytes(super_copy);
  3803. u64 old_size = btrfs_device_get_total_bytes(device);
  3804. u64 diff;
  3805. new_size = round_down(new_size, fs_info->sectorsize);
  3806. diff = round_down(old_size - new_size, fs_info->sectorsize);
  3807. if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
  3808. return -EINVAL;
  3809. path = btrfs_alloc_path();
  3810. if (!path)
  3811. return -ENOMEM;
  3812. path->reada = READA_BACK;
  3813. mutex_lock(&fs_info->chunk_mutex);
  3814. btrfs_device_set_total_bytes(device, new_size);
  3815. if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
  3816. device->fs_devices->total_rw_bytes -= diff;
  3817. atomic64_sub(diff, &fs_info->free_chunk_space);
  3818. }
  3819. mutex_unlock(&fs_info->chunk_mutex);
  3820. again:
  3821. key.objectid = device->devid;
  3822. key.offset = (u64)-1;
  3823. key.type = BTRFS_DEV_EXTENT_KEY;
  3824. do {
  3825. mutex_lock(&fs_info->delete_unused_bgs_mutex);
  3826. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  3827. if (ret < 0) {
  3828. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3829. goto done;
  3830. }
  3831. ret = btrfs_previous_item(root, path, 0, key.type);
  3832. if (ret)
  3833. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3834. if (ret < 0)
  3835. goto done;
  3836. if (ret) {
  3837. ret = 0;
  3838. btrfs_release_path(path);
  3839. break;
  3840. }
  3841. l = path->nodes[0];
  3842. slot = path->slots[0];
  3843. btrfs_item_key_to_cpu(l, &key, path->slots[0]);
  3844. if (key.objectid != device->devid) {
  3845. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3846. btrfs_release_path(path);
  3847. break;
  3848. }
  3849. dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
  3850. length = btrfs_dev_extent_length(l, dev_extent);
  3851. if (key.offset + length <= new_size) {
  3852. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3853. btrfs_release_path(path);
  3854. break;
  3855. }
  3856. chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
  3857. btrfs_release_path(path);
  3858. /*
  3859. * We may be relocating the only data chunk we have,
  3860. * which could potentially end up with losing data's
  3861. * raid profile, so lets allocate an empty one in
  3862. * advance.
  3863. */
  3864. ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
  3865. if (ret < 0) {
  3866. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3867. goto done;
  3868. }
  3869. ret = btrfs_relocate_chunk(fs_info, chunk_offset);
  3870. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  3871. if (ret && ret != -ENOSPC)
  3872. goto done;
  3873. if (ret == -ENOSPC)
  3874. failed++;
  3875. } while (key.offset-- > 0);
  3876. if (failed && !retried) {
  3877. failed = 0;
  3878. retried = true;
  3879. goto again;
  3880. } else if (failed && retried) {
  3881. ret = -ENOSPC;
  3882. goto done;
  3883. }
  3884. /* Shrinking succeeded, else we would be at "done". */
  3885. trans = btrfs_start_transaction(root, 0);
  3886. if (IS_ERR(trans)) {
  3887. ret = PTR_ERR(trans);
  3888. goto done;
  3889. }
  3890. mutex_lock(&fs_info->chunk_mutex);
  3891. /*
  3892. * We checked in the above loop all device extents that were already in
  3893. * the device tree. However before we have updated the device's
  3894. * total_bytes to the new size, we might have had chunk allocations that
  3895. * have not complete yet (new block groups attached to transaction
  3896. * handles), and therefore their device extents were not yet in the
  3897. * device tree and we missed them in the loop above. So if we have any
  3898. * pending chunk using a device extent that overlaps the device range
  3899. * that we can not use anymore, commit the current transaction and
  3900. * repeat the search on the device tree - this way we guarantee we will
  3901. * not have chunks using device extents that end beyond 'new_size'.
  3902. */
  3903. if (!checked_pending_chunks) {
  3904. u64 start = new_size;
  3905. u64 len = old_size - new_size;
  3906. if (contains_pending_extent(trans->transaction, device,
  3907. &start, len)) {
  3908. mutex_unlock(&fs_info->chunk_mutex);
  3909. checked_pending_chunks = true;
  3910. failed = 0;
  3911. retried = false;
  3912. ret = btrfs_commit_transaction(trans);
  3913. if (ret)
  3914. goto done;
  3915. goto again;
  3916. }
  3917. }
  3918. btrfs_device_set_disk_total_bytes(device, new_size);
  3919. if (list_empty(&device->resized_list))
  3920. list_add_tail(&device->resized_list,
  3921. &fs_info->fs_devices->resized_devices);
  3922. WARN_ON(diff > old_total);
  3923. btrfs_set_super_total_bytes(super_copy,
  3924. round_down(old_total - diff, fs_info->sectorsize));
  3925. mutex_unlock(&fs_info->chunk_mutex);
  3926. /* Now btrfs_update_device() will change the on-disk size. */
  3927. ret = btrfs_update_device(trans, device);
  3928. btrfs_end_transaction(trans);
  3929. done:
  3930. btrfs_free_path(path);
  3931. if (ret) {
  3932. mutex_lock(&fs_info->chunk_mutex);
  3933. btrfs_device_set_total_bytes(device, old_size);
  3934. if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
  3935. device->fs_devices->total_rw_bytes += diff;
  3936. atomic64_add(diff, &fs_info->free_chunk_space);
  3937. mutex_unlock(&fs_info->chunk_mutex);
  3938. }
  3939. return ret;
  3940. }
  3941. static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
  3942. struct btrfs_key *key,
  3943. struct btrfs_chunk *chunk, int item_size)
  3944. {
  3945. struct btrfs_super_block *super_copy = fs_info->super_copy;
  3946. struct btrfs_disk_key disk_key;
  3947. u32 array_size;
  3948. u8 *ptr;
  3949. mutex_lock(&fs_info->chunk_mutex);
  3950. array_size = btrfs_super_sys_array_size(super_copy);
  3951. if (array_size + item_size + sizeof(disk_key)
  3952. > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
  3953. mutex_unlock(&fs_info->chunk_mutex);
  3954. return -EFBIG;
  3955. }
  3956. ptr = super_copy->sys_chunk_array + array_size;
  3957. btrfs_cpu_key_to_disk(&disk_key, key);
  3958. memcpy(ptr, &disk_key, sizeof(disk_key));
  3959. ptr += sizeof(disk_key);
  3960. memcpy(ptr, chunk, item_size);
  3961. item_size += sizeof(disk_key);
  3962. btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
  3963. mutex_unlock(&fs_info->chunk_mutex);
  3964. return 0;
  3965. }
  3966. /*
  3967. * sort the devices in descending order by max_avail, total_avail
  3968. */
  3969. static int btrfs_cmp_device_info(const void *a, const void *b)
  3970. {
  3971. const struct btrfs_device_info *di_a = a;
  3972. const struct btrfs_device_info *di_b = b;
  3973. if (di_a->max_avail > di_b->max_avail)
  3974. return -1;
  3975. if (di_a->max_avail < di_b->max_avail)
  3976. return 1;
  3977. if (di_a->total_avail > di_b->total_avail)
  3978. return -1;
  3979. if (di_a->total_avail < di_b->total_avail)
  3980. return 1;
  3981. return 0;
  3982. }
  3983. static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
  3984. {
  3985. if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
  3986. return;
  3987. btrfs_set_fs_incompat(info, RAID56);
  3988. }
  3989. #define BTRFS_MAX_DEVS(info) ((BTRFS_MAX_ITEM_SIZE(info) \
  3990. - sizeof(struct btrfs_chunk)) \
  3991. / sizeof(struct btrfs_stripe) + 1)
  3992. #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
  3993. - 2 * sizeof(struct btrfs_disk_key) \
  3994. - 2 * sizeof(struct btrfs_chunk)) \
  3995. / sizeof(struct btrfs_stripe) + 1)
  3996. static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
  3997. u64 start, u64 type)
  3998. {
  3999. struct btrfs_fs_info *info = trans->fs_info;
  4000. struct btrfs_fs_devices *fs_devices = info->fs_devices;
  4001. struct btrfs_device *device;
  4002. struct map_lookup *map = NULL;
  4003. struct extent_map_tree *em_tree;
  4004. struct extent_map *em;
  4005. struct btrfs_device_info *devices_info = NULL;
  4006. u64 total_avail;
  4007. int num_stripes; /* total number of stripes to allocate */
  4008. int data_stripes; /* number of stripes that count for
  4009. block group size */
  4010. int sub_stripes; /* sub_stripes info for map */
  4011. int dev_stripes; /* stripes per dev */
  4012. int devs_max; /* max devs to use */
  4013. int devs_min; /* min devs needed */
  4014. int devs_increment; /* ndevs has to be a multiple of this */
  4015. int ncopies; /* how many copies to data has */
  4016. int ret;
  4017. u64 max_stripe_size;
  4018. u64 max_chunk_size;
  4019. u64 stripe_size;
  4020. u64 num_bytes;
  4021. int ndevs;
  4022. int i;
  4023. int j;
  4024. int index;
  4025. BUG_ON(!alloc_profile_is_valid(type, 0));
  4026. if (list_empty(&fs_devices->alloc_list)) {
  4027. if (btrfs_test_opt(info, ENOSPC_DEBUG))
  4028. btrfs_debug(info, "%s: no writable device", __func__);
  4029. return -ENOSPC;
  4030. }
  4031. index = btrfs_bg_flags_to_raid_index(type);
  4032. sub_stripes = btrfs_raid_array[index].sub_stripes;
  4033. dev_stripes = btrfs_raid_array[index].dev_stripes;
  4034. devs_max = btrfs_raid_array[index].devs_max;
  4035. devs_min = btrfs_raid_array[index].devs_min;
  4036. devs_increment = btrfs_raid_array[index].devs_increment;
  4037. ncopies = btrfs_raid_array[index].ncopies;
  4038. if (type & BTRFS_BLOCK_GROUP_DATA) {
  4039. max_stripe_size = SZ_1G;
  4040. max_chunk_size = 10 * max_stripe_size;
  4041. if (!devs_max)
  4042. devs_max = BTRFS_MAX_DEVS(info);
  4043. } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
  4044. /* for larger filesystems, use larger metadata chunks */
  4045. if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
  4046. max_stripe_size = SZ_1G;
  4047. else
  4048. max_stripe_size = SZ_256M;
  4049. max_chunk_size = max_stripe_size;
  4050. if (!devs_max)
  4051. devs_max = BTRFS_MAX_DEVS(info);
  4052. } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
  4053. max_stripe_size = SZ_32M;
  4054. max_chunk_size = 2 * max_stripe_size;
  4055. if (!devs_max)
  4056. devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
  4057. } else {
  4058. btrfs_err(info, "invalid chunk type 0x%llx requested",
  4059. type);
  4060. BUG_ON(1);
  4061. }
  4062. /* we don't want a chunk larger than 10% of writeable space */
  4063. max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
  4064. max_chunk_size);
  4065. devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
  4066. GFP_NOFS);
  4067. if (!devices_info)
  4068. return -ENOMEM;
  4069. /*
  4070. * in the first pass through the devices list, we gather information
  4071. * about the available holes on each device.
  4072. */
  4073. ndevs = 0;
  4074. list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
  4075. u64 max_avail;
  4076. u64 dev_offset;
  4077. if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
  4078. WARN(1, KERN_ERR
  4079. "BTRFS: read-only device in alloc_list\n");
  4080. continue;
  4081. }
  4082. if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
  4083. &device->dev_state) ||
  4084. test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
  4085. continue;
  4086. if (device->total_bytes > device->bytes_used)
  4087. total_avail = device->total_bytes - device->bytes_used;
  4088. else
  4089. total_avail = 0;
  4090. /* If there is no space on this device, skip it. */
  4091. if (total_avail == 0)
  4092. continue;
  4093. ret = find_free_dev_extent(trans, device,
  4094. max_stripe_size * dev_stripes,
  4095. &dev_offset, &max_avail);
  4096. if (ret && ret != -ENOSPC)
  4097. goto error;
  4098. if (ret == 0)
  4099. max_avail = max_stripe_size * dev_stripes;
  4100. if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
  4101. if (btrfs_test_opt(info, ENOSPC_DEBUG))
  4102. btrfs_debug(info,
  4103. "%s: devid %llu has no free space, have=%llu want=%u",
  4104. __func__, device->devid, max_avail,
  4105. BTRFS_STRIPE_LEN * dev_stripes);
  4106. continue;
  4107. }
  4108. if (ndevs == fs_devices->rw_devices) {
  4109. WARN(1, "%s: found more than %llu devices\n",
  4110. __func__, fs_devices->rw_devices);
  4111. break;
  4112. }
  4113. devices_info[ndevs].dev_offset = dev_offset;
  4114. devices_info[ndevs].max_avail = max_avail;
  4115. devices_info[ndevs].total_avail = total_avail;
  4116. devices_info[ndevs].dev = device;
  4117. ++ndevs;
  4118. }
  4119. /*
  4120. * now sort the devices by hole size / available space
  4121. */
  4122. sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
  4123. btrfs_cmp_device_info, NULL);
  4124. /* round down to number of usable stripes */
  4125. ndevs = round_down(ndevs, devs_increment);
  4126. if (ndevs < devs_min) {
  4127. ret = -ENOSPC;
  4128. if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
  4129. btrfs_debug(info,
  4130. "%s: not enough devices with free space: have=%d minimum required=%d",
  4131. __func__, ndevs, devs_min);
  4132. }
  4133. goto error;
  4134. }
  4135. ndevs = min(ndevs, devs_max);
  4136. /*
  4137. * The primary goal is to maximize the number of stripes, so use as
  4138. * many devices as possible, even if the stripes are not maximum sized.
  4139. *
  4140. * The DUP profile stores more than one stripe per device, the
  4141. * max_avail is the total size so we have to adjust.
  4142. */
  4143. stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
  4144. num_stripes = ndevs * dev_stripes;
  4145. /*
  4146. * this will have to be fixed for RAID1 and RAID10 over
  4147. * more drives
  4148. */
  4149. data_stripes = num_stripes / ncopies;
  4150. if (type & BTRFS_BLOCK_GROUP_RAID5)
  4151. data_stripes = num_stripes - 1;
  4152. if (type & BTRFS_BLOCK_GROUP_RAID6)
  4153. data_stripes = num_stripes - 2;
  4154. /*
  4155. * Use the number of data stripes to figure out how big this chunk
  4156. * is really going to be in terms of logical address space,
  4157. * and compare that answer with the max chunk size
  4158. */
  4159. if (stripe_size * data_stripes > max_chunk_size) {
  4160. stripe_size = div_u64(max_chunk_size, data_stripes);
  4161. /* bump the answer up to a 16MB boundary */
  4162. stripe_size = round_up(stripe_size, SZ_16M);
  4163. /*
  4164. * But don't go higher than the limits we found while searching
  4165. * for free extents
  4166. */
  4167. stripe_size = min(devices_info[ndevs - 1].max_avail,
  4168. stripe_size);
  4169. }
  4170. /* align to BTRFS_STRIPE_LEN */
  4171. stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
  4172. map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
  4173. if (!map) {
  4174. ret = -ENOMEM;
  4175. goto error;
  4176. }
  4177. map->num_stripes = num_stripes;
  4178. for (i = 0; i < ndevs; ++i) {
  4179. for (j = 0; j < dev_stripes; ++j) {
  4180. int s = i * dev_stripes + j;
  4181. map->stripes[s].dev = devices_info[i].dev;
  4182. map->stripes[s].physical = devices_info[i].dev_offset +
  4183. j * stripe_size;
  4184. }
  4185. }
  4186. map->stripe_len = BTRFS_STRIPE_LEN;
  4187. map->io_align = BTRFS_STRIPE_LEN;
  4188. map->io_width = BTRFS_STRIPE_LEN;
  4189. map->type = type;
  4190. map->sub_stripes = sub_stripes;
  4191. num_bytes = stripe_size * data_stripes;
  4192. trace_btrfs_chunk_alloc(info, map, start, num_bytes);
  4193. em = alloc_extent_map();
  4194. if (!em) {
  4195. kfree(map);
  4196. ret = -ENOMEM;
  4197. goto error;
  4198. }
  4199. set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
  4200. em->map_lookup = map;
  4201. em->start = start;
  4202. em->len = num_bytes;
  4203. em->block_start = 0;
  4204. em->block_len = em->len;
  4205. em->orig_block_len = stripe_size;
  4206. em_tree = &info->mapping_tree.map_tree;
  4207. write_lock(&em_tree->lock);
  4208. ret = add_extent_mapping(em_tree, em, 0);
  4209. if (ret) {
  4210. write_unlock(&em_tree->lock);
  4211. free_extent_map(em);
  4212. goto error;
  4213. }
  4214. list_add_tail(&em->list, &trans->transaction->pending_chunks);
  4215. refcount_inc(&em->refs);
  4216. write_unlock(&em_tree->lock);
  4217. ret = btrfs_make_block_group(trans, info, 0, type, start, num_bytes);
  4218. if (ret)
  4219. goto error_del_extent;
  4220. for (i = 0; i < map->num_stripes; i++) {
  4221. num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
  4222. btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
  4223. }
  4224. atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
  4225. free_extent_map(em);
  4226. check_raid56_incompat_flag(info, type);
  4227. kfree(devices_info);
  4228. return 0;
  4229. error_del_extent:
  4230. write_lock(&em_tree->lock);
  4231. remove_extent_mapping(em_tree, em);
  4232. write_unlock(&em_tree->lock);
  4233. /* One for our allocation */
  4234. free_extent_map(em);
  4235. /* One for the tree reference */
  4236. free_extent_map(em);
  4237. /* One for the pending_chunks list reference */
  4238. free_extent_map(em);
  4239. error:
  4240. kfree(devices_info);
  4241. return ret;
  4242. }
  4243. int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
  4244. struct btrfs_fs_info *fs_info,
  4245. u64 chunk_offset, u64 chunk_size)
  4246. {
  4247. struct btrfs_root *extent_root = fs_info->extent_root;
  4248. struct btrfs_root *chunk_root = fs_info->chunk_root;
  4249. struct btrfs_key key;
  4250. struct btrfs_device *device;
  4251. struct btrfs_chunk *chunk;
  4252. struct btrfs_stripe *stripe;
  4253. struct extent_map *em;
  4254. struct map_lookup *map;
  4255. size_t item_size;
  4256. u64 dev_offset;
  4257. u64 stripe_size;
  4258. int i = 0;
  4259. int ret = 0;
  4260. em = get_chunk_map(fs_info, chunk_offset, chunk_size);
  4261. if (IS_ERR(em))
  4262. return PTR_ERR(em);
  4263. map = em->map_lookup;
  4264. item_size = btrfs_chunk_item_size(map->num_stripes);
  4265. stripe_size = em->orig_block_len;
  4266. chunk = kzalloc(item_size, GFP_NOFS);
  4267. if (!chunk) {
  4268. ret = -ENOMEM;
  4269. goto out;
  4270. }
  4271. /*
  4272. * Take the device list mutex to prevent races with the final phase of
  4273. * a device replace operation that replaces the device object associated
  4274. * with the map's stripes, because the device object's id can change
  4275. * at any time during that final phase of the device replace operation
  4276. * (dev-replace.c:btrfs_dev_replace_finishing()).
  4277. */
  4278. mutex_lock(&fs_info->fs_devices->device_list_mutex);
  4279. for (i = 0; i < map->num_stripes; i++) {
  4280. device = map->stripes[i].dev;
  4281. dev_offset = map->stripes[i].physical;
  4282. ret = btrfs_update_device(trans, device);
  4283. if (ret)
  4284. break;
  4285. ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
  4286. dev_offset, stripe_size);
  4287. if (ret)
  4288. break;
  4289. }
  4290. if (ret) {
  4291. mutex_unlock(&fs_info->fs_devices->device_list_mutex);
  4292. goto out;
  4293. }
  4294. stripe = &chunk->stripe;
  4295. for (i = 0; i < map->num_stripes; i++) {
  4296. device = map->stripes[i].dev;
  4297. dev_offset = map->stripes[i].physical;
  4298. btrfs_set_stack_stripe_devid(stripe, device->devid);
  4299. btrfs_set_stack_stripe_offset(stripe, dev_offset);
  4300. memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
  4301. stripe++;
  4302. }
  4303. mutex_unlock(&fs_info->fs_devices->device_list_mutex);
  4304. btrfs_set_stack_chunk_length(chunk, chunk_size);
  4305. btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
  4306. btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
  4307. btrfs_set_stack_chunk_type(chunk, map->type);
  4308. btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
  4309. btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
  4310. btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
  4311. btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
  4312. btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
  4313. key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
  4314. key.type = BTRFS_CHUNK_ITEM_KEY;
  4315. key.offset = chunk_offset;
  4316. ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
  4317. if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
  4318. /*
  4319. * TODO: Cleanup of inserted chunk root in case of
  4320. * failure.
  4321. */
  4322. ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
  4323. }
  4324. out:
  4325. kfree(chunk);
  4326. free_extent_map(em);
  4327. return ret;
  4328. }
  4329. /*
  4330. * Chunk allocation falls into two parts. The first part does works
  4331. * that make the new allocated chunk useable, but not do any operation
  4332. * that modifies the chunk tree. The second part does the works that
  4333. * require modifying the chunk tree. This division is important for the
  4334. * bootstrap process of adding storage to a seed btrfs.
  4335. */
  4336. int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
  4337. struct btrfs_fs_info *fs_info, u64 type)
  4338. {
  4339. u64 chunk_offset;
  4340. lockdep_assert_held(&fs_info->chunk_mutex);
  4341. chunk_offset = find_next_chunk(fs_info);
  4342. return __btrfs_alloc_chunk(trans, chunk_offset, type);
  4343. }
  4344. static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
  4345. struct btrfs_fs_info *fs_info)
  4346. {
  4347. u64 chunk_offset;
  4348. u64 sys_chunk_offset;
  4349. u64 alloc_profile;
  4350. int ret;
  4351. chunk_offset = find_next_chunk(fs_info);
  4352. alloc_profile = btrfs_metadata_alloc_profile(fs_info);
  4353. ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
  4354. if (ret)
  4355. return ret;
  4356. sys_chunk_offset = find_next_chunk(fs_info);
  4357. alloc_profile = btrfs_system_alloc_profile(fs_info);
  4358. ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
  4359. return ret;
  4360. }
  4361. static inline int btrfs_chunk_max_errors(struct map_lookup *map)
  4362. {
  4363. int max_errors;
  4364. if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
  4365. BTRFS_BLOCK_GROUP_RAID10 |
  4366. BTRFS_BLOCK_GROUP_RAID5 |
  4367. BTRFS_BLOCK_GROUP_DUP)) {
  4368. max_errors = 1;
  4369. } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
  4370. max_errors = 2;
  4371. } else {
  4372. max_errors = 0;
  4373. }
  4374. return max_errors;
  4375. }
  4376. int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
  4377. {
  4378. struct extent_map *em;
  4379. struct map_lookup *map;
  4380. int readonly = 0;
  4381. int miss_ndevs = 0;
  4382. int i;
  4383. em = get_chunk_map(fs_info, chunk_offset, 1);
  4384. if (IS_ERR(em))
  4385. return 1;
  4386. map = em->map_lookup;
  4387. for (i = 0; i < map->num_stripes; i++) {
  4388. if (test_bit(BTRFS_DEV_STATE_MISSING,
  4389. &map->stripes[i].dev->dev_state)) {
  4390. miss_ndevs++;
  4391. continue;
  4392. }
  4393. if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
  4394. &map->stripes[i].dev->dev_state)) {
  4395. readonly = 1;
  4396. goto end;
  4397. }
  4398. }
  4399. /*
  4400. * If the number of missing devices is larger than max errors,
  4401. * we can not write the data into that chunk successfully, so
  4402. * set it readonly.
  4403. */
  4404. if (miss_ndevs > btrfs_chunk_max_errors(map))
  4405. readonly = 1;
  4406. end:
  4407. free_extent_map(em);
  4408. return readonly;
  4409. }
  4410. void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
  4411. {
  4412. extent_map_tree_init(&tree->map_tree);
  4413. }
  4414. void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
  4415. {
  4416. struct extent_map *em;
  4417. while (1) {
  4418. write_lock(&tree->map_tree.lock);
  4419. em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
  4420. if (em)
  4421. remove_extent_mapping(&tree->map_tree, em);
  4422. write_unlock(&tree->map_tree.lock);
  4423. if (!em)
  4424. break;
  4425. /* once for us */
  4426. free_extent_map(em);
  4427. /* once for the tree */
  4428. free_extent_map(em);
  4429. }
  4430. }
  4431. int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
  4432. {
  4433. struct extent_map *em;
  4434. struct map_lookup *map;
  4435. int ret;
  4436. em = get_chunk_map(fs_info, logical, len);
  4437. if (IS_ERR(em))
  4438. /*
  4439. * We could return errors for these cases, but that could get
  4440. * ugly and we'd probably do the same thing which is just not do
  4441. * anything else and exit, so return 1 so the callers don't try
  4442. * to use other copies.
  4443. */
  4444. return 1;
  4445. map = em->map_lookup;
  4446. if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
  4447. ret = map->num_stripes;
  4448. else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
  4449. ret = map->sub_stripes;
  4450. else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
  4451. ret = 2;
  4452. else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
  4453. /*
  4454. * There could be two corrupted data stripes, we need
  4455. * to loop retry in order to rebuild the correct data.
  4456. *
  4457. * Fail a stripe at a time on every retry except the
  4458. * stripe under reconstruction.
  4459. */
  4460. ret = map->num_stripes;
  4461. else
  4462. ret = 1;
  4463. free_extent_map(em);
  4464. btrfs_dev_replace_read_lock(&fs_info->dev_replace);
  4465. if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
  4466. fs_info->dev_replace.tgtdev)
  4467. ret++;
  4468. btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
  4469. return ret;
  4470. }
  4471. unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
  4472. u64 logical)
  4473. {
  4474. struct extent_map *em;
  4475. struct map_lookup *map;
  4476. unsigned long len = fs_info->sectorsize;
  4477. em = get_chunk_map(fs_info, logical, len);
  4478. if (!WARN_ON(IS_ERR(em))) {
  4479. map = em->map_lookup;
  4480. if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
  4481. len = map->stripe_len * nr_data_stripes(map);
  4482. free_extent_map(em);
  4483. }
  4484. return len;
  4485. }
  4486. int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
  4487. {
  4488. struct extent_map *em;
  4489. struct map_lookup *map;
  4490. int ret = 0;
  4491. em = get_chunk_map(fs_info, logical, len);
  4492. if(!WARN_ON(IS_ERR(em))) {
  4493. map = em->map_lookup;
  4494. if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
  4495. ret = 1;
  4496. free_extent_map(em);
  4497. }
  4498. return ret;
  4499. }
  4500. static int find_live_mirror(struct btrfs_fs_info *fs_info,
  4501. struct map_lookup *map, int first,
  4502. int dev_replace_is_ongoing)
  4503. {
  4504. int i;
  4505. int num_stripes;
  4506. int preferred_mirror;
  4507. int tolerance;
  4508. struct btrfs_device *srcdev;
  4509. ASSERT((map->type &
  4510. (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
  4511. if (map->type & BTRFS_BLOCK_GROUP_RAID10)
  4512. num_stripes = map->sub_stripes;
  4513. else
  4514. num_stripes = map->num_stripes;
  4515. preferred_mirror = first + current->pid % num_stripes;
  4516. if (dev_replace_is_ongoing &&
  4517. fs_info->dev_replace.cont_reading_from_srcdev_mode ==
  4518. BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
  4519. srcdev = fs_info->dev_replace.srcdev;
  4520. else
  4521. srcdev = NULL;
  4522. /*
  4523. * try to avoid the drive that is the source drive for a
  4524. * dev-replace procedure, only choose it if no other non-missing
  4525. * mirror is available
  4526. */
  4527. for (tolerance = 0; tolerance < 2; tolerance++) {
  4528. if (map->stripes[preferred_mirror].dev->bdev &&
  4529. (tolerance || map->stripes[preferred_mirror].dev != srcdev))
  4530. return preferred_mirror;
  4531. for (i = first; i < first + num_stripes; i++) {
  4532. if (map->stripes[i].dev->bdev &&
  4533. (tolerance || map->stripes[i].dev != srcdev))
  4534. return i;
  4535. }
  4536. }
  4537. /* we couldn't find one that doesn't fail. Just return something
  4538. * and the io error handling code will clean up eventually
  4539. */
  4540. return preferred_mirror;
  4541. }
  4542. static inline int parity_smaller(u64 a, u64 b)
  4543. {
  4544. return a > b;
  4545. }
  4546. /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
  4547. static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
  4548. {
  4549. struct btrfs_bio_stripe s;
  4550. int i;
  4551. u64 l;
  4552. int again = 1;
  4553. while (again) {
  4554. again = 0;
  4555. for (i = 0; i < num_stripes - 1; i++) {
  4556. if (parity_smaller(bbio->raid_map[i],
  4557. bbio->raid_map[i+1])) {
  4558. s = bbio->stripes[i];
  4559. l = bbio->raid_map[i];
  4560. bbio->stripes[i] = bbio->stripes[i+1];
  4561. bbio->raid_map[i] = bbio->raid_map[i+1];
  4562. bbio->stripes[i+1] = s;
  4563. bbio->raid_map[i+1] = l;
  4564. again = 1;
  4565. }
  4566. }
  4567. }
  4568. }
  4569. static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
  4570. {
  4571. struct btrfs_bio *bbio = kzalloc(
  4572. /* the size of the btrfs_bio */
  4573. sizeof(struct btrfs_bio) +
  4574. /* plus the variable array for the stripes */
  4575. sizeof(struct btrfs_bio_stripe) * (total_stripes) +
  4576. /* plus the variable array for the tgt dev */
  4577. sizeof(int) * (real_stripes) +
  4578. /*
  4579. * plus the raid_map, which includes both the tgt dev
  4580. * and the stripes
  4581. */
  4582. sizeof(u64) * (total_stripes),
  4583. GFP_NOFS|__GFP_NOFAIL);
  4584. atomic_set(&bbio->error, 0);
  4585. refcount_set(&bbio->refs, 1);
  4586. return bbio;
  4587. }
  4588. void btrfs_get_bbio(struct btrfs_bio *bbio)
  4589. {
  4590. WARN_ON(!refcount_read(&bbio->refs));
  4591. refcount_inc(&bbio->refs);
  4592. }
  4593. void btrfs_put_bbio(struct btrfs_bio *bbio)
  4594. {
  4595. if (!bbio)
  4596. return;
  4597. if (refcount_dec_and_test(&bbio->refs))
  4598. kfree(bbio);
  4599. }
  4600. /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
  4601. /*
  4602. * Please note that, discard won't be sent to target device of device
  4603. * replace.
  4604. */
  4605. static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
  4606. u64 logical, u64 length,
  4607. struct btrfs_bio **bbio_ret)
  4608. {
  4609. struct extent_map *em;
  4610. struct map_lookup *map;
  4611. struct btrfs_bio *bbio;
  4612. u64 offset;
  4613. u64 stripe_nr;
  4614. u64 stripe_nr_end;
  4615. u64 stripe_end_offset;
  4616. u64 stripe_cnt;
  4617. u64 stripe_len;
  4618. u64 stripe_offset;
  4619. u64 num_stripes;
  4620. u32 stripe_index;
  4621. u32 factor = 0;
  4622. u32 sub_stripes = 0;
  4623. u64 stripes_per_dev = 0;
  4624. u32 remaining_stripes = 0;
  4625. u32 last_stripe = 0;
  4626. int ret = 0;
  4627. int i;
  4628. /* discard always return a bbio */
  4629. ASSERT(bbio_ret);
  4630. em = get_chunk_map(fs_info, logical, length);
  4631. if (IS_ERR(em))
  4632. return PTR_ERR(em);
  4633. map = em->map_lookup;
  4634. /* we don't discard raid56 yet */
  4635. if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
  4636. ret = -EOPNOTSUPP;
  4637. goto out;
  4638. }
  4639. offset = logical - em->start;
  4640. length = min_t(u64, em->len - offset, length);
  4641. stripe_len = map->stripe_len;
  4642. /*
  4643. * stripe_nr counts the total number of stripes we have to stride
  4644. * to get to this block
  4645. */
  4646. stripe_nr = div64_u64(offset, stripe_len);
  4647. /* stripe_offset is the offset of this block in its stripe */
  4648. stripe_offset = offset - stripe_nr * stripe_len;
  4649. stripe_nr_end = round_up(offset + length, map->stripe_len);
  4650. stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
  4651. stripe_cnt = stripe_nr_end - stripe_nr;
  4652. stripe_end_offset = stripe_nr_end * map->stripe_len -
  4653. (offset + length);
  4654. /*
  4655. * after this, stripe_nr is the number of stripes on this
  4656. * device we have to walk to find the data, and stripe_index is
  4657. * the number of our device in the stripe array
  4658. */
  4659. num_stripes = 1;
  4660. stripe_index = 0;
  4661. if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
  4662. BTRFS_BLOCK_GROUP_RAID10)) {
  4663. if (map->type & BTRFS_BLOCK_GROUP_RAID0)
  4664. sub_stripes = 1;
  4665. else
  4666. sub_stripes = map->sub_stripes;
  4667. factor = map->num_stripes / sub_stripes;
  4668. num_stripes = min_t(u64, map->num_stripes,
  4669. sub_stripes * stripe_cnt);
  4670. stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
  4671. stripe_index *= sub_stripes;
  4672. stripes_per_dev = div_u64_rem(stripe_cnt, factor,
  4673. &remaining_stripes);
  4674. div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
  4675. last_stripe *= sub_stripes;
  4676. } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
  4677. BTRFS_BLOCK_GROUP_DUP)) {
  4678. num_stripes = map->num_stripes;
  4679. } else {
  4680. stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
  4681. &stripe_index);
  4682. }
  4683. bbio = alloc_btrfs_bio(num_stripes, 0);
  4684. if (!bbio) {
  4685. ret = -ENOMEM;
  4686. goto out;
  4687. }
  4688. for (i = 0; i < num_stripes; i++) {
  4689. bbio->stripes[i].physical =
  4690. map->stripes[stripe_index].physical +
  4691. stripe_offset + stripe_nr * map->stripe_len;
  4692. bbio->stripes[i].dev = map->stripes[stripe_index].dev;
  4693. if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
  4694. BTRFS_BLOCK_GROUP_RAID10)) {
  4695. bbio->stripes[i].length = stripes_per_dev *
  4696. map->stripe_len;
  4697. if (i / sub_stripes < remaining_stripes)
  4698. bbio->stripes[i].length +=
  4699. map->stripe_len;
  4700. /*
  4701. * Special for the first stripe and
  4702. * the last stripe:
  4703. *
  4704. * |-------|...|-------|
  4705. * |----------|
  4706. * off end_off
  4707. */
  4708. if (i < sub_stripes)
  4709. bbio->stripes[i].length -=
  4710. stripe_offset;
  4711. if (stripe_index >= last_stripe &&
  4712. stripe_index <= (last_stripe +
  4713. sub_stripes - 1))
  4714. bbio->stripes[i].length -=
  4715. stripe_end_offset;
  4716. if (i == sub_stripes - 1)
  4717. stripe_offset = 0;
  4718. } else {
  4719. bbio->stripes[i].length = length;
  4720. }
  4721. stripe_index++;
  4722. if (stripe_index == map->num_stripes) {
  4723. stripe_index = 0;
  4724. stripe_nr++;
  4725. }
  4726. }
  4727. *bbio_ret = bbio;
  4728. bbio->map_type = map->type;
  4729. bbio->num_stripes = num_stripes;
  4730. out:
  4731. free_extent_map(em);
  4732. return ret;
  4733. }
  4734. /*
  4735. * In dev-replace case, for repair case (that's the only case where the mirror
  4736. * is selected explicitly when calling btrfs_map_block), blocks left of the
  4737. * left cursor can also be read from the target drive.
  4738. *
  4739. * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
  4740. * array of stripes.
  4741. * For READ, it also needs to be supported using the same mirror number.
  4742. *
  4743. * If the requested block is not left of the left cursor, EIO is returned. This
  4744. * can happen because btrfs_num_copies() returns one more in the dev-replace
  4745. * case.
  4746. */
  4747. static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
  4748. u64 logical, u64 length,
  4749. u64 srcdev_devid, int *mirror_num,
  4750. u64 *physical)
  4751. {
  4752. struct btrfs_bio *bbio = NULL;
  4753. int num_stripes;
  4754. int index_srcdev = 0;
  4755. int found = 0;
  4756. u64 physical_of_found = 0;
  4757. int i;
  4758. int ret = 0;
  4759. ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
  4760. logical, &length, &bbio, 0, 0);
  4761. if (ret) {
  4762. ASSERT(bbio == NULL);
  4763. return ret;
  4764. }
  4765. num_stripes = bbio->num_stripes;
  4766. if (*mirror_num > num_stripes) {
  4767. /*
  4768. * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
  4769. * that means that the requested area is not left of the left
  4770. * cursor
  4771. */
  4772. btrfs_put_bbio(bbio);
  4773. return -EIO;
  4774. }
  4775. /*
  4776. * process the rest of the function using the mirror_num of the source
  4777. * drive. Therefore look it up first. At the end, patch the device
  4778. * pointer to the one of the target drive.
  4779. */
  4780. for (i = 0; i < num_stripes; i++) {
  4781. if (bbio->stripes[i].dev->devid != srcdev_devid)
  4782. continue;
  4783. /*
  4784. * In case of DUP, in order to keep it simple, only add the
  4785. * mirror with the lowest physical address
  4786. */
  4787. if (found &&
  4788. physical_of_found <= bbio->stripes[i].physical)
  4789. continue;
  4790. index_srcdev = i;
  4791. found = 1;
  4792. physical_of_found = bbio->stripes[i].physical;
  4793. }
  4794. btrfs_put_bbio(bbio);
  4795. ASSERT(found);
  4796. if (!found)
  4797. return -EIO;
  4798. *mirror_num = index_srcdev + 1;
  4799. *physical = physical_of_found;
  4800. return ret;
  4801. }
  4802. static void handle_ops_on_dev_replace(enum btrfs_map_op op,
  4803. struct btrfs_bio **bbio_ret,
  4804. struct btrfs_dev_replace *dev_replace,
  4805. int *num_stripes_ret, int *max_errors_ret)
  4806. {
  4807. struct btrfs_bio *bbio = *bbio_ret;
  4808. u64 srcdev_devid = dev_replace->srcdev->devid;
  4809. int tgtdev_indexes = 0;
  4810. int num_stripes = *num_stripes_ret;
  4811. int max_errors = *max_errors_ret;
  4812. int i;
  4813. if (op == BTRFS_MAP_WRITE) {
  4814. int index_where_to_add;
  4815. /*
  4816. * duplicate the write operations while the dev replace
  4817. * procedure is running. Since the copying of the old disk to
  4818. * the new disk takes place at run time while the filesystem is
  4819. * mounted writable, the regular write operations to the old
  4820. * disk have to be duplicated to go to the new disk as well.
  4821. *
  4822. * Note that device->missing is handled by the caller, and that
  4823. * the write to the old disk is already set up in the stripes
  4824. * array.
  4825. */
  4826. index_where_to_add = num_stripes;
  4827. for (i = 0; i < num_stripes; i++) {
  4828. if (bbio->stripes[i].dev->devid == srcdev_devid) {
  4829. /* write to new disk, too */
  4830. struct btrfs_bio_stripe *new =
  4831. bbio->stripes + index_where_to_add;
  4832. struct btrfs_bio_stripe *old =
  4833. bbio->stripes + i;
  4834. new->physical = old->physical;
  4835. new->length = old->length;
  4836. new->dev = dev_replace->tgtdev;
  4837. bbio->tgtdev_map[i] = index_where_to_add;
  4838. index_where_to_add++;
  4839. max_errors++;
  4840. tgtdev_indexes++;
  4841. }
  4842. }
  4843. num_stripes = index_where_to_add;
  4844. } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
  4845. int index_srcdev = 0;
  4846. int found = 0;
  4847. u64 physical_of_found = 0;
  4848. /*
  4849. * During the dev-replace procedure, the target drive can also
  4850. * be used to read data in case it is needed to repair a corrupt
  4851. * block elsewhere. This is possible if the requested area is
  4852. * left of the left cursor. In this area, the target drive is a
  4853. * full copy of the source drive.
  4854. */
  4855. for (i = 0; i < num_stripes; i++) {
  4856. if (bbio->stripes[i].dev->devid == srcdev_devid) {
  4857. /*
  4858. * In case of DUP, in order to keep it simple,
  4859. * only add the mirror with the lowest physical
  4860. * address
  4861. */
  4862. if (found &&
  4863. physical_of_found <=
  4864. bbio->stripes[i].physical)
  4865. continue;
  4866. index_srcdev = i;
  4867. found = 1;
  4868. physical_of_found = bbio->stripes[i].physical;
  4869. }
  4870. }
  4871. if (found) {
  4872. struct btrfs_bio_stripe *tgtdev_stripe =
  4873. bbio->stripes + num_stripes;
  4874. tgtdev_stripe->physical = physical_of_found;
  4875. tgtdev_stripe->length =
  4876. bbio->stripes[index_srcdev].length;
  4877. tgtdev_stripe->dev = dev_replace->tgtdev;
  4878. bbio->tgtdev_map[index_srcdev] = num_stripes;
  4879. tgtdev_indexes++;
  4880. num_stripes++;
  4881. }
  4882. }
  4883. *num_stripes_ret = num_stripes;
  4884. *max_errors_ret = max_errors;
  4885. bbio->num_tgtdevs = tgtdev_indexes;
  4886. *bbio_ret = bbio;
  4887. }
  4888. static bool need_full_stripe(enum btrfs_map_op op)
  4889. {
  4890. return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
  4891. }
  4892. static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
  4893. enum btrfs_map_op op,
  4894. u64 logical, u64 *length,
  4895. struct btrfs_bio **bbio_ret,
  4896. int mirror_num, int need_raid_map)
  4897. {
  4898. struct extent_map *em;
  4899. struct map_lookup *map;
  4900. u64 offset;
  4901. u64 stripe_offset;
  4902. u64 stripe_nr;
  4903. u64 stripe_len;
  4904. u32 stripe_index;
  4905. int i;
  4906. int ret = 0;
  4907. int num_stripes;
  4908. int max_errors = 0;
  4909. int tgtdev_indexes = 0;
  4910. struct btrfs_bio *bbio = NULL;
  4911. struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
  4912. int dev_replace_is_ongoing = 0;
  4913. int num_alloc_stripes;
  4914. int patch_the_first_stripe_for_dev_replace = 0;
  4915. u64 physical_to_patch_in_first_stripe = 0;
  4916. u64 raid56_full_stripe_start = (u64)-1;
  4917. if (op == BTRFS_MAP_DISCARD)
  4918. return __btrfs_map_block_for_discard(fs_info, logical,
  4919. *length, bbio_ret);
  4920. em = get_chunk_map(fs_info, logical, *length);
  4921. if (IS_ERR(em))
  4922. return PTR_ERR(em);
  4923. map = em->map_lookup;
  4924. offset = logical - em->start;
  4925. stripe_len = map->stripe_len;
  4926. stripe_nr = offset;
  4927. /*
  4928. * stripe_nr counts the total number of stripes we have to stride
  4929. * to get to this block
  4930. */
  4931. stripe_nr = div64_u64(stripe_nr, stripe_len);
  4932. stripe_offset = stripe_nr * stripe_len;
  4933. if (offset < stripe_offset) {
  4934. btrfs_crit(fs_info,
  4935. "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
  4936. stripe_offset, offset, em->start, logical,
  4937. stripe_len);
  4938. free_extent_map(em);
  4939. return -EINVAL;
  4940. }
  4941. /* stripe_offset is the offset of this block in its stripe*/
  4942. stripe_offset = offset - stripe_offset;
  4943. /* if we're here for raid56, we need to know the stripe aligned start */
  4944. if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
  4945. unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
  4946. raid56_full_stripe_start = offset;
  4947. /* allow a write of a full stripe, but make sure we don't
  4948. * allow straddling of stripes
  4949. */
  4950. raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
  4951. full_stripe_len);
  4952. raid56_full_stripe_start *= full_stripe_len;
  4953. }
  4954. if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
  4955. u64 max_len;
  4956. /* For writes to RAID[56], allow a full stripeset across all disks.
  4957. For other RAID types and for RAID[56] reads, just allow a single
  4958. stripe (on a single disk). */
  4959. if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
  4960. (op == BTRFS_MAP_WRITE)) {
  4961. max_len = stripe_len * nr_data_stripes(map) -
  4962. (offset - raid56_full_stripe_start);
  4963. } else {
  4964. /* we limit the length of each bio to what fits in a stripe */
  4965. max_len = stripe_len - stripe_offset;
  4966. }
  4967. *length = min_t(u64, em->len - offset, max_len);
  4968. } else {
  4969. *length = em->len - offset;
  4970. }
  4971. /* This is for when we're called from btrfs_merge_bio_hook() and all
  4972. it cares about is the length */
  4973. if (!bbio_ret)
  4974. goto out;
  4975. btrfs_dev_replace_read_lock(dev_replace);
  4976. dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
  4977. if (!dev_replace_is_ongoing)
  4978. btrfs_dev_replace_read_unlock(dev_replace);
  4979. else
  4980. btrfs_dev_replace_set_lock_blocking(dev_replace);
  4981. if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
  4982. !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
  4983. ret = get_extra_mirror_from_replace(fs_info, logical, *length,
  4984. dev_replace->srcdev->devid,
  4985. &mirror_num,
  4986. &physical_to_patch_in_first_stripe);
  4987. if (ret)
  4988. goto out;
  4989. else
  4990. patch_the_first_stripe_for_dev_replace = 1;
  4991. } else if (mirror_num > map->num_stripes) {
  4992. mirror_num = 0;
  4993. }
  4994. num_stripes = 1;
  4995. stripe_index = 0;
  4996. if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
  4997. stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
  4998. &stripe_index);
  4999. if (!need_full_stripe(op))
  5000. mirror_num = 1;
  5001. } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
  5002. if (need_full_stripe(op))
  5003. num_stripes = map->num_stripes;
  5004. else if (mirror_num)
  5005. stripe_index = mirror_num - 1;
  5006. else {
  5007. stripe_index = find_live_mirror(fs_info, map, 0,
  5008. dev_replace_is_ongoing);
  5009. mirror_num = stripe_index + 1;
  5010. }
  5011. } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
  5012. if (need_full_stripe(op)) {
  5013. num_stripes = map->num_stripes;
  5014. } else if (mirror_num) {
  5015. stripe_index = mirror_num - 1;
  5016. } else {
  5017. mirror_num = 1;
  5018. }
  5019. } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
  5020. u32 factor = map->num_stripes / map->sub_stripes;
  5021. stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
  5022. stripe_index *= map->sub_stripes;
  5023. if (need_full_stripe(op))
  5024. num_stripes = map->sub_stripes;
  5025. else if (mirror_num)
  5026. stripe_index += mirror_num - 1;
  5027. else {
  5028. int old_stripe_index = stripe_index;
  5029. stripe_index = find_live_mirror(fs_info, map,
  5030. stripe_index,
  5031. dev_replace_is_ongoing);
  5032. mirror_num = stripe_index - old_stripe_index + 1;
  5033. }
  5034. } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
  5035. if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
  5036. /* push stripe_nr back to the start of the full stripe */
  5037. stripe_nr = div64_u64(raid56_full_stripe_start,
  5038. stripe_len * nr_data_stripes(map));
  5039. /* RAID[56] write or recovery. Return all stripes */
  5040. num_stripes = map->num_stripes;
  5041. max_errors = nr_parity_stripes(map);
  5042. *length = map->stripe_len;
  5043. stripe_index = 0;
  5044. stripe_offset = 0;
  5045. } else {
  5046. /*
  5047. * Mirror #0 or #1 means the original data block.
  5048. * Mirror #2 is RAID5 parity block.
  5049. * Mirror #3 is RAID6 Q block.
  5050. */
  5051. stripe_nr = div_u64_rem(stripe_nr,
  5052. nr_data_stripes(map), &stripe_index);
  5053. if (mirror_num > 1)
  5054. stripe_index = nr_data_stripes(map) +
  5055. mirror_num - 2;
  5056. /* We distribute the parity blocks across stripes */
  5057. div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
  5058. &stripe_index);
  5059. if (!need_full_stripe(op) && mirror_num <= 1)
  5060. mirror_num = 1;
  5061. }
  5062. } else {
  5063. /*
  5064. * after this, stripe_nr is the number of stripes on this
  5065. * device we have to walk to find the data, and stripe_index is
  5066. * the number of our device in the stripe array
  5067. */
  5068. stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
  5069. &stripe_index);
  5070. mirror_num = stripe_index + 1;
  5071. }
  5072. if (stripe_index >= map->num_stripes) {
  5073. btrfs_crit(fs_info,
  5074. "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
  5075. stripe_index, map->num_stripes);
  5076. ret = -EINVAL;
  5077. goto out;
  5078. }
  5079. num_alloc_stripes = num_stripes;
  5080. if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
  5081. if (op == BTRFS_MAP_WRITE)
  5082. num_alloc_stripes <<= 1;
  5083. if (op == BTRFS_MAP_GET_READ_MIRRORS)
  5084. num_alloc_stripes++;
  5085. tgtdev_indexes = num_stripes;
  5086. }
  5087. bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
  5088. if (!bbio) {
  5089. ret = -ENOMEM;
  5090. goto out;
  5091. }
  5092. if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
  5093. bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
  5094. /* build raid_map */
  5095. if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
  5096. (need_full_stripe(op) || mirror_num > 1)) {
  5097. u64 tmp;
  5098. unsigned rot;
  5099. bbio->raid_map = (u64 *)((void *)bbio->stripes +
  5100. sizeof(struct btrfs_bio_stripe) *
  5101. num_alloc_stripes +
  5102. sizeof(int) * tgtdev_indexes);
  5103. /* Work out the disk rotation on this stripe-set */
  5104. div_u64_rem(stripe_nr, num_stripes, &rot);
  5105. /* Fill in the logical address of each stripe */
  5106. tmp = stripe_nr * nr_data_stripes(map);
  5107. for (i = 0; i < nr_data_stripes(map); i++)
  5108. bbio->raid_map[(i+rot) % num_stripes] =
  5109. em->start + (tmp + i) * map->stripe_len;
  5110. bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
  5111. if (map->type & BTRFS_BLOCK_GROUP_RAID6)
  5112. bbio->raid_map[(i+rot+1) % num_stripes] =
  5113. RAID6_Q_STRIPE;
  5114. }
  5115. for (i = 0; i < num_stripes; i++) {
  5116. bbio->stripes[i].physical =
  5117. map->stripes[stripe_index].physical +
  5118. stripe_offset +
  5119. stripe_nr * map->stripe_len;
  5120. bbio->stripes[i].dev =
  5121. map->stripes[stripe_index].dev;
  5122. stripe_index++;
  5123. }
  5124. if (need_full_stripe(op))
  5125. max_errors = btrfs_chunk_max_errors(map);
  5126. if (bbio->raid_map)
  5127. sort_parity_stripes(bbio, num_stripes);
  5128. if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
  5129. need_full_stripe(op)) {
  5130. handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
  5131. &max_errors);
  5132. }
  5133. *bbio_ret = bbio;
  5134. bbio->map_type = map->type;
  5135. bbio->num_stripes = num_stripes;
  5136. bbio->max_errors = max_errors;
  5137. bbio->mirror_num = mirror_num;
  5138. /*
  5139. * this is the case that REQ_READ && dev_replace_is_ongoing &&
  5140. * mirror_num == num_stripes + 1 && dev_replace target drive is
  5141. * available as a mirror
  5142. */
  5143. if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
  5144. WARN_ON(num_stripes > 1);
  5145. bbio->stripes[0].dev = dev_replace->tgtdev;
  5146. bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
  5147. bbio->mirror_num = map->num_stripes + 1;
  5148. }
  5149. out:
  5150. if (dev_replace_is_ongoing) {
  5151. btrfs_dev_replace_clear_lock_blocking(dev_replace);
  5152. btrfs_dev_replace_read_unlock(dev_replace);
  5153. }
  5154. free_extent_map(em);
  5155. return ret;
  5156. }
  5157. int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
  5158. u64 logical, u64 *length,
  5159. struct btrfs_bio **bbio_ret, int mirror_num)
  5160. {
  5161. return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
  5162. mirror_num, 0);
  5163. }
  5164. /* For Scrub/replace */
  5165. int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
  5166. u64 logical, u64 *length,
  5167. struct btrfs_bio **bbio_ret)
  5168. {
  5169. return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
  5170. }
  5171. int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
  5172. u64 physical, u64 **logical, int *naddrs, int *stripe_len)
  5173. {
  5174. struct extent_map *em;
  5175. struct map_lookup *map;
  5176. u64 *buf;
  5177. u64 bytenr;
  5178. u64 length;
  5179. u64 stripe_nr;
  5180. u64 rmap_len;
  5181. int i, j, nr = 0;
  5182. em = get_chunk_map(fs_info, chunk_start, 1);
  5183. if (IS_ERR(em))
  5184. return -EIO;
  5185. map = em->map_lookup;
  5186. length = em->len;
  5187. rmap_len = map->stripe_len;
  5188. if (map->type & BTRFS_BLOCK_GROUP_RAID10)
  5189. length = div_u64(length, map->num_stripes / map->sub_stripes);
  5190. else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
  5191. length = div_u64(length, map->num_stripes);
  5192. else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
  5193. length = div_u64(length, nr_data_stripes(map));
  5194. rmap_len = map->stripe_len * nr_data_stripes(map);
  5195. }
  5196. buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
  5197. BUG_ON(!buf); /* -ENOMEM */
  5198. for (i = 0; i < map->num_stripes; i++) {
  5199. if (map->stripes[i].physical > physical ||
  5200. map->stripes[i].physical + length <= physical)
  5201. continue;
  5202. stripe_nr = physical - map->stripes[i].physical;
  5203. stripe_nr = div64_u64(stripe_nr, map->stripe_len);
  5204. if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
  5205. stripe_nr = stripe_nr * map->num_stripes + i;
  5206. stripe_nr = div_u64(stripe_nr, map->sub_stripes);
  5207. } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
  5208. stripe_nr = stripe_nr * map->num_stripes + i;
  5209. } /* else if RAID[56], multiply by nr_data_stripes().
  5210. * Alternatively, just use rmap_len below instead of
  5211. * map->stripe_len */
  5212. bytenr = chunk_start + stripe_nr * rmap_len;
  5213. WARN_ON(nr >= map->num_stripes);
  5214. for (j = 0; j < nr; j++) {
  5215. if (buf[j] == bytenr)
  5216. break;
  5217. }
  5218. if (j == nr) {
  5219. WARN_ON(nr >= map->num_stripes);
  5220. buf[nr++] = bytenr;
  5221. }
  5222. }
  5223. *logical = buf;
  5224. *naddrs = nr;
  5225. *stripe_len = rmap_len;
  5226. free_extent_map(em);
  5227. return 0;
  5228. }
  5229. static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
  5230. {
  5231. bio->bi_private = bbio->private;
  5232. bio->bi_end_io = bbio->end_io;
  5233. bio_endio(bio);
  5234. btrfs_put_bbio(bbio);
  5235. }
  5236. static void btrfs_end_bio(struct bio *bio)
  5237. {
  5238. struct btrfs_bio *bbio = bio->bi_private;
  5239. int is_orig_bio = 0;
  5240. if (bio->bi_status) {
  5241. atomic_inc(&bbio->error);
  5242. if (bio->bi_status == BLK_STS_IOERR ||
  5243. bio->bi_status == BLK_STS_TARGET) {
  5244. unsigned int stripe_index =
  5245. btrfs_io_bio(bio)->stripe_index;
  5246. struct btrfs_device *dev;
  5247. BUG_ON(stripe_index >= bbio->num_stripes);
  5248. dev = bbio->stripes[stripe_index].dev;
  5249. if (dev->bdev) {
  5250. if (bio_op(bio) == REQ_OP_WRITE)
  5251. btrfs_dev_stat_inc_and_print(dev,
  5252. BTRFS_DEV_STAT_WRITE_ERRS);
  5253. else
  5254. btrfs_dev_stat_inc_and_print(dev,
  5255. BTRFS_DEV_STAT_READ_ERRS);
  5256. if (bio->bi_opf & REQ_PREFLUSH)
  5257. btrfs_dev_stat_inc_and_print(dev,
  5258. BTRFS_DEV_STAT_FLUSH_ERRS);
  5259. }
  5260. }
  5261. }
  5262. if (bio == bbio->orig_bio)
  5263. is_orig_bio = 1;
  5264. btrfs_bio_counter_dec(bbio->fs_info);
  5265. if (atomic_dec_and_test(&bbio->stripes_pending)) {
  5266. if (!is_orig_bio) {
  5267. bio_put(bio);
  5268. bio = bbio->orig_bio;
  5269. }
  5270. btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
  5271. /* only send an error to the higher layers if it is
  5272. * beyond the tolerance of the btrfs bio
  5273. */
  5274. if (atomic_read(&bbio->error) > bbio->max_errors) {
  5275. bio->bi_status = BLK_STS_IOERR;
  5276. } else {
  5277. /*
  5278. * this bio is actually up to date, we didn't
  5279. * go over the max number of errors
  5280. */
  5281. bio->bi_status = BLK_STS_OK;
  5282. }
  5283. btrfs_end_bbio(bbio, bio);
  5284. } else if (!is_orig_bio) {
  5285. bio_put(bio);
  5286. }
  5287. }
  5288. /*
  5289. * see run_scheduled_bios for a description of why bios are collected for
  5290. * async submit.
  5291. *
  5292. * This will add one bio to the pending list for a device and make sure
  5293. * the work struct is scheduled.
  5294. */
  5295. static noinline void btrfs_schedule_bio(struct btrfs_device *device,
  5296. struct bio *bio)
  5297. {
  5298. struct btrfs_fs_info *fs_info = device->fs_info;
  5299. int should_queue = 1;
  5300. struct btrfs_pending_bios *pending_bios;
  5301. if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state) ||
  5302. !device->bdev) {
  5303. bio_io_error(bio);
  5304. return;
  5305. }
  5306. /* don't bother with additional async steps for reads, right now */
  5307. if (bio_op(bio) == REQ_OP_READ) {
  5308. btrfsic_submit_bio(bio);
  5309. return;
  5310. }
  5311. WARN_ON(bio->bi_next);
  5312. bio->bi_next = NULL;
  5313. spin_lock(&device->io_lock);
  5314. if (op_is_sync(bio->bi_opf))
  5315. pending_bios = &device->pending_sync_bios;
  5316. else
  5317. pending_bios = &device->pending_bios;
  5318. if (pending_bios->tail)
  5319. pending_bios->tail->bi_next = bio;
  5320. pending_bios->tail = bio;
  5321. if (!pending_bios->head)
  5322. pending_bios->head = bio;
  5323. if (device->running_pending)
  5324. should_queue = 0;
  5325. spin_unlock(&device->io_lock);
  5326. if (should_queue)
  5327. btrfs_queue_work(fs_info->submit_workers, &device->work);
  5328. }
  5329. static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
  5330. u64 physical, int dev_nr, int async)
  5331. {
  5332. struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
  5333. struct btrfs_fs_info *fs_info = bbio->fs_info;
  5334. bio->bi_private = bbio;
  5335. btrfs_io_bio(bio)->stripe_index = dev_nr;
  5336. bio->bi_end_io = btrfs_end_bio;
  5337. bio->bi_iter.bi_sector = physical >> 9;
  5338. #ifdef DEBUG
  5339. {
  5340. struct rcu_string *name;
  5341. rcu_read_lock();
  5342. name = rcu_dereference(dev->name);
  5343. btrfs_debug(fs_info,
  5344. "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
  5345. bio_op(bio), bio->bi_opf,
  5346. (u64)bio->bi_iter.bi_sector,
  5347. (u_long)dev->bdev->bd_dev, name->str, dev->devid,
  5348. bio->bi_iter.bi_size);
  5349. rcu_read_unlock();
  5350. }
  5351. #endif
  5352. bio_set_dev(bio, dev->bdev);
  5353. btrfs_bio_counter_inc_noblocked(fs_info);
  5354. if (async)
  5355. btrfs_schedule_bio(dev, bio);
  5356. else
  5357. btrfsic_submit_bio(bio);
  5358. }
  5359. static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
  5360. {
  5361. atomic_inc(&bbio->error);
  5362. if (atomic_dec_and_test(&bbio->stripes_pending)) {
  5363. /* Should be the original bio. */
  5364. WARN_ON(bio != bbio->orig_bio);
  5365. btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
  5366. bio->bi_iter.bi_sector = logical >> 9;
  5367. if (atomic_read(&bbio->error) > bbio->max_errors)
  5368. bio->bi_status = BLK_STS_IOERR;
  5369. else
  5370. bio->bi_status = BLK_STS_OK;
  5371. btrfs_end_bbio(bbio, bio);
  5372. }
  5373. }
  5374. blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
  5375. int mirror_num, int async_submit)
  5376. {
  5377. struct btrfs_device *dev;
  5378. struct bio *first_bio = bio;
  5379. u64 logical = (u64)bio->bi_iter.bi_sector << 9;
  5380. u64 length = 0;
  5381. u64 map_length;
  5382. int ret;
  5383. int dev_nr;
  5384. int total_devs;
  5385. struct btrfs_bio *bbio = NULL;
  5386. length = bio->bi_iter.bi_size;
  5387. map_length = length;
  5388. btrfs_bio_counter_inc_blocked(fs_info);
  5389. ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
  5390. &map_length, &bbio, mirror_num, 1);
  5391. if (ret) {
  5392. btrfs_bio_counter_dec(fs_info);
  5393. return errno_to_blk_status(ret);
  5394. }
  5395. total_devs = bbio->num_stripes;
  5396. bbio->orig_bio = first_bio;
  5397. bbio->private = first_bio->bi_private;
  5398. bbio->end_io = first_bio->bi_end_io;
  5399. bbio->fs_info = fs_info;
  5400. atomic_set(&bbio->stripes_pending, bbio->num_stripes);
  5401. if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
  5402. ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
  5403. /* In this case, map_length has been set to the length of
  5404. a single stripe; not the whole write */
  5405. if (bio_op(bio) == REQ_OP_WRITE) {
  5406. ret = raid56_parity_write(fs_info, bio, bbio,
  5407. map_length);
  5408. } else {
  5409. ret = raid56_parity_recover(fs_info, bio, bbio,
  5410. map_length, mirror_num, 1);
  5411. }
  5412. btrfs_bio_counter_dec(fs_info);
  5413. return errno_to_blk_status(ret);
  5414. }
  5415. if (map_length < length) {
  5416. btrfs_crit(fs_info,
  5417. "mapping failed logical %llu bio len %llu len %llu",
  5418. logical, length, map_length);
  5419. BUG();
  5420. }
  5421. for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
  5422. dev = bbio->stripes[dev_nr].dev;
  5423. if (!dev || !dev->bdev ||
  5424. (bio_op(first_bio) == REQ_OP_WRITE &&
  5425. !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
  5426. bbio_error(bbio, first_bio, logical);
  5427. continue;
  5428. }
  5429. if (dev_nr < total_devs - 1)
  5430. bio = btrfs_bio_clone(first_bio);
  5431. else
  5432. bio = first_bio;
  5433. submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
  5434. dev_nr, async_submit);
  5435. }
  5436. btrfs_bio_counter_dec(fs_info);
  5437. return BLK_STS_OK;
  5438. }
  5439. struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
  5440. u8 *uuid, u8 *fsid)
  5441. {
  5442. struct btrfs_device *device;
  5443. struct btrfs_fs_devices *cur_devices;
  5444. cur_devices = fs_info->fs_devices;
  5445. while (cur_devices) {
  5446. if (!fsid ||
  5447. !memcmp(cur_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
  5448. device = find_device(cur_devices, devid, uuid);
  5449. if (device)
  5450. return device;
  5451. }
  5452. cur_devices = cur_devices->seed;
  5453. }
  5454. return NULL;
  5455. }
  5456. static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
  5457. u64 devid, u8 *dev_uuid)
  5458. {
  5459. struct btrfs_device *device;
  5460. device = btrfs_alloc_device(NULL, &devid, dev_uuid);
  5461. if (IS_ERR(device))
  5462. return device;
  5463. list_add(&device->dev_list, &fs_devices->devices);
  5464. device->fs_devices = fs_devices;
  5465. fs_devices->num_devices++;
  5466. set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
  5467. fs_devices->missing_devices++;
  5468. return device;
  5469. }
  5470. /**
  5471. * btrfs_alloc_device - allocate struct btrfs_device
  5472. * @fs_info: used only for generating a new devid, can be NULL if
  5473. * devid is provided (i.e. @devid != NULL).
  5474. * @devid: a pointer to devid for this device. If NULL a new devid
  5475. * is generated.
  5476. * @uuid: a pointer to UUID for this device. If NULL a new UUID
  5477. * is generated.
  5478. *
  5479. * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
  5480. * on error. Returned struct is not linked onto any lists and must be
  5481. * destroyed with btrfs_free_device.
  5482. */
  5483. struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
  5484. const u64 *devid,
  5485. const u8 *uuid)
  5486. {
  5487. struct btrfs_device *dev;
  5488. u64 tmp;
  5489. if (WARN_ON(!devid && !fs_info))
  5490. return ERR_PTR(-EINVAL);
  5491. dev = __alloc_device();
  5492. if (IS_ERR(dev))
  5493. return dev;
  5494. if (devid)
  5495. tmp = *devid;
  5496. else {
  5497. int ret;
  5498. ret = find_next_devid(fs_info, &tmp);
  5499. if (ret) {
  5500. btrfs_free_device(dev);
  5501. return ERR_PTR(ret);
  5502. }
  5503. }
  5504. dev->devid = tmp;
  5505. if (uuid)
  5506. memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
  5507. else
  5508. generate_random_uuid(dev->uuid);
  5509. btrfs_init_work(&dev->work, btrfs_submit_helper,
  5510. pending_bios_fn, NULL, NULL);
  5511. return dev;
  5512. }
  5513. /* Return -EIO if any error, otherwise return 0. */
  5514. static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
  5515. struct extent_buffer *leaf,
  5516. struct btrfs_chunk *chunk, u64 logical)
  5517. {
  5518. u64 length;
  5519. u64 stripe_len;
  5520. u16 num_stripes;
  5521. u16 sub_stripes;
  5522. u64 type;
  5523. length = btrfs_chunk_length(leaf, chunk);
  5524. stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
  5525. num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
  5526. sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
  5527. type = btrfs_chunk_type(leaf, chunk);
  5528. if (!num_stripes) {
  5529. btrfs_err(fs_info, "invalid chunk num_stripes: %u",
  5530. num_stripes);
  5531. return -EIO;
  5532. }
  5533. if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
  5534. btrfs_err(fs_info, "invalid chunk logical %llu", logical);
  5535. return -EIO;
  5536. }
  5537. if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
  5538. btrfs_err(fs_info, "invalid chunk sectorsize %u",
  5539. btrfs_chunk_sector_size(leaf, chunk));
  5540. return -EIO;
  5541. }
  5542. if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
  5543. btrfs_err(fs_info, "invalid chunk length %llu", length);
  5544. return -EIO;
  5545. }
  5546. if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
  5547. btrfs_err(fs_info, "invalid chunk stripe length: %llu",
  5548. stripe_len);
  5549. return -EIO;
  5550. }
  5551. if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
  5552. type) {
  5553. btrfs_err(fs_info, "unrecognized chunk type: %llu",
  5554. ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
  5555. BTRFS_BLOCK_GROUP_PROFILE_MASK) &
  5556. btrfs_chunk_type(leaf, chunk));
  5557. return -EIO;
  5558. }
  5559. if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
  5560. (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
  5561. (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
  5562. (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
  5563. (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
  5564. ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
  5565. num_stripes != 1)) {
  5566. btrfs_err(fs_info,
  5567. "invalid num_stripes:sub_stripes %u:%u for profile %llu",
  5568. num_stripes, sub_stripes,
  5569. type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
  5570. return -EIO;
  5571. }
  5572. return 0;
  5573. }
  5574. static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
  5575. u64 devid, u8 *uuid, bool error)
  5576. {
  5577. if (error)
  5578. btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
  5579. devid, uuid);
  5580. else
  5581. btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
  5582. devid, uuid);
  5583. }
  5584. static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
  5585. struct extent_buffer *leaf,
  5586. struct btrfs_chunk *chunk)
  5587. {
  5588. struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
  5589. struct map_lookup *map;
  5590. struct extent_map *em;
  5591. u64 logical;
  5592. u64 length;
  5593. u64 devid;
  5594. u8 uuid[BTRFS_UUID_SIZE];
  5595. int num_stripes;
  5596. int ret;
  5597. int i;
  5598. logical = key->offset;
  5599. length = btrfs_chunk_length(leaf, chunk);
  5600. num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
  5601. ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
  5602. if (ret)
  5603. return ret;
  5604. read_lock(&map_tree->map_tree.lock);
  5605. em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
  5606. read_unlock(&map_tree->map_tree.lock);
  5607. /* already mapped? */
  5608. if (em && em->start <= logical && em->start + em->len > logical) {
  5609. free_extent_map(em);
  5610. return 0;
  5611. } else if (em) {
  5612. free_extent_map(em);
  5613. }
  5614. em = alloc_extent_map();
  5615. if (!em)
  5616. return -ENOMEM;
  5617. map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
  5618. if (!map) {
  5619. free_extent_map(em);
  5620. return -ENOMEM;
  5621. }
  5622. set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
  5623. em->map_lookup = map;
  5624. em->start = logical;
  5625. em->len = length;
  5626. em->orig_start = 0;
  5627. em->block_start = 0;
  5628. em->block_len = em->len;
  5629. map->num_stripes = num_stripes;
  5630. map->io_width = btrfs_chunk_io_width(leaf, chunk);
  5631. map->io_align = btrfs_chunk_io_align(leaf, chunk);
  5632. map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
  5633. map->type = btrfs_chunk_type(leaf, chunk);
  5634. map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
  5635. for (i = 0; i < num_stripes; i++) {
  5636. map->stripes[i].physical =
  5637. btrfs_stripe_offset_nr(leaf, chunk, i);
  5638. devid = btrfs_stripe_devid_nr(leaf, chunk, i);
  5639. read_extent_buffer(leaf, uuid, (unsigned long)
  5640. btrfs_stripe_dev_uuid_nr(chunk, i),
  5641. BTRFS_UUID_SIZE);
  5642. map->stripes[i].dev = btrfs_find_device(fs_info, devid,
  5643. uuid, NULL);
  5644. if (!map->stripes[i].dev &&
  5645. !btrfs_test_opt(fs_info, DEGRADED)) {
  5646. free_extent_map(em);
  5647. btrfs_report_missing_device(fs_info, devid, uuid, true);
  5648. return -ENOENT;
  5649. }
  5650. if (!map->stripes[i].dev) {
  5651. map->stripes[i].dev =
  5652. add_missing_dev(fs_info->fs_devices, devid,
  5653. uuid);
  5654. if (IS_ERR(map->stripes[i].dev)) {
  5655. free_extent_map(em);
  5656. btrfs_err(fs_info,
  5657. "failed to init missing dev %llu: %ld",
  5658. devid, PTR_ERR(map->stripes[i].dev));
  5659. return PTR_ERR(map->stripes[i].dev);
  5660. }
  5661. btrfs_report_missing_device(fs_info, devid, uuid, false);
  5662. }
  5663. set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
  5664. &(map->stripes[i].dev->dev_state));
  5665. }
  5666. write_lock(&map_tree->map_tree.lock);
  5667. ret = add_extent_mapping(&map_tree->map_tree, em, 0);
  5668. write_unlock(&map_tree->map_tree.lock);
  5669. BUG_ON(ret); /* Tree corruption */
  5670. free_extent_map(em);
  5671. return 0;
  5672. }
  5673. static void fill_device_from_item(struct extent_buffer *leaf,
  5674. struct btrfs_dev_item *dev_item,
  5675. struct btrfs_device *device)
  5676. {
  5677. unsigned long ptr;
  5678. device->devid = btrfs_device_id(leaf, dev_item);
  5679. device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
  5680. device->total_bytes = device->disk_total_bytes;
  5681. device->commit_total_bytes = device->disk_total_bytes;
  5682. device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
  5683. device->commit_bytes_used = device->bytes_used;
  5684. device->type = btrfs_device_type(leaf, dev_item);
  5685. device->io_align = btrfs_device_io_align(leaf, dev_item);
  5686. device->io_width = btrfs_device_io_width(leaf, dev_item);
  5687. device->sector_size = btrfs_device_sector_size(leaf, dev_item);
  5688. WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
  5689. clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
  5690. ptr = btrfs_device_uuid(dev_item);
  5691. read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
  5692. }
  5693. static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
  5694. u8 *fsid)
  5695. {
  5696. struct btrfs_fs_devices *fs_devices;
  5697. int ret;
  5698. lockdep_assert_held(&uuid_mutex);
  5699. ASSERT(fsid);
  5700. fs_devices = fs_info->fs_devices->seed;
  5701. while (fs_devices) {
  5702. if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
  5703. return fs_devices;
  5704. fs_devices = fs_devices->seed;
  5705. }
  5706. fs_devices = find_fsid(fsid);
  5707. if (!fs_devices) {
  5708. if (!btrfs_test_opt(fs_info, DEGRADED))
  5709. return ERR_PTR(-ENOENT);
  5710. fs_devices = alloc_fs_devices(fsid);
  5711. if (IS_ERR(fs_devices))
  5712. return fs_devices;
  5713. fs_devices->seeding = 1;
  5714. fs_devices->opened = 1;
  5715. return fs_devices;
  5716. }
  5717. fs_devices = clone_fs_devices(fs_devices);
  5718. if (IS_ERR(fs_devices))
  5719. return fs_devices;
  5720. ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
  5721. if (ret) {
  5722. free_fs_devices(fs_devices);
  5723. fs_devices = ERR_PTR(ret);
  5724. goto out;
  5725. }
  5726. if (!fs_devices->seeding) {
  5727. close_fs_devices(fs_devices);
  5728. free_fs_devices(fs_devices);
  5729. fs_devices = ERR_PTR(-EINVAL);
  5730. goto out;
  5731. }
  5732. fs_devices->seed = fs_info->fs_devices->seed;
  5733. fs_info->fs_devices->seed = fs_devices;
  5734. out:
  5735. return fs_devices;
  5736. }
  5737. static int read_one_dev(struct btrfs_fs_info *fs_info,
  5738. struct extent_buffer *leaf,
  5739. struct btrfs_dev_item *dev_item)
  5740. {
  5741. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  5742. struct btrfs_device *device;
  5743. u64 devid;
  5744. int ret;
  5745. u8 fs_uuid[BTRFS_FSID_SIZE];
  5746. u8 dev_uuid[BTRFS_UUID_SIZE];
  5747. devid = btrfs_device_id(leaf, dev_item);
  5748. read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
  5749. BTRFS_UUID_SIZE);
  5750. read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
  5751. BTRFS_FSID_SIZE);
  5752. if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
  5753. fs_devices = open_seed_devices(fs_info, fs_uuid);
  5754. if (IS_ERR(fs_devices))
  5755. return PTR_ERR(fs_devices);
  5756. }
  5757. device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
  5758. if (!device) {
  5759. if (!btrfs_test_opt(fs_info, DEGRADED)) {
  5760. btrfs_report_missing_device(fs_info, devid,
  5761. dev_uuid, true);
  5762. return -ENOENT;
  5763. }
  5764. device = add_missing_dev(fs_devices, devid, dev_uuid);
  5765. if (IS_ERR(device)) {
  5766. btrfs_err(fs_info,
  5767. "failed to add missing dev %llu: %ld",
  5768. devid, PTR_ERR(device));
  5769. return PTR_ERR(device);
  5770. }
  5771. btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
  5772. } else {
  5773. if (!device->bdev) {
  5774. if (!btrfs_test_opt(fs_info, DEGRADED)) {
  5775. btrfs_report_missing_device(fs_info,
  5776. devid, dev_uuid, true);
  5777. return -ENOENT;
  5778. }
  5779. btrfs_report_missing_device(fs_info, devid,
  5780. dev_uuid, false);
  5781. }
  5782. if (!device->bdev &&
  5783. !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
  5784. /*
  5785. * this happens when a device that was properly setup
  5786. * in the device info lists suddenly goes bad.
  5787. * device->bdev is NULL, and so we have to set
  5788. * device->missing to one here
  5789. */
  5790. device->fs_devices->missing_devices++;
  5791. set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
  5792. }
  5793. /* Move the device to its own fs_devices */
  5794. if (device->fs_devices != fs_devices) {
  5795. ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
  5796. &device->dev_state));
  5797. list_move(&device->dev_list, &fs_devices->devices);
  5798. device->fs_devices->num_devices--;
  5799. fs_devices->num_devices++;
  5800. device->fs_devices->missing_devices--;
  5801. fs_devices->missing_devices++;
  5802. device->fs_devices = fs_devices;
  5803. }
  5804. }
  5805. if (device->fs_devices != fs_info->fs_devices) {
  5806. BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
  5807. if (device->generation !=
  5808. btrfs_device_generation(leaf, dev_item))
  5809. return -EINVAL;
  5810. }
  5811. fill_device_from_item(leaf, dev_item, device);
  5812. set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
  5813. if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
  5814. !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
  5815. device->fs_devices->total_rw_bytes += device->total_bytes;
  5816. atomic64_add(device->total_bytes - device->bytes_used,
  5817. &fs_info->free_chunk_space);
  5818. }
  5819. ret = 0;
  5820. return ret;
  5821. }
  5822. int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
  5823. {
  5824. struct btrfs_root *root = fs_info->tree_root;
  5825. struct btrfs_super_block *super_copy = fs_info->super_copy;
  5826. struct extent_buffer *sb;
  5827. struct btrfs_disk_key *disk_key;
  5828. struct btrfs_chunk *chunk;
  5829. u8 *array_ptr;
  5830. unsigned long sb_array_offset;
  5831. int ret = 0;
  5832. u32 num_stripes;
  5833. u32 array_size;
  5834. u32 len = 0;
  5835. u32 cur_offset;
  5836. u64 type;
  5837. struct btrfs_key key;
  5838. ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
  5839. /*
  5840. * This will create extent buffer of nodesize, superblock size is
  5841. * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
  5842. * overallocate but we can keep it as-is, only the first page is used.
  5843. */
  5844. sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
  5845. if (IS_ERR(sb))
  5846. return PTR_ERR(sb);
  5847. set_extent_buffer_uptodate(sb);
  5848. btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
  5849. /*
  5850. * The sb extent buffer is artificial and just used to read the system array.
  5851. * set_extent_buffer_uptodate() call does not properly mark all it's
  5852. * pages up-to-date when the page is larger: extent does not cover the
  5853. * whole page and consequently check_page_uptodate does not find all
  5854. * the page's extents up-to-date (the hole beyond sb),
  5855. * write_extent_buffer then triggers a WARN_ON.
  5856. *
  5857. * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
  5858. * but sb spans only this function. Add an explicit SetPageUptodate call
  5859. * to silence the warning eg. on PowerPC 64.
  5860. */
  5861. if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
  5862. SetPageUptodate(sb->pages[0]);
  5863. write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
  5864. array_size = btrfs_super_sys_array_size(super_copy);
  5865. array_ptr = super_copy->sys_chunk_array;
  5866. sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
  5867. cur_offset = 0;
  5868. while (cur_offset < array_size) {
  5869. disk_key = (struct btrfs_disk_key *)array_ptr;
  5870. len = sizeof(*disk_key);
  5871. if (cur_offset + len > array_size)
  5872. goto out_short_read;
  5873. btrfs_disk_key_to_cpu(&key, disk_key);
  5874. array_ptr += len;
  5875. sb_array_offset += len;
  5876. cur_offset += len;
  5877. if (key.type == BTRFS_CHUNK_ITEM_KEY) {
  5878. chunk = (struct btrfs_chunk *)sb_array_offset;
  5879. /*
  5880. * At least one btrfs_chunk with one stripe must be
  5881. * present, exact stripe count check comes afterwards
  5882. */
  5883. len = btrfs_chunk_item_size(1);
  5884. if (cur_offset + len > array_size)
  5885. goto out_short_read;
  5886. num_stripes = btrfs_chunk_num_stripes(sb, chunk);
  5887. if (!num_stripes) {
  5888. btrfs_err(fs_info,
  5889. "invalid number of stripes %u in sys_array at offset %u",
  5890. num_stripes, cur_offset);
  5891. ret = -EIO;
  5892. break;
  5893. }
  5894. type = btrfs_chunk_type(sb, chunk);
  5895. if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
  5896. btrfs_err(fs_info,
  5897. "invalid chunk type %llu in sys_array at offset %u",
  5898. type, cur_offset);
  5899. ret = -EIO;
  5900. break;
  5901. }
  5902. len = btrfs_chunk_item_size(num_stripes);
  5903. if (cur_offset + len > array_size)
  5904. goto out_short_read;
  5905. ret = read_one_chunk(fs_info, &key, sb, chunk);
  5906. if (ret)
  5907. break;
  5908. } else {
  5909. btrfs_err(fs_info,
  5910. "unexpected item type %u in sys_array at offset %u",
  5911. (u32)key.type, cur_offset);
  5912. ret = -EIO;
  5913. break;
  5914. }
  5915. array_ptr += len;
  5916. sb_array_offset += len;
  5917. cur_offset += len;
  5918. }
  5919. clear_extent_buffer_uptodate(sb);
  5920. free_extent_buffer_stale(sb);
  5921. return ret;
  5922. out_short_read:
  5923. btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
  5924. len, cur_offset);
  5925. clear_extent_buffer_uptodate(sb);
  5926. free_extent_buffer_stale(sb);
  5927. return -EIO;
  5928. }
  5929. /*
  5930. * Check if all chunks in the fs are OK for read-write degraded mount
  5931. *
  5932. * If the @failing_dev is specified, it's accounted as missing.
  5933. *
  5934. * Return true if all chunks meet the minimal RW mount requirements.
  5935. * Return false if any chunk doesn't meet the minimal RW mount requirements.
  5936. */
  5937. bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
  5938. struct btrfs_device *failing_dev)
  5939. {
  5940. struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
  5941. struct extent_map *em;
  5942. u64 next_start = 0;
  5943. bool ret = true;
  5944. read_lock(&map_tree->map_tree.lock);
  5945. em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
  5946. read_unlock(&map_tree->map_tree.lock);
  5947. /* No chunk at all? Return false anyway */
  5948. if (!em) {
  5949. ret = false;
  5950. goto out;
  5951. }
  5952. while (em) {
  5953. struct map_lookup *map;
  5954. int missing = 0;
  5955. int max_tolerated;
  5956. int i;
  5957. map = em->map_lookup;
  5958. max_tolerated =
  5959. btrfs_get_num_tolerated_disk_barrier_failures(
  5960. map->type);
  5961. for (i = 0; i < map->num_stripes; i++) {
  5962. struct btrfs_device *dev = map->stripes[i].dev;
  5963. if (!dev || !dev->bdev ||
  5964. test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
  5965. dev->last_flush_error)
  5966. missing++;
  5967. else if (failing_dev && failing_dev == dev)
  5968. missing++;
  5969. }
  5970. if (missing > max_tolerated) {
  5971. if (!failing_dev)
  5972. btrfs_warn(fs_info,
  5973. "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
  5974. em->start, missing, max_tolerated);
  5975. free_extent_map(em);
  5976. ret = false;
  5977. goto out;
  5978. }
  5979. next_start = extent_map_end(em);
  5980. free_extent_map(em);
  5981. read_lock(&map_tree->map_tree.lock);
  5982. em = lookup_extent_mapping(&map_tree->map_tree, next_start,
  5983. (u64)(-1) - next_start);
  5984. read_unlock(&map_tree->map_tree.lock);
  5985. }
  5986. out:
  5987. return ret;
  5988. }
  5989. int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
  5990. {
  5991. struct btrfs_root *root = fs_info->chunk_root;
  5992. struct btrfs_path *path;
  5993. struct extent_buffer *leaf;
  5994. struct btrfs_key key;
  5995. struct btrfs_key found_key;
  5996. int ret;
  5997. int slot;
  5998. u64 total_dev = 0;
  5999. path = btrfs_alloc_path();
  6000. if (!path)
  6001. return -ENOMEM;
  6002. /*
  6003. * uuid_mutex is needed only if we are mounting a sprout FS
  6004. * otherwise we don't need it.
  6005. */
  6006. mutex_lock(&uuid_mutex);
  6007. mutex_lock(&fs_info->chunk_mutex);
  6008. /*
  6009. * Read all device items, and then all the chunk items. All
  6010. * device items are found before any chunk item (their object id
  6011. * is smaller than the lowest possible object id for a chunk
  6012. * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
  6013. */
  6014. key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
  6015. key.offset = 0;
  6016. key.type = 0;
  6017. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  6018. if (ret < 0)
  6019. goto error;
  6020. while (1) {
  6021. leaf = path->nodes[0];
  6022. slot = path->slots[0];
  6023. if (slot >= btrfs_header_nritems(leaf)) {
  6024. ret = btrfs_next_leaf(root, path);
  6025. if (ret == 0)
  6026. continue;
  6027. if (ret < 0)
  6028. goto error;
  6029. break;
  6030. }
  6031. btrfs_item_key_to_cpu(leaf, &found_key, slot);
  6032. if (found_key.type == BTRFS_DEV_ITEM_KEY) {
  6033. struct btrfs_dev_item *dev_item;
  6034. dev_item = btrfs_item_ptr(leaf, slot,
  6035. struct btrfs_dev_item);
  6036. ret = read_one_dev(fs_info, leaf, dev_item);
  6037. if (ret)
  6038. goto error;
  6039. total_dev++;
  6040. } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
  6041. struct btrfs_chunk *chunk;
  6042. chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
  6043. ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
  6044. if (ret)
  6045. goto error;
  6046. }
  6047. path->slots[0]++;
  6048. }
  6049. /*
  6050. * After loading chunk tree, we've got all device information,
  6051. * do another round of validation checks.
  6052. */
  6053. if (total_dev != fs_info->fs_devices->total_devices) {
  6054. btrfs_err(fs_info,
  6055. "super_num_devices %llu mismatch with num_devices %llu found here",
  6056. btrfs_super_num_devices(fs_info->super_copy),
  6057. total_dev);
  6058. ret = -EINVAL;
  6059. goto error;
  6060. }
  6061. if (btrfs_super_total_bytes(fs_info->super_copy) <
  6062. fs_info->fs_devices->total_rw_bytes) {
  6063. btrfs_err(fs_info,
  6064. "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
  6065. btrfs_super_total_bytes(fs_info->super_copy),
  6066. fs_info->fs_devices->total_rw_bytes);
  6067. ret = -EINVAL;
  6068. goto error;
  6069. }
  6070. ret = 0;
  6071. error:
  6072. mutex_unlock(&fs_info->chunk_mutex);
  6073. mutex_unlock(&uuid_mutex);
  6074. btrfs_free_path(path);
  6075. return ret;
  6076. }
  6077. void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
  6078. {
  6079. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  6080. struct btrfs_device *device;
  6081. while (fs_devices) {
  6082. mutex_lock(&fs_devices->device_list_mutex);
  6083. list_for_each_entry(device, &fs_devices->devices, dev_list)
  6084. device->fs_info = fs_info;
  6085. mutex_unlock(&fs_devices->device_list_mutex);
  6086. fs_devices = fs_devices->seed;
  6087. }
  6088. }
  6089. static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
  6090. {
  6091. int i;
  6092. for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
  6093. btrfs_dev_stat_reset(dev, i);
  6094. }
  6095. int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
  6096. {
  6097. struct btrfs_key key;
  6098. struct btrfs_key found_key;
  6099. struct btrfs_root *dev_root = fs_info->dev_root;
  6100. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  6101. struct extent_buffer *eb;
  6102. int slot;
  6103. int ret = 0;
  6104. struct btrfs_device *device;
  6105. struct btrfs_path *path = NULL;
  6106. int i;
  6107. path = btrfs_alloc_path();
  6108. if (!path) {
  6109. ret = -ENOMEM;
  6110. goto out;
  6111. }
  6112. mutex_lock(&fs_devices->device_list_mutex);
  6113. list_for_each_entry(device, &fs_devices->devices, dev_list) {
  6114. int item_size;
  6115. struct btrfs_dev_stats_item *ptr;
  6116. key.objectid = BTRFS_DEV_STATS_OBJECTID;
  6117. key.type = BTRFS_PERSISTENT_ITEM_KEY;
  6118. key.offset = device->devid;
  6119. ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
  6120. if (ret) {
  6121. __btrfs_reset_dev_stats(device);
  6122. device->dev_stats_valid = 1;
  6123. btrfs_release_path(path);
  6124. continue;
  6125. }
  6126. slot = path->slots[0];
  6127. eb = path->nodes[0];
  6128. btrfs_item_key_to_cpu(eb, &found_key, slot);
  6129. item_size = btrfs_item_size_nr(eb, slot);
  6130. ptr = btrfs_item_ptr(eb, slot,
  6131. struct btrfs_dev_stats_item);
  6132. for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
  6133. if (item_size >= (1 + i) * sizeof(__le64))
  6134. btrfs_dev_stat_set(device, i,
  6135. btrfs_dev_stats_value(eb, ptr, i));
  6136. else
  6137. btrfs_dev_stat_reset(device, i);
  6138. }
  6139. device->dev_stats_valid = 1;
  6140. btrfs_dev_stat_print_on_load(device);
  6141. btrfs_release_path(path);
  6142. }
  6143. mutex_unlock(&fs_devices->device_list_mutex);
  6144. out:
  6145. btrfs_free_path(path);
  6146. return ret < 0 ? ret : 0;
  6147. }
  6148. static int update_dev_stat_item(struct btrfs_trans_handle *trans,
  6149. struct btrfs_fs_info *fs_info,
  6150. struct btrfs_device *device)
  6151. {
  6152. struct btrfs_root *dev_root = fs_info->dev_root;
  6153. struct btrfs_path *path;
  6154. struct btrfs_key key;
  6155. struct extent_buffer *eb;
  6156. struct btrfs_dev_stats_item *ptr;
  6157. int ret;
  6158. int i;
  6159. key.objectid = BTRFS_DEV_STATS_OBJECTID;
  6160. key.type = BTRFS_PERSISTENT_ITEM_KEY;
  6161. key.offset = device->devid;
  6162. path = btrfs_alloc_path();
  6163. if (!path)
  6164. return -ENOMEM;
  6165. ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
  6166. if (ret < 0) {
  6167. btrfs_warn_in_rcu(fs_info,
  6168. "error %d while searching for dev_stats item for device %s",
  6169. ret, rcu_str_deref(device->name));
  6170. goto out;
  6171. }
  6172. if (ret == 0 &&
  6173. btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
  6174. /* need to delete old one and insert a new one */
  6175. ret = btrfs_del_item(trans, dev_root, path);
  6176. if (ret != 0) {
  6177. btrfs_warn_in_rcu(fs_info,
  6178. "delete too small dev_stats item for device %s failed %d",
  6179. rcu_str_deref(device->name), ret);
  6180. goto out;
  6181. }
  6182. ret = 1;
  6183. }
  6184. if (ret == 1) {
  6185. /* need to insert a new item */
  6186. btrfs_release_path(path);
  6187. ret = btrfs_insert_empty_item(trans, dev_root, path,
  6188. &key, sizeof(*ptr));
  6189. if (ret < 0) {
  6190. btrfs_warn_in_rcu(fs_info,
  6191. "insert dev_stats item for device %s failed %d",
  6192. rcu_str_deref(device->name), ret);
  6193. goto out;
  6194. }
  6195. }
  6196. eb = path->nodes[0];
  6197. ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
  6198. for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
  6199. btrfs_set_dev_stats_value(eb, ptr, i,
  6200. btrfs_dev_stat_read(device, i));
  6201. btrfs_mark_buffer_dirty(eb);
  6202. out:
  6203. btrfs_free_path(path);
  6204. return ret;
  6205. }
  6206. /*
  6207. * called from commit_transaction. Writes all changed device stats to disk.
  6208. */
  6209. int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
  6210. struct btrfs_fs_info *fs_info)
  6211. {
  6212. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  6213. struct btrfs_device *device;
  6214. int stats_cnt;
  6215. int ret = 0;
  6216. mutex_lock(&fs_devices->device_list_mutex);
  6217. list_for_each_entry(device, &fs_devices->devices, dev_list) {
  6218. stats_cnt = atomic_read(&device->dev_stats_ccnt);
  6219. if (!device->dev_stats_valid || stats_cnt == 0)
  6220. continue;
  6221. /*
  6222. * There is a LOAD-LOAD control dependency between the value of
  6223. * dev_stats_ccnt and updating the on-disk values which requires
  6224. * reading the in-memory counters. Such control dependencies
  6225. * require explicit read memory barriers.
  6226. *
  6227. * This memory barriers pairs with smp_mb__before_atomic in
  6228. * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
  6229. * barrier implied by atomic_xchg in
  6230. * btrfs_dev_stats_read_and_reset
  6231. */
  6232. smp_rmb();
  6233. ret = update_dev_stat_item(trans, fs_info, device);
  6234. if (!ret)
  6235. atomic_sub(stats_cnt, &device->dev_stats_ccnt);
  6236. }
  6237. mutex_unlock(&fs_devices->device_list_mutex);
  6238. return ret;
  6239. }
  6240. void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
  6241. {
  6242. btrfs_dev_stat_inc(dev, index);
  6243. btrfs_dev_stat_print_on_error(dev);
  6244. }
  6245. static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
  6246. {
  6247. if (!dev->dev_stats_valid)
  6248. return;
  6249. btrfs_err_rl_in_rcu(dev->fs_info,
  6250. "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
  6251. rcu_str_deref(dev->name),
  6252. btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
  6253. btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
  6254. btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
  6255. btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
  6256. btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
  6257. }
  6258. static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
  6259. {
  6260. int i;
  6261. for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
  6262. if (btrfs_dev_stat_read(dev, i) != 0)
  6263. break;
  6264. if (i == BTRFS_DEV_STAT_VALUES_MAX)
  6265. return; /* all values == 0, suppress message */
  6266. btrfs_info_in_rcu(dev->fs_info,
  6267. "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
  6268. rcu_str_deref(dev->name),
  6269. btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
  6270. btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
  6271. btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
  6272. btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
  6273. btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
  6274. }
  6275. int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
  6276. struct btrfs_ioctl_get_dev_stats *stats)
  6277. {
  6278. struct btrfs_device *dev;
  6279. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  6280. int i;
  6281. mutex_lock(&fs_devices->device_list_mutex);
  6282. dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
  6283. mutex_unlock(&fs_devices->device_list_mutex);
  6284. if (!dev) {
  6285. btrfs_warn(fs_info, "get dev_stats failed, device not found");
  6286. return -ENODEV;
  6287. } else if (!dev->dev_stats_valid) {
  6288. btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
  6289. return -ENODEV;
  6290. } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
  6291. for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
  6292. if (stats->nr_items > i)
  6293. stats->values[i] =
  6294. btrfs_dev_stat_read_and_reset(dev, i);
  6295. else
  6296. btrfs_dev_stat_reset(dev, i);
  6297. }
  6298. } else {
  6299. for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
  6300. if (stats->nr_items > i)
  6301. stats->values[i] = btrfs_dev_stat_read(dev, i);
  6302. }
  6303. if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
  6304. stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
  6305. return 0;
  6306. }
  6307. void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
  6308. {
  6309. struct buffer_head *bh;
  6310. struct btrfs_super_block *disk_super;
  6311. int copy_num;
  6312. if (!bdev)
  6313. return;
  6314. for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
  6315. copy_num++) {
  6316. if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
  6317. continue;
  6318. disk_super = (struct btrfs_super_block *)bh->b_data;
  6319. memset(&disk_super->magic, 0, sizeof(disk_super->magic));
  6320. set_buffer_dirty(bh);
  6321. sync_dirty_buffer(bh);
  6322. brelse(bh);
  6323. }
  6324. /* Notify udev that device has changed */
  6325. btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
  6326. /* Update ctime/mtime for device path for libblkid */
  6327. update_dev_time(device_path);
  6328. }
  6329. /*
  6330. * Update the size of all devices, which is used for writing out the
  6331. * super blocks.
  6332. */
  6333. void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
  6334. {
  6335. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  6336. struct btrfs_device *curr, *next;
  6337. if (list_empty(&fs_devices->resized_devices))
  6338. return;
  6339. mutex_lock(&fs_devices->device_list_mutex);
  6340. mutex_lock(&fs_info->chunk_mutex);
  6341. list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
  6342. resized_list) {
  6343. list_del_init(&curr->resized_list);
  6344. curr->commit_total_bytes = curr->disk_total_bytes;
  6345. }
  6346. mutex_unlock(&fs_info->chunk_mutex);
  6347. mutex_unlock(&fs_devices->device_list_mutex);
  6348. }
  6349. /* Must be invoked during the transaction commit */
  6350. void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans)
  6351. {
  6352. struct btrfs_fs_info *fs_info = trans->fs_info;
  6353. struct extent_map *em;
  6354. struct map_lookup *map;
  6355. struct btrfs_device *dev;
  6356. int i;
  6357. if (list_empty(&trans->pending_chunks))
  6358. return;
  6359. /* In order to kick the device replace finish process */
  6360. mutex_lock(&fs_info->chunk_mutex);
  6361. list_for_each_entry(em, &trans->pending_chunks, list) {
  6362. map = em->map_lookup;
  6363. for (i = 0; i < map->num_stripes; i++) {
  6364. dev = map->stripes[i].dev;
  6365. dev->commit_bytes_used = dev->bytes_used;
  6366. }
  6367. }
  6368. mutex_unlock(&fs_info->chunk_mutex);
  6369. }
  6370. void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
  6371. {
  6372. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  6373. while (fs_devices) {
  6374. fs_devices->fs_info = fs_info;
  6375. fs_devices = fs_devices->seed;
  6376. }
  6377. }
  6378. void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
  6379. {
  6380. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  6381. while (fs_devices) {
  6382. fs_devices->fs_info = NULL;
  6383. fs_devices = fs_devices->seed;
  6384. }
  6385. }