volumes.c 193 KB

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