volumes.c 198 KB

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