volumes.c 222 KB

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