volumes.c 198 KB

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