block.c 249 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488
  1. /*
  2. * QEMU System Emulator block driver
  3. *
  4. * Copyright (c) 2003 Fabrice Bellard
  5. * Copyright (c) 2020 Virtuozzo International GmbH.
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in
  15. * all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  20. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. * THE SOFTWARE.
  24. */
  25. #include "qemu/osdep.h"
  26. #include "block/trace.h"
  27. #include "block/block_int.h"
  28. #include "block/blockjob.h"
  29. #include "block/dirty-bitmap.h"
  30. #include "block/fuse.h"
  31. #include "block/nbd.h"
  32. #include "block/qdict.h"
  33. #include "qemu/error-report.h"
  34. #include "block/module_block.h"
  35. #include "qemu/main-loop.h"
  36. #include "qemu/module.h"
  37. #include "qapi/error.h"
  38. #include "qobject/qdict.h"
  39. #include "qobject/qjson.h"
  40. #include "qobject/qnull.h"
  41. #include "qobject/qstring.h"
  42. #include "qapi/qobject-output-visitor.h"
  43. #include "qapi/qapi-visit-block-core.h"
  44. #include "system/block-backend.h"
  45. #include "qemu/notify.h"
  46. #include "qemu/option.h"
  47. #include "qemu/coroutine.h"
  48. #include "block/qapi.h"
  49. #include "qemu/timer.h"
  50. #include "qemu/cutils.h"
  51. #include "qemu/id.h"
  52. #include "qemu/range.h"
  53. #include "qemu/rcu.h"
  54. #include "block/coroutines.h"
  55. #ifdef CONFIG_BSD
  56. #include <sys/ioctl.h>
  57. #include <sys/queue.h>
  58. #if defined(HAVE_SYS_DISK_H)
  59. #include <sys/disk.h>
  60. #endif
  61. #endif
  62. #ifdef _WIN32
  63. #include <windows.h>
  64. #endif
  65. #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
  66. /* Protected by BQL */
  67. static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
  68. QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
  69. /* Protected by BQL */
  70. static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
  71. QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
  72. /* Protected by BQL */
  73. static QLIST_HEAD(, BlockDriver) bdrv_drivers =
  74. QLIST_HEAD_INITIALIZER(bdrv_drivers);
  75. static BlockDriverState *bdrv_open_inherit(const char *filename,
  76. const char *reference,
  77. QDict *options, int flags,
  78. BlockDriverState *parent,
  79. const BdrvChildClass *child_class,
  80. BdrvChildRole child_role,
  81. bool parse_filename,
  82. Error **errp);
  83. static bool bdrv_recurse_has_child(BlockDriverState *bs,
  84. BlockDriverState *child);
  85. static void GRAPH_WRLOCK
  86. bdrv_replace_child_noperm(BdrvChild *child, BlockDriverState *new_bs);
  87. static void GRAPH_WRLOCK
  88. bdrv_remove_child(BdrvChild *child, Transaction *tran);
  89. static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
  90. BlockReopenQueue *queue,
  91. Transaction *change_child_tran, Error **errp);
  92. static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
  93. static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
  94. static bool bdrv_backing_overridden(BlockDriverState *bs);
  95. static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
  96. GHashTable *visited, Transaction *tran,
  97. Error **errp);
  98. /* If non-zero, use only whitelisted block drivers */
  99. static int use_bdrv_whitelist;
  100. #ifdef _WIN32
  101. static int is_windows_drive_prefix(const char *filename)
  102. {
  103. return (((filename[0] >= 'a' && filename[0] <= 'z') ||
  104. (filename[0] >= 'A' && filename[0] <= 'Z')) &&
  105. filename[1] == ':');
  106. }
  107. int is_windows_drive(const char *filename)
  108. {
  109. if (is_windows_drive_prefix(filename) &&
  110. filename[2] == '\0')
  111. return 1;
  112. if (strstart(filename, "\\\\.\\", NULL) ||
  113. strstart(filename, "//./", NULL))
  114. return 1;
  115. return 0;
  116. }
  117. #endif
  118. size_t bdrv_opt_mem_align(BlockDriverState *bs)
  119. {
  120. if (!bs || !bs->drv) {
  121. /* page size or 4k (hdd sector size) should be on the safe side */
  122. return MAX(4096, qemu_real_host_page_size());
  123. }
  124. IO_CODE();
  125. return bs->bl.opt_mem_alignment;
  126. }
  127. size_t bdrv_min_mem_align(BlockDriverState *bs)
  128. {
  129. if (!bs || !bs->drv) {
  130. /* page size or 4k (hdd sector size) should be on the safe side */
  131. return MAX(4096, qemu_real_host_page_size());
  132. }
  133. IO_CODE();
  134. return bs->bl.min_mem_alignment;
  135. }
  136. /* check if the path starts with "<protocol>:" */
  137. int path_has_protocol(const char *path)
  138. {
  139. const char *p;
  140. #ifdef _WIN32
  141. if (is_windows_drive(path) ||
  142. is_windows_drive_prefix(path)) {
  143. return 0;
  144. }
  145. p = path + strcspn(path, ":/\\");
  146. #else
  147. p = path + strcspn(path, ":/");
  148. #endif
  149. return *p == ':';
  150. }
  151. int path_is_absolute(const char *path)
  152. {
  153. #ifdef _WIN32
  154. /* specific case for names like: "\\.\d:" */
  155. if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
  156. return 1;
  157. }
  158. return (*path == '/' || *path == '\\');
  159. #else
  160. return (*path == '/');
  161. #endif
  162. }
  163. /* if filename is absolute, just return its duplicate. Otherwise, build a
  164. path to it by considering it is relative to base_path. URL are
  165. supported. */
  166. char *path_combine(const char *base_path, const char *filename)
  167. {
  168. const char *protocol_stripped = NULL;
  169. const char *p, *p1;
  170. char *result;
  171. int len;
  172. if (path_is_absolute(filename)) {
  173. return g_strdup(filename);
  174. }
  175. if (path_has_protocol(base_path)) {
  176. protocol_stripped = strchr(base_path, ':');
  177. if (protocol_stripped) {
  178. protocol_stripped++;
  179. }
  180. }
  181. p = protocol_stripped ?: base_path;
  182. p1 = strrchr(base_path, '/');
  183. #ifdef _WIN32
  184. {
  185. const char *p2;
  186. p2 = strrchr(base_path, '\\');
  187. if (!p1 || p2 > p1) {
  188. p1 = p2;
  189. }
  190. }
  191. #endif
  192. if (p1) {
  193. p1++;
  194. } else {
  195. p1 = base_path;
  196. }
  197. if (p1 > p) {
  198. p = p1;
  199. }
  200. len = p - base_path;
  201. result = g_malloc(len + strlen(filename) + 1);
  202. memcpy(result, base_path, len);
  203. strcpy(result + len, filename);
  204. return result;
  205. }
  206. /*
  207. * Helper function for bdrv_parse_filename() implementations to remove optional
  208. * protocol prefixes (especially "file:") from a filename and for putting the
  209. * stripped filename into the options QDict if there is such a prefix.
  210. */
  211. void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
  212. QDict *options)
  213. {
  214. if (strstart(filename, prefix, &filename)) {
  215. /* Stripping the explicit protocol prefix may result in a protocol
  216. * prefix being (wrongly) detected (if the filename contains a colon) */
  217. if (path_has_protocol(filename)) {
  218. GString *fat_filename;
  219. /* This means there is some colon before the first slash; therefore,
  220. * this cannot be an absolute path */
  221. assert(!path_is_absolute(filename));
  222. /* And we can thus fix the protocol detection issue by prefixing it
  223. * by "./" */
  224. fat_filename = g_string_new("./");
  225. g_string_append(fat_filename, filename);
  226. assert(!path_has_protocol(fat_filename->str));
  227. qdict_put(options, "filename",
  228. qstring_from_gstring(fat_filename));
  229. } else {
  230. /* If no protocol prefix was detected, we can use the shortened
  231. * filename as-is */
  232. qdict_put_str(options, "filename", filename);
  233. }
  234. }
  235. }
  236. /* Returns whether the image file is opened as read-only. Note that this can
  237. * return false and writing to the image file is still not possible because the
  238. * image is inactivated. */
  239. bool bdrv_is_read_only(BlockDriverState *bs)
  240. {
  241. IO_CODE();
  242. return !(bs->open_flags & BDRV_O_RDWR);
  243. }
  244. static int GRAPH_RDLOCK
  245. bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
  246. bool ignore_allow_rdw, Error **errp)
  247. {
  248. IO_CODE();
  249. /* Do not set read_only if copy_on_read is enabled */
  250. if (bs->copy_on_read && read_only) {
  251. error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
  252. bdrv_get_device_or_node_name(bs));
  253. return -EINVAL;
  254. }
  255. /* Do not clear read_only if it is prohibited */
  256. if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
  257. !ignore_allow_rdw)
  258. {
  259. error_setg(errp, "Node '%s' is read only",
  260. bdrv_get_device_or_node_name(bs));
  261. return -EPERM;
  262. }
  263. return 0;
  264. }
  265. /*
  266. * Called by a driver that can only provide a read-only image.
  267. *
  268. * Returns 0 if the node is already read-only or it could switch the node to
  269. * read-only because BDRV_O_AUTO_RDONLY is set.
  270. *
  271. * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
  272. * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
  273. * is not NULL, it is used as the error message for the Error object.
  274. */
  275. int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
  276. Error **errp)
  277. {
  278. int ret = 0;
  279. IO_CODE();
  280. if (!(bs->open_flags & BDRV_O_RDWR)) {
  281. return 0;
  282. }
  283. if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
  284. goto fail;
  285. }
  286. ret = bdrv_can_set_read_only(bs, true, false, NULL);
  287. if (ret < 0) {
  288. goto fail;
  289. }
  290. bs->open_flags &= ~BDRV_O_RDWR;
  291. return 0;
  292. fail:
  293. error_setg(errp, "%s", errmsg ?: "Image is read-only");
  294. return -EACCES;
  295. }
  296. /*
  297. * If @backing is empty, this function returns NULL without setting
  298. * @errp. In all other cases, NULL will only be returned with @errp
  299. * set.
  300. *
  301. * Therefore, a return value of NULL without @errp set means that
  302. * there is no backing file; if @errp is set, there is one but its
  303. * absolute filename cannot be generated.
  304. */
  305. char *bdrv_get_full_backing_filename_from_filename(const char *backed,
  306. const char *backing,
  307. Error **errp)
  308. {
  309. if (backing[0] == '\0') {
  310. return NULL;
  311. } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
  312. return g_strdup(backing);
  313. } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
  314. error_setg(errp, "Cannot use relative backing file names for '%s'",
  315. backed);
  316. return NULL;
  317. } else {
  318. return path_combine(backed, backing);
  319. }
  320. }
  321. /*
  322. * If @filename is empty or NULL, this function returns NULL without
  323. * setting @errp. In all other cases, NULL will only be returned with
  324. * @errp set.
  325. */
  326. static char * GRAPH_RDLOCK
  327. bdrv_make_absolute_filename(BlockDriverState *relative_to,
  328. const char *filename, Error **errp)
  329. {
  330. char *dir, *full_name;
  331. if (!filename || filename[0] == '\0') {
  332. return NULL;
  333. } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
  334. return g_strdup(filename);
  335. }
  336. dir = bdrv_dirname(relative_to, errp);
  337. if (!dir) {
  338. return NULL;
  339. }
  340. full_name = g_strconcat(dir, filename, NULL);
  341. g_free(dir);
  342. return full_name;
  343. }
  344. char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
  345. {
  346. GLOBAL_STATE_CODE();
  347. return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
  348. }
  349. void bdrv_register(BlockDriver *bdrv)
  350. {
  351. assert(bdrv->format_name);
  352. GLOBAL_STATE_CODE();
  353. QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
  354. }
  355. BlockDriverState *bdrv_new(void)
  356. {
  357. BlockDriverState *bs;
  358. int i;
  359. GLOBAL_STATE_CODE();
  360. bs = g_new0(BlockDriverState, 1);
  361. QLIST_INIT(&bs->dirty_bitmaps);
  362. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  363. QLIST_INIT(&bs->op_blockers[i]);
  364. }
  365. qemu_mutex_init(&bs->reqs_lock);
  366. qemu_mutex_init(&bs->dirty_bitmap_mutex);
  367. bs->refcnt = 1;
  368. bs->aio_context = qemu_get_aio_context();
  369. qemu_co_queue_init(&bs->flush_queue);
  370. qemu_co_mutex_init(&bs->bsc_modify_lock);
  371. bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
  372. for (i = 0; i < bdrv_drain_all_count; i++) {
  373. bdrv_drained_begin(bs);
  374. }
  375. QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
  376. return bs;
  377. }
  378. static BlockDriver *bdrv_do_find_format(const char *format_name)
  379. {
  380. BlockDriver *drv1;
  381. GLOBAL_STATE_CODE();
  382. QLIST_FOREACH(drv1, &bdrv_drivers, list) {
  383. if (!strcmp(drv1->format_name, format_name)) {
  384. return drv1;
  385. }
  386. }
  387. return NULL;
  388. }
  389. BlockDriver *bdrv_find_format(const char *format_name)
  390. {
  391. BlockDriver *drv1;
  392. int i;
  393. GLOBAL_STATE_CODE();
  394. drv1 = bdrv_do_find_format(format_name);
  395. if (drv1) {
  396. return drv1;
  397. }
  398. /* The driver isn't registered, maybe we need to load a module */
  399. for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
  400. if (!strcmp(block_driver_modules[i].format_name, format_name)) {
  401. Error *local_err = NULL;
  402. int rv = block_module_load(block_driver_modules[i].library_name,
  403. &local_err);
  404. if (rv > 0) {
  405. return bdrv_do_find_format(format_name);
  406. } else if (rv < 0) {
  407. error_report_err(local_err);
  408. }
  409. break;
  410. }
  411. }
  412. return NULL;
  413. }
  414. static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
  415. {
  416. static const char *whitelist_rw[] = {
  417. CONFIG_BDRV_RW_WHITELIST
  418. NULL
  419. };
  420. static const char *whitelist_ro[] = {
  421. CONFIG_BDRV_RO_WHITELIST
  422. NULL
  423. };
  424. const char **p;
  425. if (!whitelist_rw[0] && !whitelist_ro[0]) {
  426. return 1; /* no whitelist, anything goes */
  427. }
  428. for (p = whitelist_rw; *p; p++) {
  429. if (!strcmp(format_name, *p)) {
  430. return 1;
  431. }
  432. }
  433. if (read_only) {
  434. for (p = whitelist_ro; *p; p++) {
  435. if (!strcmp(format_name, *p)) {
  436. return 1;
  437. }
  438. }
  439. }
  440. return 0;
  441. }
  442. int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
  443. {
  444. GLOBAL_STATE_CODE();
  445. return bdrv_format_is_whitelisted(drv->format_name, read_only);
  446. }
  447. bool bdrv_uses_whitelist(void)
  448. {
  449. return use_bdrv_whitelist;
  450. }
  451. typedef struct CreateCo {
  452. BlockDriver *drv;
  453. char *filename;
  454. QemuOpts *opts;
  455. int ret;
  456. Error *err;
  457. } CreateCo;
  458. int coroutine_fn bdrv_co_create(BlockDriver *drv, const char *filename,
  459. QemuOpts *opts, Error **errp)
  460. {
  461. ERRP_GUARD();
  462. int ret;
  463. GLOBAL_STATE_CODE();
  464. if (!drv->bdrv_co_create_opts) {
  465. error_setg(errp, "Driver '%s' does not support image creation",
  466. drv->format_name);
  467. return -ENOTSUP;
  468. }
  469. ret = drv->bdrv_co_create_opts(drv, filename, opts, errp);
  470. if (ret < 0 && !*errp) {
  471. error_setg_errno(errp, -ret, "Could not create image");
  472. }
  473. return ret;
  474. }
  475. /**
  476. * Helper function for bdrv_create_file_fallback(): Resize @blk to at
  477. * least the given @minimum_size.
  478. *
  479. * On success, return @blk's actual length.
  480. * Otherwise, return -errno.
  481. */
  482. static int64_t coroutine_fn GRAPH_UNLOCKED
  483. create_file_fallback_truncate(BlockBackend *blk, int64_t minimum_size,
  484. Error **errp)
  485. {
  486. Error *local_err = NULL;
  487. int64_t size;
  488. int ret;
  489. GLOBAL_STATE_CODE();
  490. ret = blk_co_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
  491. &local_err);
  492. if (ret < 0 && ret != -ENOTSUP) {
  493. error_propagate(errp, local_err);
  494. return ret;
  495. }
  496. size = blk_co_getlength(blk);
  497. if (size < 0) {
  498. error_free(local_err);
  499. error_setg_errno(errp, -size,
  500. "Failed to inquire the new image file's length");
  501. return size;
  502. }
  503. if (size < minimum_size) {
  504. /* Need to grow the image, but we failed to do that */
  505. error_propagate(errp, local_err);
  506. return -ENOTSUP;
  507. }
  508. error_free(local_err);
  509. local_err = NULL;
  510. return size;
  511. }
  512. /**
  513. * Helper function for bdrv_create_file_fallback(): Zero the first
  514. * sector to remove any potentially pre-existing image header.
  515. */
  516. static int coroutine_fn
  517. create_file_fallback_zero_first_sector(BlockBackend *blk,
  518. int64_t current_size,
  519. Error **errp)
  520. {
  521. int64_t bytes_to_clear;
  522. int ret;
  523. GLOBAL_STATE_CODE();
  524. bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
  525. if (bytes_to_clear) {
  526. ret = blk_co_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
  527. if (ret < 0) {
  528. error_setg_errno(errp, -ret,
  529. "Failed to clear the new image's first sector");
  530. return ret;
  531. }
  532. }
  533. return 0;
  534. }
  535. /**
  536. * Simple implementation of bdrv_co_create_opts for protocol drivers
  537. * which only support creation via opening a file
  538. * (usually existing raw storage device)
  539. */
  540. int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
  541. const char *filename,
  542. QemuOpts *opts,
  543. Error **errp)
  544. {
  545. ERRP_GUARD();
  546. BlockBackend *blk;
  547. QDict *options;
  548. int64_t size = 0;
  549. char *buf = NULL;
  550. PreallocMode prealloc;
  551. Error *local_err = NULL;
  552. int ret;
  553. GLOBAL_STATE_CODE();
  554. size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
  555. buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
  556. prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
  557. PREALLOC_MODE_OFF, &local_err);
  558. g_free(buf);
  559. if (local_err) {
  560. error_propagate(errp, local_err);
  561. return -EINVAL;
  562. }
  563. if (prealloc != PREALLOC_MODE_OFF) {
  564. error_setg(errp, "Unsupported preallocation mode '%s'",
  565. PreallocMode_str(prealloc));
  566. return -ENOTSUP;
  567. }
  568. options = qdict_new();
  569. qdict_put_str(options, "driver", drv->format_name);
  570. blk = blk_co_new_open(filename, NULL, options,
  571. BDRV_O_RDWR | BDRV_O_RESIZE, errp);
  572. if (!blk) {
  573. error_prepend(errp, "Protocol driver '%s' does not support creating "
  574. "new images, so an existing image must be selected as "
  575. "the target; however, opening the given target as an "
  576. "existing image failed: ",
  577. drv->format_name);
  578. return -EINVAL;
  579. }
  580. size = create_file_fallback_truncate(blk, size, errp);
  581. if (size < 0) {
  582. ret = size;
  583. goto out;
  584. }
  585. ret = create_file_fallback_zero_first_sector(blk, size, errp);
  586. if (ret < 0) {
  587. goto out;
  588. }
  589. ret = 0;
  590. out:
  591. blk_co_unref(blk);
  592. return ret;
  593. }
  594. int coroutine_fn bdrv_co_create_file(const char *filename, QemuOpts *opts,
  595. Error **errp)
  596. {
  597. QemuOpts *protocol_opts;
  598. BlockDriver *drv;
  599. QDict *qdict;
  600. int ret;
  601. GLOBAL_STATE_CODE();
  602. drv = bdrv_find_protocol(filename, true, errp);
  603. if (drv == NULL) {
  604. return -ENOENT;
  605. }
  606. if (!drv->create_opts) {
  607. error_setg(errp, "Driver '%s' does not support image creation",
  608. drv->format_name);
  609. return -ENOTSUP;
  610. }
  611. /*
  612. * 'opts' contains a QemuOptsList with a combination of format and protocol
  613. * default values.
  614. *
  615. * The format properly removes its options, but the default values remain
  616. * in 'opts->list'. So if the protocol has options with the same name
  617. * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
  618. * of the format, since for overlapping options, the format wins.
  619. *
  620. * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
  621. * only the set options, and then convert it back to QemuOpts, using the
  622. * create_opts of the protocol. So the new QemuOpts, will contain only the
  623. * protocol defaults.
  624. */
  625. qdict = qemu_opts_to_qdict(opts, NULL);
  626. protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
  627. if (protocol_opts == NULL) {
  628. ret = -EINVAL;
  629. goto out;
  630. }
  631. ret = bdrv_co_create(drv, filename, protocol_opts, errp);
  632. out:
  633. qemu_opts_del(protocol_opts);
  634. qobject_unref(qdict);
  635. return ret;
  636. }
  637. int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
  638. {
  639. Error *local_err = NULL;
  640. int ret;
  641. IO_CODE();
  642. assert(bs != NULL);
  643. assert_bdrv_graph_readable();
  644. if (!bs->drv) {
  645. error_setg(errp, "Block node '%s' is not opened", bs->filename);
  646. return -ENOMEDIUM;
  647. }
  648. if (!bs->drv->bdrv_co_delete_file) {
  649. error_setg(errp, "Driver '%s' does not support image deletion",
  650. bs->drv->format_name);
  651. return -ENOTSUP;
  652. }
  653. ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
  654. if (ret < 0) {
  655. error_propagate(errp, local_err);
  656. }
  657. return ret;
  658. }
  659. void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
  660. {
  661. Error *local_err = NULL;
  662. int ret;
  663. IO_CODE();
  664. if (!bs) {
  665. return;
  666. }
  667. ret = bdrv_co_delete_file(bs, &local_err);
  668. /*
  669. * ENOTSUP will happen if the block driver doesn't support
  670. * the 'bdrv_co_delete_file' interface. This is a predictable
  671. * scenario and shouldn't be reported back to the user.
  672. */
  673. if (ret == -ENOTSUP) {
  674. error_free(local_err);
  675. } else if (ret < 0) {
  676. error_report_err(local_err);
  677. }
  678. }
  679. /**
  680. * Try to get @bs's logical and physical block size.
  681. * On success, store them in @bsz struct and return 0.
  682. * On failure return -errno.
  683. * @bs must not be empty.
  684. */
  685. int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
  686. {
  687. BlockDriver *drv = bs->drv;
  688. BlockDriverState *filtered = bdrv_filter_bs(bs);
  689. GLOBAL_STATE_CODE();
  690. if (drv && drv->bdrv_probe_blocksizes) {
  691. return drv->bdrv_probe_blocksizes(bs, bsz);
  692. } else if (filtered) {
  693. return bdrv_probe_blocksizes(filtered, bsz);
  694. }
  695. return -ENOTSUP;
  696. }
  697. /**
  698. * Try to get @bs's geometry (cyls, heads, sectors).
  699. * On success, store them in @geo struct and return 0.
  700. * On failure return -errno.
  701. * @bs must not be empty.
  702. */
  703. int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
  704. {
  705. BlockDriver *drv = bs->drv;
  706. BlockDriverState *filtered;
  707. GLOBAL_STATE_CODE();
  708. GRAPH_RDLOCK_GUARD_MAINLOOP();
  709. if (drv && drv->bdrv_probe_geometry) {
  710. return drv->bdrv_probe_geometry(bs, geo);
  711. }
  712. filtered = bdrv_filter_bs(bs);
  713. if (filtered) {
  714. return bdrv_probe_geometry(filtered, geo);
  715. }
  716. return -ENOTSUP;
  717. }
  718. /*
  719. * Create a uniquely-named empty temporary file.
  720. * Return the actual file name used upon success, otherwise NULL.
  721. * This string should be freed with g_free() when not needed any longer.
  722. *
  723. * Note: creating a temporary file for the caller to (re)open is
  724. * inherently racy. Use g_file_open_tmp() instead whenever practical.
  725. */
  726. char *create_tmp_file(Error **errp)
  727. {
  728. int fd;
  729. const char *tmpdir;
  730. g_autofree char *filename = NULL;
  731. tmpdir = g_get_tmp_dir();
  732. #ifndef _WIN32
  733. /*
  734. * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
  735. *
  736. * This function is used to create temporary disk images (like -snapshot),
  737. * so the files can become very large. /tmp is often a tmpfs where as
  738. * /var/tmp is usually on a disk, so more appropriate for disk images.
  739. */
  740. if (!g_strcmp0(tmpdir, "/tmp")) {
  741. tmpdir = "/var/tmp";
  742. }
  743. #endif
  744. filename = g_strdup_printf("%s/vl.XXXXXX", tmpdir);
  745. fd = g_mkstemp(filename);
  746. if (fd < 0) {
  747. error_setg_errno(errp, errno, "Could not open temporary file '%s'",
  748. filename);
  749. return NULL;
  750. }
  751. close(fd);
  752. return g_steal_pointer(&filename);
  753. }
  754. /*
  755. * Detect host devices. By convention, /dev/cdrom[N] is always
  756. * recognized as a host CDROM.
  757. */
  758. static BlockDriver *find_hdev_driver(const char *filename)
  759. {
  760. int score_max = 0, score;
  761. BlockDriver *drv = NULL, *d;
  762. GLOBAL_STATE_CODE();
  763. QLIST_FOREACH(d, &bdrv_drivers, list) {
  764. if (d->bdrv_probe_device) {
  765. score = d->bdrv_probe_device(filename);
  766. if (score > score_max) {
  767. score_max = score;
  768. drv = d;
  769. }
  770. }
  771. }
  772. return drv;
  773. }
  774. static BlockDriver *bdrv_do_find_protocol(const char *protocol)
  775. {
  776. BlockDriver *drv1;
  777. GLOBAL_STATE_CODE();
  778. QLIST_FOREACH(drv1, &bdrv_drivers, list) {
  779. if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
  780. return drv1;
  781. }
  782. }
  783. return NULL;
  784. }
  785. BlockDriver *bdrv_find_protocol(const char *filename,
  786. bool allow_protocol_prefix,
  787. Error **errp)
  788. {
  789. BlockDriver *drv1;
  790. char protocol[128];
  791. int len;
  792. const char *p;
  793. int i;
  794. GLOBAL_STATE_CODE();
  795. /*
  796. * XXX(hch): we really should not let host device detection
  797. * override an explicit protocol specification, but moving this
  798. * later breaks access to device names with colons in them.
  799. * Thanks to the brain-dead persistent naming schemes on udev-
  800. * based Linux systems those actually are quite common.
  801. */
  802. drv1 = find_hdev_driver(filename);
  803. if (drv1) {
  804. return drv1;
  805. }
  806. if (!path_has_protocol(filename) || !allow_protocol_prefix) {
  807. return &bdrv_file;
  808. }
  809. p = strchr(filename, ':');
  810. assert(p != NULL);
  811. len = p - filename;
  812. if (len > sizeof(protocol) - 1)
  813. len = sizeof(protocol) - 1;
  814. memcpy(protocol, filename, len);
  815. protocol[len] = '\0';
  816. drv1 = bdrv_do_find_protocol(protocol);
  817. if (drv1) {
  818. return drv1;
  819. }
  820. for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
  821. if (block_driver_modules[i].protocol_name &&
  822. !strcmp(block_driver_modules[i].protocol_name, protocol)) {
  823. int rv = block_module_load(block_driver_modules[i].library_name, errp);
  824. if (rv > 0) {
  825. drv1 = bdrv_do_find_protocol(protocol);
  826. } else if (rv < 0) {
  827. return NULL;
  828. }
  829. break;
  830. }
  831. }
  832. if (!drv1) {
  833. error_setg(errp, "Unknown protocol '%s'", protocol);
  834. }
  835. return drv1;
  836. }
  837. /*
  838. * Guess image format by probing its contents.
  839. * This is not a good idea when your image is raw (CVE-2008-2004), but
  840. * we do it anyway for backward compatibility.
  841. *
  842. * @buf contains the image's first @buf_size bytes.
  843. * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
  844. * but can be smaller if the image file is smaller)
  845. * @filename is its filename.
  846. *
  847. * For all block drivers, call the bdrv_probe() method to get its
  848. * probing score.
  849. * Return the first block driver with the highest probing score.
  850. */
  851. BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
  852. const char *filename)
  853. {
  854. int score_max = 0, score;
  855. BlockDriver *drv = NULL, *d;
  856. IO_CODE();
  857. QLIST_FOREACH(d, &bdrv_drivers, list) {
  858. if (d->bdrv_probe) {
  859. score = d->bdrv_probe(buf, buf_size, filename);
  860. if (score > score_max) {
  861. score_max = score;
  862. drv = d;
  863. }
  864. }
  865. }
  866. return drv;
  867. }
  868. static int find_image_format(BlockBackend *file, const char *filename,
  869. BlockDriver **pdrv, Error **errp)
  870. {
  871. BlockDriver *drv;
  872. uint8_t buf[BLOCK_PROBE_BUF_SIZE];
  873. int ret = 0;
  874. GLOBAL_STATE_CODE();
  875. /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
  876. if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
  877. *pdrv = &bdrv_raw;
  878. return ret;
  879. }
  880. ret = blk_pread(file, 0, sizeof(buf), buf, 0);
  881. if (ret < 0) {
  882. error_setg_errno(errp, -ret, "Could not read image for determining its "
  883. "format");
  884. *pdrv = NULL;
  885. return ret;
  886. }
  887. drv = bdrv_probe_all(buf, sizeof(buf), filename);
  888. if (!drv) {
  889. error_setg(errp, "Could not determine image format: No compatible "
  890. "driver found");
  891. *pdrv = NULL;
  892. return -ENOENT;
  893. }
  894. *pdrv = drv;
  895. return 0;
  896. }
  897. /**
  898. * Set the current 'total_sectors' value
  899. * Return 0 on success, -errno on error.
  900. */
  901. int coroutine_fn bdrv_co_refresh_total_sectors(BlockDriverState *bs,
  902. int64_t hint)
  903. {
  904. BlockDriver *drv = bs->drv;
  905. IO_CODE();
  906. assert_bdrv_graph_readable();
  907. if (!drv) {
  908. return -ENOMEDIUM;
  909. }
  910. /* Do not attempt drv->bdrv_co_getlength() on scsi-generic devices */
  911. if (bdrv_is_sg(bs))
  912. return 0;
  913. /* query actual device if possible, otherwise just trust the hint */
  914. if (drv->bdrv_co_getlength) {
  915. int64_t length = drv->bdrv_co_getlength(bs);
  916. if (length < 0) {
  917. return length;
  918. }
  919. hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
  920. }
  921. bs->total_sectors = hint;
  922. if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
  923. return -EFBIG;
  924. }
  925. return 0;
  926. }
  927. /**
  928. * Combines a QDict of new block driver @options with any missing options taken
  929. * from @old_options, so that leaving out an option defaults to its old value.
  930. */
  931. static void bdrv_join_options(BlockDriverState *bs, QDict *options,
  932. QDict *old_options)
  933. {
  934. GLOBAL_STATE_CODE();
  935. if (bs->drv && bs->drv->bdrv_join_options) {
  936. bs->drv->bdrv_join_options(options, old_options);
  937. } else {
  938. qdict_join(options, old_options, false);
  939. }
  940. }
  941. static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
  942. int open_flags,
  943. Error **errp)
  944. {
  945. Error *local_err = NULL;
  946. char *value = qemu_opt_get_del(opts, "detect-zeroes");
  947. BlockdevDetectZeroesOptions detect_zeroes =
  948. qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
  949. BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
  950. GLOBAL_STATE_CODE();
  951. g_free(value);
  952. if (local_err) {
  953. error_propagate(errp, local_err);
  954. return detect_zeroes;
  955. }
  956. if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
  957. !(open_flags & BDRV_O_UNMAP))
  958. {
  959. error_setg(errp, "setting detect-zeroes to unmap is not allowed "
  960. "without setting discard operation to unmap");
  961. }
  962. return detect_zeroes;
  963. }
  964. /**
  965. * Set open flags for aio engine
  966. *
  967. * Return 0 on success, -1 if the engine specified is invalid
  968. */
  969. int bdrv_parse_aio(const char *mode, int *flags)
  970. {
  971. if (!strcmp(mode, "threads")) {
  972. /* do nothing, default */
  973. } else if (!strcmp(mode, "native")) {
  974. *flags |= BDRV_O_NATIVE_AIO;
  975. #ifdef CONFIG_LINUX_IO_URING
  976. } else if (!strcmp(mode, "io_uring")) {
  977. *flags |= BDRV_O_IO_URING;
  978. #endif
  979. } else {
  980. return -1;
  981. }
  982. return 0;
  983. }
  984. /**
  985. * Set open flags for a given discard mode
  986. *
  987. * Return 0 on success, -1 if the discard mode was invalid.
  988. */
  989. int bdrv_parse_discard_flags(const char *mode, int *flags)
  990. {
  991. *flags &= ~BDRV_O_UNMAP;
  992. if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
  993. /* do nothing */
  994. } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
  995. *flags |= BDRV_O_UNMAP;
  996. } else {
  997. return -1;
  998. }
  999. return 0;
  1000. }
  1001. /**
  1002. * Set open flags for a given cache mode
  1003. *
  1004. * Return 0 on success, -1 if the cache mode was invalid.
  1005. */
  1006. int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
  1007. {
  1008. *flags &= ~BDRV_O_CACHE_MASK;
  1009. if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
  1010. *writethrough = false;
  1011. *flags |= BDRV_O_NOCACHE;
  1012. } else if (!strcmp(mode, "directsync")) {
  1013. *writethrough = true;
  1014. *flags |= BDRV_O_NOCACHE;
  1015. } else if (!strcmp(mode, "writeback")) {
  1016. *writethrough = false;
  1017. } else if (!strcmp(mode, "unsafe")) {
  1018. *writethrough = false;
  1019. *flags |= BDRV_O_NO_FLUSH;
  1020. } else if (!strcmp(mode, "writethrough")) {
  1021. *writethrough = true;
  1022. } else {
  1023. return -1;
  1024. }
  1025. return 0;
  1026. }
  1027. static char *bdrv_child_get_parent_desc(BdrvChild *c)
  1028. {
  1029. BlockDriverState *parent = c->opaque;
  1030. return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
  1031. }
  1032. static void GRAPH_RDLOCK bdrv_child_cb_drained_begin(BdrvChild *child)
  1033. {
  1034. BlockDriverState *bs = child->opaque;
  1035. bdrv_do_drained_begin_quiesce(bs, NULL);
  1036. }
  1037. static bool GRAPH_RDLOCK bdrv_child_cb_drained_poll(BdrvChild *child)
  1038. {
  1039. BlockDriverState *bs = child->opaque;
  1040. return bdrv_drain_poll(bs, NULL, false);
  1041. }
  1042. static void GRAPH_RDLOCK bdrv_child_cb_drained_end(BdrvChild *child)
  1043. {
  1044. BlockDriverState *bs = child->opaque;
  1045. bdrv_drained_end(bs);
  1046. }
  1047. static int bdrv_child_cb_inactivate(BdrvChild *child)
  1048. {
  1049. BlockDriverState *bs = child->opaque;
  1050. GLOBAL_STATE_CODE();
  1051. assert(bs->open_flags & BDRV_O_INACTIVE);
  1052. return 0;
  1053. }
  1054. static bool bdrv_child_cb_change_aio_ctx(BdrvChild *child, AioContext *ctx,
  1055. GHashTable *visited, Transaction *tran,
  1056. Error **errp)
  1057. {
  1058. BlockDriverState *bs = child->opaque;
  1059. return bdrv_change_aio_context(bs, ctx, visited, tran, errp);
  1060. }
  1061. /*
  1062. * Returns the options and flags that a temporary snapshot should get, based on
  1063. * the originally requested flags (the originally requested image will have
  1064. * flags like a backing file)
  1065. */
  1066. static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
  1067. int parent_flags, QDict *parent_options)
  1068. {
  1069. GLOBAL_STATE_CODE();
  1070. *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
  1071. /* For temporary files, unconditional cache=unsafe is fine */
  1072. qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
  1073. qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
  1074. /* Copy the read-only and discard options from the parent */
  1075. qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
  1076. qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
  1077. /* aio=native doesn't work for cache.direct=off, so disable it for the
  1078. * temporary snapshot */
  1079. *child_flags &= ~BDRV_O_NATIVE_AIO;
  1080. }
  1081. static void GRAPH_WRLOCK bdrv_backing_attach(BdrvChild *c)
  1082. {
  1083. BlockDriverState *parent = c->opaque;
  1084. BlockDriverState *backing_hd = c->bs;
  1085. GLOBAL_STATE_CODE();
  1086. assert(!parent->backing_blocker);
  1087. error_setg(&parent->backing_blocker,
  1088. "node is used as backing hd of '%s'",
  1089. bdrv_get_device_or_node_name(parent));
  1090. bdrv_refresh_filename(backing_hd);
  1091. parent->open_flags &= ~BDRV_O_NO_BACKING;
  1092. bdrv_op_block_all(backing_hd, parent->backing_blocker);
  1093. /* Otherwise we won't be able to commit or stream */
  1094. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
  1095. parent->backing_blocker);
  1096. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
  1097. parent->backing_blocker);
  1098. /*
  1099. * We do backup in 3 ways:
  1100. * 1. drive backup
  1101. * The target bs is new opened, and the source is top BDS
  1102. * 2. blockdev backup
  1103. * Both the source and the target are top BDSes.
  1104. * 3. internal backup(used for block replication)
  1105. * Both the source and the target are backing file
  1106. *
  1107. * In case 1 and 2, neither the source nor the target is the backing file.
  1108. * In case 3, we will block the top BDS, so there is only one block job
  1109. * for the top BDS and its backing chain.
  1110. */
  1111. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
  1112. parent->backing_blocker);
  1113. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
  1114. parent->backing_blocker);
  1115. }
  1116. static void bdrv_backing_detach(BdrvChild *c)
  1117. {
  1118. BlockDriverState *parent = c->opaque;
  1119. GLOBAL_STATE_CODE();
  1120. assert(parent->backing_blocker);
  1121. bdrv_op_unblock_all(c->bs, parent->backing_blocker);
  1122. error_free(parent->backing_blocker);
  1123. parent->backing_blocker = NULL;
  1124. }
  1125. static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
  1126. const char *filename,
  1127. bool backing_mask_protocol,
  1128. Error **errp)
  1129. {
  1130. BlockDriverState *parent = c->opaque;
  1131. bool read_only = bdrv_is_read_only(parent);
  1132. int ret;
  1133. const char *format_name;
  1134. GLOBAL_STATE_CODE();
  1135. if (read_only) {
  1136. ret = bdrv_reopen_set_read_only(parent, false, errp);
  1137. if (ret < 0) {
  1138. return ret;
  1139. }
  1140. }
  1141. if (base->drv) {
  1142. /*
  1143. * If the new base image doesn't have a format driver layer, which we
  1144. * detect by the fact that @base is a protocol driver, we record
  1145. * 'raw' as the format instead of putting the protocol name as the
  1146. * backing format
  1147. */
  1148. if (backing_mask_protocol && base->drv->protocol_name) {
  1149. format_name = "raw";
  1150. } else {
  1151. format_name = base->drv->format_name;
  1152. }
  1153. } else {
  1154. format_name = "";
  1155. }
  1156. ret = bdrv_change_backing_file(parent, filename, format_name, false);
  1157. if (ret < 0) {
  1158. error_setg_errno(errp, -ret, "Could not update backing file link");
  1159. }
  1160. if (read_only) {
  1161. bdrv_reopen_set_read_only(parent, true, NULL);
  1162. }
  1163. return ret;
  1164. }
  1165. /*
  1166. * Returns the options and flags that a generic child of a BDS should
  1167. * get, based on the given options and flags for the parent BDS.
  1168. */
  1169. static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
  1170. int *child_flags, QDict *child_options,
  1171. int parent_flags, QDict *parent_options)
  1172. {
  1173. int flags = parent_flags;
  1174. GLOBAL_STATE_CODE();
  1175. /*
  1176. * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
  1177. * Generally, the question to answer is: Should this child be
  1178. * format-probed by default?
  1179. */
  1180. /*
  1181. * Pure and non-filtered data children of non-format nodes should
  1182. * be probed by default (even when the node itself has BDRV_O_PROTOCOL
  1183. * set). This only affects a very limited set of drivers (namely
  1184. * quorum and blkverify when this comment was written).
  1185. * Force-clear BDRV_O_PROTOCOL then.
  1186. */
  1187. if (!parent_is_format &&
  1188. (role & BDRV_CHILD_DATA) &&
  1189. !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
  1190. {
  1191. flags &= ~BDRV_O_PROTOCOL;
  1192. }
  1193. /*
  1194. * All children of format nodes (except for COW children) and all
  1195. * metadata children in general should never be format-probed.
  1196. * Force-set BDRV_O_PROTOCOL then.
  1197. */
  1198. if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
  1199. (role & BDRV_CHILD_METADATA))
  1200. {
  1201. flags |= BDRV_O_PROTOCOL;
  1202. }
  1203. /*
  1204. * If the cache mode isn't explicitly set, inherit direct and no-flush from
  1205. * the parent.
  1206. */
  1207. qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
  1208. qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
  1209. qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
  1210. if (role & BDRV_CHILD_COW) {
  1211. /* backing files are opened read-only by default */
  1212. qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
  1213. qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
  1214. } else {
  1215. /* Inherit the read-only option from the parent if it's not set */
  1216. qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
  1217. qdict_copy_default(child_options, parent_options,
  1218. BDRV_OPT_AUTO_READ_ONLY);
  1219. }
  1220. /*
  1221. * bdrv_co_pdiscard() respects unmap policy for the parent, so we
  1222. * can default to enable it on lower layers regardless of the
  1223. * parent option.
  1224. */
  1225. qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
  1226. /* Clear flags that only apply to the top layer */
  1227. flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
  1228. if (role & BDRV_CHILD_METADATA) {
  1229. flags &= ~BDRV_O_NO_IO;
  1230. }
  1231. if (role & BDRV_CHILD_COW) {
  1232. flags &= ~BDRV_O_TEMPORARY;
  1233. }
  1234. *child_flags = flags;
  1235. }
  1236. static void GRAPH_WRLOCK bdrv_child_cb_attach(BdrvChild *child)
  1237. {
  1238. BlockDriverState *bs = child->opaque;
  1239. assert_bdrv_graph_writable();
  1240. QLIST_INSERT_HEAD(&bs->children, child, next);
  1241. if (bs->drv->is_filter || (child->role & BDRV_CHILD_FILTERED)) {
  1242. /*
  1243. * Here we handle filters and block/raw-format.c when it behave like
  1244. * filter. They generally have a single PRIMARY child, which is also the
  1245. * FILTERED child, and that they may have multiple more children, which
  1246. * are neither PRIMARY nor FILTERED. And never we have a COW child here.
  1247. * So bs->file will be the PRIMARY child, unless the PRIMARY child goes
  1248. * into bs->backing on exceptional cases; and bs->backing will be
  1249. * nothing else.
  1250. */
  1251. assert(!(child->role & BDRV_CHILD_COW));
  1252. if (child->role & BDRV_CHILD_PRIMARY) {
  1253. assert(child->role & BDRV_CHILD_FILTERED);
  1254. assert(!bs->backing);
  1255. assert(!bs->file);
  1256. if (bs->drv->filtered_child_is_backing) {
  1257. bs->backing = child;
  1258. } else {
  1259. bs->file = child;
  1260. }
  1261. } else {
  1262. assert(!(child->role & BDRV_CHILD_FILTERED));
  1263. }
  1264. } else if (child->role & BDRV_CHILD_COW) {
  1265. assert(bs->drv->supports_backing);
  1266. assert(!(child->role & BDRV_CHILD_PRIMARY));
  1267. assert(!bs->backing);
  1268. bs->backing = child;
  1269. bdrv_backing_attach(child);
  1270. } else if (child->role & BDRV_CHILD_PRIMARY) {
  1271. assert(!bs->file);
  1272. bs->file = child;
  1273. }
  1274. }
  1275. static void GRAPH_WRLOCK bdrv_child_cb_detach(BdrvChild *child)
  1276. {
  1277. BlockDriverState *bs = child->opaque;
  1278. if (child->role & BDRV_CHILD_COW) {
  1279. bdrv_backing_detach(child);
  1280. }
  1281. assert_bdrv_graph_writable();
  1282. QLIST_REMOVE(child, next);
  1283. if (child == bs->backing) {
  1284. assert(child != bs->file);
  1285. bs->backing = NULL;
  1286. } else if (child == bs->file) {
  1287. bs->file = NULL;
  1288. }
  1289. }
  1290. static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
  1291. const char *filename,
  1292. bool backing_mask_protocol,
  1293. Error **errp)
  1294. {
  1295. if (c->role & BDRV_CHILD_COW) {
  1296. return bdrv_backing_update_filename(c, base, filename,
  1297. backing_mask_protocol,
  1298. errp);
  1299. }
  1300. return 0;
  1301. }
  1302. AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
  1303. {
  1304. BlockDriverState *bs = c->opaque;
  1305. IO_CODE();
  1306. return bdrv_get_aio_context(bs);
  1307. }
  1308. const BdrvChildClass child_of_bds = {
  1309. .parent_is_bds = true,
  1310. .get_parent_desc = bdrv_child_get_parent_desc,
  1311. .inherit_options = bdrv_inherited_options,
  1312. .drained_begin = bdrv_child_cb_drained_begin,
  1313. .drained_poll = bdrv_child_cb_drained_poll,
  1314. .drained_end = bdrv_child_cb_drained_end,
  1315. .attach = bdrv_child_cb_attach,
  1316. .detach = bdrv_child_cb_detach,
  1317. .inactivate = bdrv_child_cb_inactivate,
  1318. .change_aio_ctx = bdrv_child_cb_change_aio_ctx,
  1319. .update_filename = bdrv_child_cb_update_filename,
  1320. .get_parent_aio_context = child_of_bds_get_parent_aio_context,
  1321. };
  1322. AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
  1323. {
  1324. IO_CODE();
  1325. return c->klass->get_parent_aio_context(c);
  1326. }
  1327. static int bdrv_open_flags(BlockDriverState *bs, int flags)
  1328. {
  1329. int open_flags = flags;
  1330. GLOBAL_STATE_CODE();
  1331. /*
  1332. * Clear flags that are internal to the block layer before opening the
  1333. * image.
  1334. */
  1335. open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
  1336. return open_flags;
  1337. }
  1338. static void update_flags_from_options(int *flags, QemuOpts *opts)
  1339. {
  1340. GLOBAL_STATE_CODE();
  1341. *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
  1342. if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
  1343. *flags |= BDRV_O_NO_FLUSH;
  1344. }
  1345. if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
  1346. *flags |= BDRV_O_NOCACHE;
  1347. }
  1348. if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
  1349. *flags |= BDRV_O_RDWR;
  1350. }
  1351. if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
  1352. *flags |= BDRV_O_AUTO_RDONLY;
  1353. }
  1354. if (!qemu_opt_get_bool_del(opts, BDRV_OPT_ACTIVE, true)) {
  1355. *flags |= BDRV_O_INACTIVE;
  1356. }
  1357. }
  1358. static void update_options_from_flags(QDict *options, int flags)
  1359. {
  1360. GLOBAL_STATE_CODE();
  1361. if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
  1362. qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
  1363. }
  1364. if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
  1365. qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
  1366. flags & BDRV_O_NO_FLUSH);
  1367. }
  1368. if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
  1369. qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
  1370. }
  1371. if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
  1372. qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
  1373. flags & BDRV_O_AUTO_RDONLY);
  1374. }
  1375. }
  1376. static void bdrv_assign_node_name(BlockDriverState *bs,
  1377. const char *node_name,
  1378. Error **errp)
  1379. {
  1380. char *gen_node_name = NULL;
  1381. GLOBAL_STATE_CODE();
  1382. if (!node_name) {
  1383. node_name = gen_node_name = id_generate(ID_BLOCK);
  1384. } else if (!id_wellformed(node_name)) {
  1385. /*
  1386. * Check for empty string or invalid characters, but not if it is
  1387. * generated (generated names use characters not available to the user)
  1388. */
  1389. error_setg(errp, "Invalid node-name: '%s'", node_name);
  1390. return;
  1391. }
  1392. /* takes care of avoiding namespaces collisions */
  1393. if (blk_by_name(node_name)) {
  1394. error_setg(errp, "node-name=%s is conflicting with a device id",
  1395. node_name);
  1396. goto out;
  1397. }
  1398. /* takes care of avoiding duplicates node names */
  1399. if (bdrv_find_node(node_name)) {
  1400. error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
  1401. goto out;
  1402. }
  1403. /* Make sure that the node name isn't truncated */
  1404. if (strlen(node_name) >= sizeof(bs->node_name)) {
  1405. error_setg(errp, "Node name too long");
  1406. goto out;
  1407. }
  1408. /* copy node name into the bs and insert it into the graph list */
  1409. pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
  1410. QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
  1411. out:
  1412. g_free(gen_node_name);
  1413. }
  1414. static int no_coroutine_fn GRAPH_UNLOCKED
  1415. bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv, const char *node_name,
  1416. QDict *options, int open_flags, Error **errp)
  1417. {
  1418. Error *local_err = NULL;
  1419. int i, ret;
  1420. GLOBAL_STATE_CODE();
  1421. bdrv_assign_node_name(bs, node_name, &local_err);
  1422. if (local_err) {
  1423. error_propagate(errp, local_err);
  1424. return -EINVAL;
  1425. }
  1426. bs->drv = drv;
  1427. bs->opaque = g_malloc0(drv->instance_size);
  1428. assert(!drv->bdrv_needs_filename || bs->filename[0]);
  1429. if (drv->bdrv_open) {
  1430. ret = drv->bdrv_open(bs, options, open_flags, &local_err);
  1431. } else {
  1432. ret = 0;
  1433. }
  1434. if (ret < 0) {
  1435. if (local_err) {
  1436. error_propagate(errp, local_err);
  1437. } else if (bs->filename[0]) {
  1438. error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
  1439. } else {
  1440. error_setg_errno(errp, -ret, "Could not open image");
  1441. }
  1442. goto open_failed;
  1443. }
  1444. assert(!(bs->supported_read_flags & ~BDRV_REQ_MASK));
  1445. assert(!(bs->supported_write_flags & ~BDRV_REQ_MASK));
  1446. /*
  1447. * Always allow the BDRV_REQ_REGISTERED_BUF optimization hint. This saves
  1448. * drivers that pass read/write requests through to a child the trouble of
  1449. * declaring support explicitly.
  1450. *
  1451. * Drivers must not propagate this flag accidentally when they initiate I/O
  1452. * to a bounce buffer. That case should be rare though.
  1453. */
  1454. bs->supported_read_flags |= BDRV_REQ_REGISTERED_BUF;
  1455. bs->supported_write_flags |= BDRV_REQ_REGISTERED_BUF;
  1456. ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
  1457. if (ret < 0) {
  1458. error_setg_errno(errp, -ret, "Could not refresh total sector count");
  1459. return ret;
  1460. }
  1461. bdrv_graph_rdlock_main_loop();
  1462. bdrv_refresh_limits(bs, NULL, &local_err);
  1463. bdrv_graph_rdunlock_main_loop();
  1464. if (local_err) {
  1465. error_propagate(errp, local_err);
  1466. return -EINVAL;
  1467. }
  1468. assert(bdrv_opt_mem_align(bs) != 0);
  1469. assert(bdrv_min_mem_align(bs) != 0);
  1470. assert(is_power_of_2(bs->bl.request_alignment));
  1471. for (i = 0; i < bs->quiesce_counter; i++) {
  1472. if (drv->bdrv_drain_begin) {
  1473. drv->bdrv_drain_begin(bs);
  1474. }
  1475. }
  1476. return 0;
  1477. open_failed:
  1478. bs->drv = NULL;
  1479. bdrv_graph_wrlock();
  1480. if (bs->file != NULL) {
  1481. bdrv_unref_child(bs, bs->file);
  1482. assert(!bs->file);
  1483. }
  1484. bdrv_graph_wrunlock();
  1485. g_free(bs->opaque);
  1486. bs->opaque = NULL;
  1487. return ret;
  1488. }
  1489. /*
  1490. * Create and open a block node.
  1491. *
  1492. * @options is a QDict of options to pass to the block drivers, or NULL for an
  1493. * empty set of options. The reference to the QDict belongs to the block layer
  1494. * after the call (even on failure), so if the caller intends to reuse the
  1495. * dictionary, it needs to use qobject_ref() before calling bdrv_open.
  1496. */
  1497. BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
  1498. const char *node_name,
  1499. QDict *options, int flags,
  1500. Error **errp)
  1501. {
  1502. BlockDriverState *bs;
  1503. int ret;
  1504. GLOBAL_STATE_CODE();
  1505. bs = bdrv_new();
  1506. bs->open_flags = flags;
  1507. bs->options = options ?: qdict_new();
  1508. bs->explicit_options = qdict_clone_shallow(bs->options);
  1509. bs->opaque = NULL;
  1510. update_options_from_flags(bs->options, flags);
  1511. ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
  1512. if (ret < 0) {
  1513. qobject_unref(bs->explicit_options);
  1514. bs->explicit_options = NULL;
  1515. qobject_unref(bs->options);
  1516. bs->options = NULL;
  1517. bdrv_unref(bs);
  1518. return NULL;
  1519. }
  1520. return bs;
  1521. }
  1522. /* Create and open a block node. */
  1523. BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
  1524. int flags, Error **errp)
  1525. {
  1526. GLOBAL_STATE_CODE();
  1527. return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
  1528. }
  1529. QemuOptsList bdrv_runtime_opts = {
  1530. .name = "bdrv_common",
  1531. .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
  1532. .desc = {
  1533. {
  1534. .name = "node-name",
  1535. .type = QEMU_OPT_STRING,
  1536. .help = "Node name of the block device node",
  1537. },
  1538. {
  1539. .name = "driver",
  1540. .type = QEMU_OPT_STRING,
  1541. .help = "Block driver to use for the node",
  1542. },
  1543. {
  1544. .name = BDRV_OPT_CACHE_DIRECT,
  1545. .type = QEMU_OPT_BOOL,
  1546. .help = "Bypass software writeback cache on the host",
  1547. },
  1548. {
  1549. .name = BDRV_OPT_CACHE_NO_FLUSH,
  1550. .type = QEMU_OPT_BOOL,
  1551. .help = "Ignore flush requests",
  1552. },
  1553. {
  1554. .name = BDRV_OPT_ACTIVE,
  1555. .type = QEMU_OPT_BOOL,
  1556. .help = "Node is activated",
  1557. },
  1558. {
  1559. .name = BDRV_OPT_READ_ONLY,
  1560. .type = QEMU_OPT_BOOL,
  1561. .help = "Node is opened in read-only mode",
  1562. },
  1563. {
  1564. .name = BDRV_OPT_AUTO_READ_ONLY,
  1565. .type = QEMU_OPT_BOOL,
  1566. .help = "Node can become read-only if opening read-write fails",
  1567. },
  1568. {
  1569. .name = "detect-zeroes",
  1570. .type = QEMU_OPT_STRING,
  1571. .help = "try to optimize zero writes (off, on, unmap)",
  1572. },
  1573. {
  1574. .name = BDRV_OPT_DISCARD,
  1575. .type = QEMU_OPT_STRING,
  1576. .help = "discard operation (ignore/off, unmap/on)",
  1577. },
  1578. {
  1579. .name = BDRV_OPT_FORCE_SHARE,
  1580. .type = QEMU_OPT_BOOL,
  1581. .help = "always accept other writers (default: off)",
  1582. },
  1583. { /* end of list */ }
  1584. },
  1585. };
  1586. QemuOptsList bdrv_create_opts_simple = {
  1587. .name = "simple-create-opts",
  1588. .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
  1589. .desc = {
  1590. {
  1591. .name = BLOCK_OPT_SIZE,
  1592. .type = QEMU_OPT_SIZE,
  1593. .help = "Virtual disk size"
  1594. },
  1595. {
  1596. .name = BLOCK_OPT_PREALLOC,
  1597. .type = QEMU_OPT_STRING,
  1598. .help = "Preallocation mode (allowed values: off)"
  1599. },
  1600. { /* end of list */ }
  1601. }
  1602. };
  1603. /*
  1604. * Common part for opening disk images and files
  1605. *
  1606. * Removes all processed options from *options.
  1607. */
  1608. static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
  1609. QDict *options, Error **errp)
  1610. {
  1611. int ret, open_flags;
  1612. const char *filename;
  1613. const char *driver_name = NULL;
  1614. const char *node_name = NULL;
  1615. const char *discard;
  1616. QemuOpts *opts;
  1617. BlockDriver *drv;
  1618. Error *local_err = NULL;
  1619. bool ro;
  1620. GLOBAL_STATE_CODE();
  1621. bdrv_graph_rdlock_main_loop();
  1622. assert(bs->file == NULL);
  1623. assert(options != NULL && bs->options != options);
  1624. bdrv_graph_rdunlock_main_loop();
  1625. opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
  1626. if (!qemu_opts_absorb_qdict(opts, options, errp)) {
  1627. ret = -EINVAL;
  1628. goto fail_opts;
  1629. }
  1630. update_flags_from_options(&bs->open_flags, opts);
  1631. driver_name = qemu_opt_get(opts, "driver");
  1632. drv = bdrv_find_format(driver_name);
  1633. assert(drv != NULL);
  1634. bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
  1635. if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
  1636. error_setg(errp,
  1637. BDRV_OPT_FORCE_SHARE
  1638. "=on can only be used with read-only images");
  1639. ret = -EINVAL;
  1640. goto fail_opts;
  1641. }
  1642. if (file != NULL) {
  1643. bdrv_graph_rdlock_main_loop();
  1644. bdrv_refresh_filename(blk_bs(file));
  1645. bdrv_graph_rdunlock_main_loop();
  1646. filename = blk_bs(file)->filename;
  1647. } else {
  1648. /*
  1649. * Caution: while qdict_get_try_str() is fine, getting
  1650. * non-string types would require more care. When @options
  1651. * come from -blockdev or blockdev_add, its members are typed
  1652. * according to the QAPI schema, but when they come from
  1653. * -drive, they're all QString.
  1654. */
  1655. filename = qdict_get_try_str(options, "filename");
  1656. }
  1657. if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
  1658. error_setg(errp, "The '%s' block driver requires a file name",
  1659. drv->format_name);
  1660. ret = -EINVAL;
  1661. goto fail_opts;
  1662. }
  1663. trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
  1664. drv->format_name);
  1665. ro = bdrv_is_read_only(bs);
  1666. if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
  1667. if (!ro && bdrv_is_whitelisted(drv, true)) {
  1668. bdrv_graph_rdlock_main_loop();
  1669. ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
  1670. bdrv_graph_rdunlock_main_loop();
  1671. } else {
  1672. ret = -ENOTSUP;
  1673. }
  1674. if (ret < 0) {
  1675. error_setg(errp,
  1676. !ro && bdrv_is_whitelisted(drv, true)
  1677. ? "Driver '%s' can only be used for read-only devices"
  1678. : "Driver '%s' is not whitelisted",
  1679. drv->format_name);
  1680. goto fail_opts;
  1681. }
  1682. }
  1683. /* bdrv_new() and bdrv_close() make it so */
  1684. assert(qatomic_read(&bs->copy_on_read) == 0);
  1685. if (bs->open_flags & BDRV_O_COPY_ON_READ) {
  1686. if (!ro) {
  1687. bdrv_enable_copy_on_read(bs);
  1688. } else {
  1689. error_setg(errp, "Can't use copy-on-read on read-only device");
  1690. ret = -EINVAL;
  1691. goto fail_opts;
  1692. }
  1693. }
  1694. discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
  1695. if (discard != NULL) {
  1696. if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
  1697. error_setg(errp, "Invalid discard option");
  1698. ret = -EINVAL;
  1699. goto fail_opts;
  1700. }
  1701. }
  1702. bs->detect_zeroes =
  1703. bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
  1704. if (local_err) {
  1705. error_propagate(errp, local_err);
  1706. ret = -EINVAL;
  1707. goto fail_opts;
  1708. }
  1709. if (filename != NULL) {
  1710. pstrcpy(bs->filename, sizeof(bs->filename), filename);
  1711. } else {
  1712. bs->filename[0] = '\0';
  1713. }
  1714. pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
  1715. /* Open the image, either directly or using a protocol */
  1716. open_flags = bdrv_open_flags(bs, bs->open_flags);
  1717. node_name = qemu_opt_get(opts, "node-name");
  1718. assert(!drv->protocol_name || file == NULL);
  1719. ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
  1720. if (ret < 0) {
  1721. goto fail_opts;
  1722. }
  1723. qemu_opts_del(opts);
  1724. return 0;
  1725. fail_opts:
  1726. qemu_opts_del(opts);
  1727. return ret;
  1728. }
  1729. static QDict *parse_json_filename(const char *filename, Error **errp)
  1730. {
  1731. ERRP_GUARD();
  1732. QObject *options_obj;
  1733. QDict *options;
  1734. int ret;
  1735. GLOBAL_STATE_CODE();
  1736. ret = strstart(filename, "json:", &filename);
  1737. assert(ret);
  1738. options_obj = qobject_from_json(filename, errp);
  1739. if (!options_obj) {
  1740. error_prepend(errp, "Could not parse the JSON options: ");
  1741. return NULL;
  1742. }
  1743. options = qobject_to(QDict, options_obj);
  1744. if (!options) {
  1745. qobject_unref(options_obj);
  1746. error_setg(errp, "Invalid JSON object given");
  1747. return NULL;
  1748. }
  1749. qdict_flatten(options);
  1750. return options;
  1751. }
  1752. static void parse_json_protocol(QDict *options, const char **pfilename,
  1753. Error **errp)
  1754. {
  1755. QDict *json_options;
  1756. Error *local_err = NULL;
  1757. GLOBAL_STATE_CODE();
  1758. /* Parse json: pseudo-protocol */
  1759. if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
  1760. return;
  1761. }
  1762. json_options = parse_json_filename(*pfilename, &local_err);
  1763. if (local_err) {
  1764. error_propagate(errp, local_err);
  1765. return;
  1766. }
  1767. /* Options given in the filename have lower priority than options
  1768. * specified directly */
  1769. qdict_join(options, json_options, false);
  1770. qobject_unref(json_options);
  1771. *pfilename = NULL;
  1772. }
  1773. /*
  1774. * Fills in default options for opening images and converts the legacy
  1775. * filename/flags pair to option QDict entries.
  1776. * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
  1777. * block driver has been specified explicitly.
  1778. */
  1779. static int bdrv_fill_options(QDict **options, const char *filename,
  1780. int *flags, bool allow_parse_filename,
  1781. Error **errp)
  1782. {
  1783. const char *drvname;
  1784. bool protocol = *flags & BDRV_O_PROTOCOL;
  1785. bool parse_filename = false;
  1786. BlockDriver *drv = NULL;
  1787. Error *local_err = NULL;
  1788. GLOBAL_STATE_CODE();
  1789. /*
  1790. * Caution: while qdict_get_try_str() is fine, getting non-string
  1791. * types would require more care. When @options come from
  1792. * -blockdev or blockdev_add, its members are typed according to
  1793. * the QAPI schema, but when they come from -drive, they're all
  1794. * QString.
  1795. */
  1796. drvname = qdict_get_try_str(*options, "driver");
  1797. if (drvname) {
  1798. drv = bdrv_find_format(drvname);
  1799. if (!drv) {
  1800. error_setg(errp, "Unknown driver '%s'", drvname);
  1801. return -ENOENT;
  1802. }
  1803. /* If the user has explicitly specified the driver, this choice should
  1804. * override the BDRV_O_PROTOCOL flag */
  1805. protocol = drv->protocol_name;
  1806. }
  1807. if (protocol) {
  1808. *flags |= BDRV_O_PROTOCOL;
  1809. } else {
  1810. *flags &= ~BDRV_O_PROTOCOL;
  1811. }
  1812. /* Translate cache options from flags into options */
  1813. update_options_from_flags(*options, *flags);
  1814. /* Fetch the file name from the options QDict if necessary */
  1815. if (protocol && filename) {
  1816. if (!qdict_haskey(*options, "filename")) {
  1817. qdict_put_str(*options, "filename", filename);
  1818. parse_filename = allow_parse_filename;
  1819. } else {
  1820. error_setg(errp, "Can't specify 'file' and 'filename' options at "
  1821. "the same time");
  1822. return -EINVAL;
  1823. }
  1824. }
  1825. /* Find the right block driver */
  1826. /* See cautionary note on accessing @options above */
  1827. filename = qdict_get_try_str(*options, "filename");
  1828. if (!drvname && protocol) {
  1829. if (filename) {
  1830. drv = bdrv_find_protocol(filename, parse_filename, errp);
  1831. if (!drv) {
  1832. return -EINVAL;
  1833. }
  1834. drvname = drv->format_name;
  1835. qdict_put_str(*options, "driver", drvname);
  1836. } else {
  1837. error_setg(errp, "Must specify either driver or file");
  1838. return -EINVAL;
  1839. }
  1840. }
  1841. assert(drv || !protocol);
  1842. /* Driver-specific filename parsing */
  1843. if (drv && drv->bdrv_parse_filename && parse_filename) {
  1844. drv->bdrv_parse_filename(filename, *options, &local_err);
  1845. if (local_err) {
  1846. error_propagate(errp, local_err);
  1847. return -EINVAL;
  1848. }
  1849. if (!drv->bdrv_needs_filename) {
  1850. qdict_del(*options, "filename");
  1851. }
  1852. }
  1853. return 0;
  1854. }
  1855. typedef struct BlockReopenQueueEntry {
  1856. bool prepared;
  1857. BDRVReopenState state;
  1858. QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
  1859. } BlockReopenQueueEntry;
  1860. /*
  1861. * Return the flags that @bs will have after the reopens in @q have
  1862. * successfully completed. If @q is NULL (or @bs is not contained in @q),
  1863. * return the current flags.
  1864. */
  1865. static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
  1866. {
  1867. BlockReopenQueueEntry *entry;
  1868. if (q != NULL) {
  1869. QTAILQ_FOREACH(entry, q, entry) {
  1870. if (entry->state.bs == bs) {
  1871. return entry->state.flags;
  1872. }
  1873. }
  1874. }
  1875. return bs->open_flags;
  1876. }
  1877. /* Returns whether the image file can be written to after the reopen queue @q
  1878. * has been successfully applied, or right now if @q is NULL. */
  1879. static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
  1880. BlockReopenQueue *q)
  1881. {
  1882. int flags = bdrv_reopen_get_flags(q, bs);
  1883. return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
  1884. }
  1885. /*
  1886. * Return whether the BDS can be written to. This is not necessarily
  1887. * the same as !bdrv_is_read_only(bs), as inactivated images may not
  1888. * be written to but do not count as read-only images.
  1889. */
  1890. bool bdrv_is_writable(BlockDriverState *bs)
  1891. {
  1892. IO_CODE();
  1893. return bdrv_is_writable_after_reopen(bs, NULL);
  1894. }
  1895. static char *bdrv_child_user_desc(BdrvChild *c)
  1896. {
  1897. GLOBAL_STATE_CODE();
  1898. return c->klass->get_parent_desc(c);
  1899. }
  1900. /*
  1901. * Check that @a allows everything that @b needs. @a and @b must reference same
  1902. * child node.
  1903. */
  1904. static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
  1905. {
  1906. const char *child_bs_name;
  1907. g_autofree char *a_user = NULL;
  1908. g_autofree char *b_user = NULL;
  1909. g_autofree char *perms = NULL;
  1910. assert(a->bs);
  1911. assert(a->bs == b->bs);
  1912. GLOBAL_STATE_CODE();
  1913. if ((b->perm & a->shared_perm) == b->perm) {
  1914. return true;
  1915. }
  1916. child_bs_name = bdrv_get_node_name(b->bs);
  1917. a_user = bdrv_child_user_desc(a);
  1918. b_user = bdrv_child_user_desc(b);
  1919. perms = bdrv_perm_names(b->perm & ~a->shared_perm);
  1920. error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
  1921. "both required by %s (uses node '%s' as '%s' child) and "
  1922. "unshared by %s (uses node '%s' as '%s' child).",
  1923. child_bs_name, perms,
  1924. b_user, child_bs_name, b->name,
  1925. a_user, child_bs_name, a->name);
  1926. return false;
  1927. }
  1928. static bool GRAPH_RDLOCK
  1929. bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
  1930. {
  1931. BdrvChild *a, *b;
  1932. GLOBAL_STATE_CODE();
  1933. /*
  1934. * During the loop we'll look at each pair twice. That's correct because
  1935. * bdrv_a_allow_b() is asymmetric and we should check each pair in both
  1936. * directions.
  1937. */
  1938. QLIST_FOREACH(a, &bs->parents, next_parent) {
  1939. QLIST_FOREACH(b, &bs->parents, next_parent) {
  1940. if (a == b) {
  1941. continue;
  1942. }
  1943. if (!bdrv_a_allow_b(a, b, errp)) {
  1944. return true;
  1945. }
  1946. }
  1947. }
  1948. return false;
  1949. }
  1950. static void GRAPH_RDLOCK
  1951. bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
  1952. BdrvChild *c, BdrvChildRole role,
  1953. BlockReopenQueue *reopen_queue,
  1954. uint64_t parent_perm, uint64_t parent_shared,
  1955. uint64_t *nperm, uint64_t *nshared)
  1956. {
  1957. assert(bs->drv && bs->drv->bdrv_child_perm);
  1958. GLOBAL_STATE_CODE();
  1959. bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
  1960. parent_perm, parent_shared,
  1961. nperm, nshared);
  1962. /* TODO Take force_share from reopen_queue */
  1963. if (child_bs && child_bs->force_share) {
  1964. *nshared = BLK_PERM_ALL;
  1965. }
  1966. }
  1967. /*
  1968. * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
  1969. * nodes that are already in the @list, of course) so that final list is
  1970. * topologically sorted. Return the result (GSList @list object is updated, so
  1971. * don't use old reference after function call).
  1972. *
  1973. * On function start @list must be already topologically sorted and for any node
  1974. * in the @list the whole subtree of the node must be in the @list as well. The
  1975. * simplest way to satisfy this criteria: use only result of
  1976. * bdrv_topological_dfs() or NULL as @list parameter.
  1977. */
  1978. static GSList * GRAPH_RDLOCK
  1979. bdrv_topological_dfs(GSList *list, GHashTable *found, BlockDriverState *bs)
  1980. {
  1981. BdrvChild *child;
  1982. g_autoptr(GHashTable) local_found = NULL;
  1983. GLOBAL_STATE_CODE();
  1984. if (!found) {
  1985. assert(!list);
  1986. found = local_found = g_hash_table_new(NULL, NULL);
  1987. }
  1988. if (g_hash_table_contains(found, bs)) {
  1989. return list;
  1990. }
  1991. g_hash_table_add(found, bs);
  1992. QLIST_FOREACH(child, &bs->children, next) {
  1993. list = bdrv_topological_dfs(list, found, child->bs);
  1994. }
  1995. return g_slist_prepend(list, bs);
  1996. }
  1997. typedef struct BdrvChildSetPermState {
  1998. BdrvChild *child;
  1999. uint64_t old_perm;
  2000. uint64_t old_shared_perm;
  2001. } BdrvChildSetPermState;
  2002. static void bdrv_child_set_perm_abort(void *opaque)
  2003. {
  2004. BdrvChildSetPermState *s = opaque;
  2005. GLOBAL_STATE_CODE();
  2006. s->child->perm = s->old_perm;
  2007. s->child->shared_perm = s->old_shared_perm;
  2008. }
  2009. static TransactionActionDrv bdrv_child_set_pem_drv = {
  2010. .abort = bdrv_child_set_perm_abort,
  2011. .clean = g_free,
  2012. };
  2013. static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
  2014. uint64_t shared, Transaction *tran)
  2015. {
  2016. BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
  2017. GLOBAL_STATE_CODE();
  2018. *s = (BdrvChildSetPermState) {
  2019. .child = c,
  2020. .old_perm = c->perm,
  2021. .old_shared_perm = c->shared_perm,
  2022. };
  2023. c->perm = perm;
  2024. c->shared_perm = shared;
  2025. tran_add(tran, &bdrv_child_set_pem_drv, s);
  2026. }
  2027. static void GRAPH_RDLOCK bdrv_drv_set_perm_commit(void *opaque)
  2028. {
  2029. BlockDriverState *bs = opaque;
  2030. uint64_t cumulative_perms, cumulative_shared_perms;
  2031. GLOBAL_STATE_CODE();
  2032. if (bs->drv->bdrv_set_perm) {
  2033. bdrv_get_cumulative_perm(bs, &cumulative_perms,
  2034. &cumulative_shared_perms);
  2035. bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
  2036. }
  2037. }
  2038. static void GRAPH_RDLOCK bdrv_drv_set_perm_abort(void *opaque)
  2039. {
  2040. BlockDriverState *bs = opaque;
  2041. GLOBAL_STATE_CODE();
  2042. if (bs->drv->bdrv_abort_perm_update) {
  2043. bs->drv->bdrv_abort_perm_update(bs);
  2044. }
  2045. }
  2046. TransactionActionDrv bdrv_drv_set_perm_drv = {
  2047. .abort = bdrv_drv_set_perm_abort,
  2048. .commit = bdrv_drv_set_perm_commit,
  2049. };
  2050. /*
  2051. * After calling this function, the transaction @tran may only be completed
  2052. * while holding a reader lock for the graph.
  2053. */
  2054. static int GRAPH_RDLOCK
  2055. bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared_perm,
  2056. Transaction *tran, Error **errp)
  2057. {
  2058. GLOBAL_STATE_CODE();
  2059. if (!bs->drv) {
  2060. return 0;
  2061. }
  2062. if (bs->drv->bdrv_check_perm) {
  2063. int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
  2064. if (ret < 0) {
  2065. return ret;
  2066. }
  2067. }
  2068. if (tran) {
  2069. tran_add(tran, &bdrv_drv_set_perm_drv, bs);
  2070. }
  2071. return 0;
  2072. }
  2073. typedef struct BdrvReplaceChildState {
  2074. BdrvChild *child;
  2075. BlockDriverState *old_bs;
  2076. } BdrvReplaceChildState;
  2077. static void GRAPH_WRLOCK bdrv_replace_child_commit(void *opaque)
  2078. {
  2079. BdrvReplaceChildState *s = opaque;
  2080. GLOBAL_STATE_CODE();
  2081. bdrv_schedule_unref(s->old_bs);
  2082. }
  2083. static void GRAPH_WRLOCK bdrv_replace_child_abort(void *opaque)
  2084. {
  2085. BdrvReplaceChildState *s = opaque;
  2086. BlockDriverState *new_bs = s->child->bs;
  2087. GLOBAL_STATE_CODE();
  2088. assert_bdrv_graph_writable();
  2089. /* old_bs reference is transparently moved from @s to @s->child */
  2090. if (!s->child->bs) {
  2091. /*
  2092. * The parents were undrained when removing old_bs from the child. New
  2093. * requests can't have been made, though, because the child was empty.
  2094. *
  2095. * TODO Make bdrv_replace_child_noperm() transactionable to avoid
  2096. * undraining the parent in the first place. Once this is done, having
  2097. * new_bs drained when calling bdrv_replace_child_tran() is not a
  2098. * requirement any more.
  2099. */
  2100. bdrv_parent_drained_begin_single(s->child);
  2101. assert(!bdrv_parent_drained_poll_single(s->child));
  2102. }
  2103. assert(s->child->quiesced_parent);
  2104. bdrv_replace_child_noperm(s->child, s->old_bs);
  2105. bdrv_unref(new_bs);
  2106. }
  2107. static TransactionActionDrv bdrv_replace_child_drv = {
  2108. .commit = bdrv_replace_child_commit,
  2109. .abort = bdrv_replace_child_abort,
  2110. .clean = g_free,
  2111. };
  2112. /*
  2113. * bdrv_replace_child_tran
  2114. *
  2115. * Note: real unref of old_bs is done only on commit.
  2116. *
  2117. * Both @child->bs and @new_bs (if non-NULL) must be drained. @new_bs must be
  2118. * kept drained until the transaction is completed.
  2119. *
  2120. * After calling this function, the transaction @tran may only be completed
  2121. * while holding a writer lock for the graph.
  2122. *
  2123. * The function doesn't update permissions, caller is responsible for this.
  2124. */
  2125. static void GRAPH_WRLOCK
  2126. bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
  2127. Transaction *tran)
  2128. {
  2129. BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
  2130. assert(child->quiesced_parent);
  2131. assert(!new_bs || new_bs->quiesce_counter);
  2132. *s = (BdrvReplaceChildState) {
  2133. .child = child,
  2134. .old_bs = child->bs,
  2135. };
  2136. tran_add(tran, &bdrv_replace_child_drv, s);
  2137. if (new_bs) {
  2138. bdrv_ref(new_bs);
  2139. }
  2140. bdrv_replace_child_noperm(child, new_bs);
  2141. /* old_bs reference is transparently moved from @child to @s */
  2142. }
  2143. /*
  2144. * Refresh permissions in @bs subtree. The function is intended to be called
  2145. * after some graph modification that was done without permission update.
  2146. *
  2147. * After calling this function, the transaction @tran may only be completed
  2148. * while holding a reader lock for the graph.
  2149. */
  2150. static int GRAPH_RDLOCK
  2151. bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
  2152. Transaction *tran, Error **errp)
  2153. {
  2154. BlockDriver *drv = bs->drv;
  2155. BdrvChild *c;
  2156. int ret;
  2157. uint64_t cumulative_perms, cumulative_shared_perms;
  2158. GLOBAL_STATE_CODE();
  2159. bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
  2160. /* Write permissions never work with read-only images */
  2161. if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
  2162. !bdrv_is_writable_after_reopen(bs, q))
  2163. {
  2164. if (!bdrv_is_writable_after_reopen(bs, NULL)) {
  2165. error_setg(errp, "Block node is read-only");
  2166. } else {
  2167. error_setg(errp, "Read-only block node '%s' cannot support "
  2168. "read-write users", bdrv_get_node_name(bs));
  2169. }
  2170. return -EPERM;
  2171. }
  2172. /*
  2173. * Unaligned requests will automatically be aligned to bl.request_alignment
  2174. * and without RESIZE we can't extend requests to write to space beyond the
  2175. * end of the image, so it's required that the image size is aligned.
  2176. */
  2177. if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
  2178. !(cumulative_perms & BLK_PERM_RESIZE))
  2179. {
  2180. if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
  2181. error_setg(errp, "Cannot get 'write' permission without 'resize': "
  2182. "Image size is not a multiple of request "
  2183. "alignment");
  2184. return -EPERM;
  2185. }
  2186. }
  2187. /* Check this node */
  2188. if (!drv) {
  2189. return 0;
  2190. }
  2191. ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
  2192. errp);
  2193. if (ret < 0) {
  2194. return ret;
  2195. }
  2196. /* Drivers that never have children can omit .bdrv_child_perm() */
  2197. if (!drv->bdrv_child_perm) {
  2198. assert(QLIST_EMPTY(&bs->children));
  2199. return 0;
  2200. }
  2201. /* Check all children */
  2202. QLIST_FOREACH(c, &bs->children, next) {
  2203. uint64_t cur_perm, cur_shared;
  2204. bdrv_child_perm(bs, c->bs, c, c->role, q,
  2205. cumulative_perms, cumulative_shared_perms,
  2206. &cur_perm, &cur_shared);
  2207. bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
  2208. }
  2209. return 0;
  2210. }
  2211. /*
  2212. * @list is a product of bdrv_topological_dfs() (may be called several times) -
  2213. * a topologically sorted subgraph.
  2214. *
  2215. * After calling this function, the transaction @tran may only be completed
  2216. * while holding a reader lock for the graph.
  2217. */
  2218. static int GRAPH_RDLOCK
  2219. bdrv_do_refresh_perms(GSList *list, BlockReopenQueue *q, Transaction *tran,
  2220. Error **errp)
  2221. {
  2222. int ret;
  2223. BlockDriverState *bs;
  2224. GLOBAL_STATE_CODE();
  2225. for ( ; list; list = list->next) {
  2226. bs = list->data;
  2227. if (bdrv_parent_perms_conflict(bs, errp)) {
  2228. return -EINVAL;
  2229. }
  2230. ret = bdrv_node_refresh_perm(bs, q, tran, errp);
  2231. if (ret < 0) {
  2232. return ret;
  2233. }
  2234. }
  2235. return 0;
  2236. }
  2237. /*
  2238. * @list is any list of nodes. List is completed by all subtrees and
  2239. * topologically sorted. It's not a problem if some node occurs in the @list
  2240. * several times.
  2241. *
  2242. * After calling this function, the transaction @tran may only be completed
  2243. * while holding a reader lock for the graph.
  2244. */
  2245. static int GRAPH_RDLOCK
  2246. bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q, Transaction *tran,
  2247. Error **errp)
  2248. {
  2249. g_autoptr(GHashTable) found = g_hash_table_new(NULL, NULL);
  2250. g_autoptr(GSList) refresh_list = NULL;
  2251. for ( ; list; list = list->next) {
  2252. refresh_list = bdrv_topological_dfs(refresh_list, found, list->data);
  2253. }
  2254. return bdrv_do_refresh_perms(refresh_list, q, tran, errp);
  2255. }
  2256. void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
  2257. uint64_t *shared_perm)
  2258. {
  2259. BdrvChild *c;
  2260. uint64_t cumulative_perms = 0;
  2261. uint64_t cumulative_shared_perms = BLK_PERM_ALL;
  2262. GLOBAL_STATE_CODE();
  2263. QLIST_FOREACH(c, &bs->parents, next_parent) {
  2264. cumulative_perms |= c->perm;
  2265. cumulative_shared_perms &= c->shared_perm;
  2266. }
  2267. *perm = cumulative_perms;
  2268. *shared_perm = cumulative_shared_perms;
  2269. }
  2270. char *bdrv_perm_names(uint64_t perm)
  2271. {
  2272. struct perm_name {
  2273. uint64_t perm;
  2274. const char *name;
  2275. } permissions[] = {
  2276. { BLK_PERM_CONSISTENT_READ, "consistent read" },
  2277. { BLK_PERM_WRITE, "write" },
  2278. { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
  2279. { BLK_PERM_RESIZE, "resize" },
  2280. { 0, NULL }
  2281. };
  2282. GString *result = g_string_sized_new(30);
  2283. struct perm_name *p;
  2284. for (p = permissions; p->name; p++) {
  2285. if (perm & p->perm) {
  2286. if (result->len > 0) {
  2287. g_string_append(result, ", ");
  2288. }
  2289. g_string_append(result, p->name);
  2290. }
  2291. }
  2292. return g_string_free(result, FALSE);
  2293. }
  2294. /*
  2295. * @tran is allowed to be NULL. In this case no rollback is possible.
  2296. *
  2297. * After calling this function, the transaction @tran may only be completed
  2298. * while holding a reader lock for the graph.
  2299. */
  2300. static int GRAPH_RDLOCK
  2301. bdrv_refresh_perms(BlockDriverState *bs, Transaction *tran, Error **errp)
  2302. {
  2303. int ret;
  2304. Transaction *local_tran = NULL;
  2305. g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
  2306. GLOBAL_STATE_CODE();
  2307. if (!tran) {
  2308. tran = local_tran = tran_new();
  2309. }
  2310. ret = bdrv_do_refresh_perms(list, NULL, tran, errp);
  2311. if (local_tran) {
  2312. tran_finalize(local_tran, ret);
  2313. }
  2314. return ret;
  2315. }
  2316. int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
  2317. Error **errp)
  2318. {
  2319. Error *local_err = NULL;
  2320. Transaction *tran = tran_new();
  2321. int ret;
  2322. GLOBAL_STATE_CODE();
  2323. bdrv_child_set_perm(c, perm, shared, tran);
  2324. ret = bdrv_refresh_perms(c->bs, tran, &local_err);
  2325. tran_finalize(tran, ret);
  2326. if (ret < 0) {
  2327. if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
  2328. /* tighten permissions */
  2329. error_propagate(errp, local_err);
  2330. } else {
  2331. /*
  2332. * Our caller may intend to only loosen restrictions and
  2333. * does not expect this function to fail. Errors are not
  2334. * fatal in such a case, so we can just hide them from our
  2335. * caller.
  2336. */
  2337. error_free(local_err);
  2338. ret = 0;
  2339. }
  2340. }
  2341. return ret;
  2342. }
  2343. int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
  2344. {
  2345. uint64_t parent_perms, parent_shared;
  2346. uint64_t perms, shared;
  2347. GLOBAL_STATE_CODE();
  2348. bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
  2349. bdrv_child_perm(bs, c->bs, c, c->role, NULL,
  2350. parent_perms, parent_shared, &perms, &shared);
  2351. return bdrv_child_try_set_perm(c, perms, shared, errp);
  2352. }
  2353. /*
  2354. * Default implementation for .bdrv_child_perm() for block filters:
  2355. * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
  2356. * filtered child.
  2357. */
  2358. static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
  2359. BdrvChildRole role,
  2360. BlockReopenQueue *reopen_queue,
  2361. uint64_t perm, uint64_t shared,
  2362. uint64_t *nperm, uint64_t *nshared)
  2363. {
  2364. GLOBAL_STATE_CODE();
  2365. *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
  2366. *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
  2367. }
  2368. static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
  2369. BdrvChildRole role,
  2370. BlockReopenQueue *reopen_queue,
  2371. uint64_t perm, uint64_t shared,
  2372. uint64_t *nperm, uint64_t *nshared)
  2373. {
  2374. assert(role & BDRV_CHILD_COW);
  2375. GLOBAL_STATE_CODE();
  2376. /*
  2377. * We want consistent read from backing files if the parent needs it.
  2378. * No other operations are performed on backing files.
  2379. */
  2380. perm &= BLK_PERM_CONSISTENT_READ;
  2381. /*
  2382. * If the parent can deal with changing data, we're okay with a
  2383. * writable and resizable backing file.
  2384. * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
  2385. */
  2386. if (shared & BLK_PERM_WRITE) {
  2387. shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
  2388. } else {
  2389. shared = 0;
  2390. }
  2391. shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
  2392. if (bs->open_flags & BDRV_O_INACTIVE) {
  2393. shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
  2394. }
  2395. *nperm = perm;
  2396. *nshared = shared;
  2397. }
  2398. static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
  2399. BdrvChildRole role,
  2400. BlockReopenQueue *reopen_queue,
  2401. uint64_t perm, uint64_t shared,
  2402. uint64_t *nperm, uint64_t *nshared)
  2403. {
  2404. int flags;
  2405. GLOBAL_STATE_CODE();
  2406. assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
  2407. flags = bdrv_reopen_get_flags(reopen_queue, bs);
  2408. /*
  2409. * Apart from the modifications below, the same permissions are
  2410. * forwarded and left alone as for filters
  2411. */
  2412. bdrv_filter_default_perms(bs, c, role, reopen_queue,
  2413. perm, shared, &perm, &shared);
  2414. if (role & BDRV_CHILD_METADATA) {
  2415. /* Format drivers may touch metadata even if the guest doesn't write */
  2416. if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
  2417. perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
  2418. }
  2419. /*
  2420. * bs->file always needs to be consistent because of the
  2421. * metadata. We can never allow other users to resize or write
  2422. * to it.
  2423. */
  2424. if (!(flags & BDRV_O_NO_IO)) {
  2425. perm |= BLK_PERM_CONSISTENT_READ;
  2426. }
  2427. shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
  2428. }
  2429. if (role & BDRV_CHILD_DATA) {
  2430. /*
  2431. * Technically, everything in this block is a subset of the
  2432. * BDRV_CHILD_METADATA path taken above, and so this could
  2433. * be an "else if" branch. However, that is not obvious, and
  2434. * this function is not performance critical, therefore we let
  2435. * this be an independent "if".
  2436. */
  2437. /*
  2438. * We cannot allow other users to resize the file because the
  2439. * format driver might have some assumptions about the size
  2440. * (e.g. because it is stored in metadata, or because the file
  2441. * is split into fixed-size data files).
  2442. */
  2443. shared &= ~BLK_PERM_RESIZE;
  2444. /*
  2445. * WRITE_UNCHANGED often cannot be performed as such on the
  2446. * data file. For example, the qcow2 driver may still need to
  2447. * write copied clusters on copy-on-read.
  2448. */
  2449. if (perm & BLK_PERM_WRITE_UNCHANGED) {
  2450. perm |= BLK_PERM_WRITE;
  2451. }
  2452. /*
  2453. * If the data file is written to, the format driver may
  2454. * expect to be able to resize it by writing beyond the EOF.
  2455. */
  2456. if (perm & BLK_PERM_WRITE) {
  2457. perm |= BLK_PERM_RESIZE;
  2458. }
  2459. }
  2460. if (bs->open_flags & BDRV_O_INACTIVE) {
  2461. shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
  2462. }
  2463. *nperm = perm;
  2464. *nshared = shared;
  2465. }
  2466. void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
  2467. BdrvChildRole role, BlockReopenQueue *reopen_queue,
  2468. uint64_t perm, uint64_t shared,
  2469. uint64_t *nperm, uint64_t *nshared)
  2470. {
  2471. GLOBAL_STATE_CODE();
  2472. if (role & BDRV_CHILD_FILTERED) {
  2473. assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
  2474. BDRV_CHILD_COW)));
  2475. bdrv_filter_default_perms(bs, c, role, reopen_queue,
  2476. perm, shared, nperm, nshared);
  2477. } else if (role & BDRV_CHILD_COW) {
  2478. assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
  2479. bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
  2480. perm, shared, nperm, nshared);
  2481. } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
  2482. bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
  2483. perm, shared, nperm, nshared);
  2484. } else {
  2485. g_assert_not_reached();
  2486. }
  2487. }
  2488. uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
  2489. {
  2490. static const uint64_t permissions[] = {
  2491. [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
  2492. [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
  2493. [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
  2494. [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
  2495. };
  2496. QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
  2497. QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
  2498. assert(qapi_perm < BLOCK_PERMISSION__MAX);
  2499. return permissions[qapi_perm];
  2500. }
  2501. /*
  2502. * Replaces the node that a BdrvChild points to without updating permissions.
  2503. *
  2504. * If @new_bs is non-NULL, the parent of @child must already be drained through
  2505. * @child.
  2506. */
  2507. static void GRAPH_WRLOCK
  2508. bdrv_replace_child_noperm(BdrvChild *child, BlockDriverState *new_bs)
  2509. {
  2510. BlockDriverState *old_bs = child->bs;
  2511. int new_bs_quiesce_counter;
  2512. assert(!child->frozen);
  2513. /*
  2514. * If we want to change the BdrvChild to point to a drained node as its new
  2515. * child->bs, we need to make sure that its new parent is drained, too. In
  2516. * other words, either child->quiesce_parent must already be true or we must
  2517. * be able to set it and keep the parent's quiesce_counter consistent with
  2518. * that, but without polling or starting new requests (this function
  2519. * guarantees that it doesn't poll, and starting new requests would be
  2520. * against the invariants of drain sections).
  2521. *
  2522. * To keep things simple, we pick the first option (child->quiesce_parent
  2523. * must already be true). We also generalise the rule a bit to make it
  2524. * easier to verify in callers and more likely to be covered in test cases:
  2525. * The parent must be quiesced through this child even if new_bs isn't
  2526. * currently drained.
  2527. *
  2528. * The only exception is for callers that always pass new_bs == NULL. In
  2529. * this case, we obviously never need to consider the case of a drained
  2530. * new_bs, so we can keep the callers simpler by allowing them not to drain
  2531. * the parent.
  2532. */
  2533. assert(!new_bs || child->quiesced_parent);
  2534. assert(old_bs != new_bs);
  2535. GLOBAL_STATE_CODE();
  2536. if (old_bs && new_bs) {
  2537. assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
  2538. }
  2539. if (old_bs) {
  2540. if (child->klass->detach) {
  2541. child->klass->detach(child);
  2542. }
  2543. QLIST_REMOVE(child, next_parent);
  2544. }
  2545. child->bs = new_bs;
  2546. if (new_bs) {
  2547. QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
  2548. if (child->klass->attach) {
  2549. child->klass->attach(child);
  2550. }
  2551. }
  2552. /*
  2553. * If the parent was drained through this BdrvChild previously, but new_bs
  2554. * is not drained, allow requests to come in only after the new node has
  2555. * been attached.
  2556. */
  2557. new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
  2558. if (!new_bs_quiesce_counter && child->quiesced_parent) {
  2559. bdrv_parent_drained_end_single(child);
  2560. }
  2561. }
  2562. /**
  2563. * Free the given @child.
  2564. *
  2565. * The child must be empty (i.e. `child->bs == NULL`) and it must be
  2566. * unused (i.e. not in a children list).
  2567. */
  2568. static void bdrv_child_free(BdrvChild *child)
  2569. {
  2570. assert(!child->bs);
  2571. GLOBAL_STATE_CODE();
  2572. GRAPH_RDLOCK_GUARD_MAINLOOP();
  2573. assert(!child->next.le_prev); /* not in children list */
  2574. g_free(child->name);
  2575. g_free(child);
  2576. }
  2577. typedef struct BdrvAttachChildCommonState {
  2578. BdrvChild *child;
  2579. AioContext *old_parent_ctx;
  2580. AioContext *old_child_ctx;
  2581. } BdrvAttachChildCommonState;
  2582. static void GRAPH_WRLOCK bdrv_attach_child_common_abort(void *opaque)
  2583. {
  2584. BdrvAttachChildCommonState *s = opaque;
  2585. BlockDriverState *bs = s->child->bs;
  2586. GLOBAL_STATE_CODE();
  2587. assert_bdrv_graph_writable();
  2588. bdrv_replace_child_noperm(s->child, NULL);
  2589. if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
  2590. bdrv_try_change_aio_context(bs, s->old_child_ctx, NULL, &error_abort);
  2591. }
  2592. if (bdrv_child_get_parent_aio_context(s->child) != s->old_parent_ctx) {
  2593. Transaction *tran;
  2594. GHashTable *visited;
  2595. bool ret;
  2596. tran = tran_new();
  2597. /* No need to visit `child`, because it has been detached already */
  2598. visited = g_hash_table_new(NULL, NULL);
  2599. ret = s->child->klass->change_aio_ctx(s->child, s->old_parent_ctx,
  2600. visited, tran, &error_abort);
  2601. g_hash_table_destroy(visited);
  2602. /* transaction is supposed to always succeed */
  2603. assert(ret == true);
  2604. tran_commit(tran);
  2605. }
  2606. bdrv_schedule_unref(bs);
  2607. bdrv_child_free(s->child);
  2608. }
  2609. static TransactionActionDrv bdrv_attach_child_common_drv = {
  2610. .abort = bdrv_attach_child_common_abort,
  2611. .clean = g_free,
  2612. };
  2613. /*
  2614. * Common part of attaching bdrv child to bs or to blk or to job
  2615. *
  2616. * Function doesn't update permissions, caller is responsible for this.
  2617. *
  2618. * After calling this function, the transaction @tran may only be completed
  2619. * while holding a writer lock for the graph.
  2620. *
  2621. * Returns new created child.
  2622. *
  2623. * Both @parent_bs and @child_bs can move to a different AioContext in this
  2624. * function.
  2625. */
  2626. static BdrvChild * GRAPH_WRLOCK
  2627. bdrv_attach_child_common(BlockDriverState *child_bs,
  2628. const char *child_name,
  2629. const BdrvChildClass *child_class,
  2630. BdrvChildRole child_role,
  2631. uint64_t perm, uint64_t shared_perm,
  2632. void *opaque,
  2633. Transaction *tran, Error **errp)
  2634. {
  2635. BdrvChild *new_child;
  2636. AioContext *parent_ctx;
  2637. AioContext *child_ctx = bdrv_get_aio_context(child_bs);
  2638. assert(child_class->get_parent_desc);
  2639. GLOBAL_STATE_CODE();
  2640. if (bdrv_is_inactive(child_bs) && (perm & ~BLK_PERM_CONSISTENT_READ)) {
  2641. g_autofree char *perm_names = bdrv_perm_names(perm);
  2642. error_setg(errp, "Permission '%s' unavailable on inactive node",
  2643. perm_names);
  2644. return NULL;
  2645. }
  2646. new_child = g_new(BdrvChild, 1);
  2647. *new_child = (BdrvChild) {
  2648. .bs = NULL,
  2649. .name = g_strdup(child_name),
  2650. .klass = child_class,
  2651. .role = child_role,
  2652. .perm = perm,
  2653. .shared_perm = shared_perm,
  2654. .opaque = opaque,
  2655. };
  2656. /*
  2657. * If the AioContexts don't match, first try to move the subtree of
  2658. * child_bs into the AioContext of the new parent. If this doesn't work,
  2659. * try moving the parent into the AioContext of child_bs instead.
  2660. */
  2661. parent_ctx = bdrv_child_get_parent_aio_context(new_child);
  2662. if (child_ctx != parent_ctx) {
  2663. Error *local_err = NULL;
  2664. int ret = bdrv_try_change_aio_context(child_bs, parent_ctx, NULL,
  2665. &local_err);
  2666. if (ret < 0 && child_class->change_aio_ctx) {
  2667. Transaction *aio_ctx_tran = tran_new();
  2668. GHashTable *visited = g_hash_table_new(NULL, NULL);
  2669. bool ret_child;
  2670. g_hash_table_add(visited, new_child);
  2671. ret_child = child_class->change_aio_ctx(new_child, child_ctx,
  2672. visited, aio_ctx_tran,
  2673. NULL);
  2674. if (ret_child == true) {
  2675. error_free(local_err);
  2676. ret = 0;
  2677. }
  2678. tran_finalize(aio_ctx_tran, ret_child == true ? 0 : -1);
  2679. g_hash_table_destroy(visited);
  2680. }
  2681. if (ret < 0) {
  2682. error_propagate(errp, local_err);
  2683. bdrv_child_free(new_child);
  2684. return NULL;
  2685. }
  2686. }
  2687. bdrv_ref(child_bs);
  2688. /*
  2689. * Let every new BdrvChild start with a drained parent. Inserting the child
  2690. * in the graph with bdrv_replace_child_noperm() will undrain it if
  2691. * @child_bs is not drained.
  2692. *
  2693. * The child was only just created and is not yet visible in global state
  2694. * until bdrv_replace_child_noperm() inserts it into the graph, so nobody
  2695. * could have sent requests and polling is not necessary.
  2696. *
  2697. * Note that this means that the parent isn't fully drained yet, we only
  2698. * stop new requests from coming in. This is fine, we don't care about the
  2699. * old requests here, they are not for this child. If another place enters a
  2700. * drain section for the same parent, but wants it to be fully quiesced, it
  2701. * will not run most of the the code in .drained_begin() again (which is not
  2702. * a problem, we already did this), but it will still poll until the parent
  2703. * is fully quiesced, so it will not be negatively affected either.
  2704. */
  2705. bdrv_parent_drained_begin_single(new_child);
  2706. bdrv_replace_child_noperm(new_child, child_bs);
  2707. BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
  2708. *s = (BdrvAttachChildCommonState) {
  2709. .child = new_child,
  2710. .old_parent_ctx = parent_ctx,
  2711. .old_child_ctx = child_ctx,
  2712. };
  2713. tran_add(tran, &bdrv_attach_child_common_drv, s);
  2714. return new_child;
  2715. }
  2716. /*
  2717. * Function doesn't update permissions, caller is responsible for this.
  2718. *
  2719. * Both @parent_bs and @child_bs can move to a different AioContext in this
  2720. * function.
  2721. *
  2722. * After calling this function, the transaction @tran may only be completed
  2723. * while holding a writer lock for the graph.
  2724. */
  2725. static BdrvChild * GRAPH_WRLOCK
  2726. bdrv_attach_child_noperm(BlockDriverState *parent_bs,
  2727. BlockDriverState *child_bs,
  2728. const char *child_name,
  2729. const BdrvChildClass *child_class,
  2730. BdrvChildRole child_role,
  2731. Transaction *tran,
  2732. Error **errp)
  2733. {
  2734. uint64_t perm, shared_perm;
  2735. assert(parent_bs->drv);
  2736. GLOBAL_STATE_CODE();
  2737. if (bdrv_recurse_has_child(child_bs, parent_bs)) {
  2738. error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
  2739. child_bs->node_name, child_name, parent_bs->node_name);
  2740. return NULL;
  2741. }
  2742. if (bdrv_is_inactive(child_bs) && !bdrv_is_inactive(parent_bs)) {
  2743. error_setg(errp, "Inactive '%s' can't be a %s child of active '%s'",
  2744. child_bs->node_name, child_name, parent_bs->node_name);
  2745. return NULL;
  2746. }
  2747. bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
  2748. bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
  2749. perm, shared_perm, &perm, &shared_perm);
  2750. return bdrv_attach_child_common(child_bs, child_name, child_class,
  2751. child_role, perm, shared_perm, parent_bs,
  2752. tran, errp);
  2753. }
  2754. /*
  2755. * This function steals the reference to child_bs from the caller.
  2756. * That reference is later dropped by bdrv_root_unref_child().
  2757. *
  2758. * On failure NULL is returned, errp is set and the reference to
  2759. * child_bs is also dropped.
  2760. */
  2761. BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
  2762. const char *child_name,
  2763. const BdrvChildClass *child_class,
  2764. BdrvChildRole child_role,
  2765. uint64_t perm, uint64_t shared_perm,
  2766. void *opaque, Error **errp)
  2767. {
  2768. int ret;
  2769. BdrvChild *child;
  2770. Transaction *tran = tran_new();
  2771. GLOBAL_STATE_CODE();
  2772. child = bdrv_attach_child_common(child_bs, child_name, child_class,
  2773. child_role, perm, shared_perm, opaque,
  2774. tran, errp);
  2775. if (!child) {
  2776. ret = -EINVAL;
  2777. goto out;
  2778. }
  2779. ret = bdrv_refresh_perms(child_bs, tran, errp);
  2780. out:
  2781. tran_finalize(tran, ret);
  2782. bdrv_schedule_unref(child_bs);
  2783. return ret < 0 ? NULL : child;
  2784. }
  2785. /*
  2786. * This function transfers the reference to child_bs from the caller
  2787. * to parent_bs. That reference is later dropped by parent_bs on
  2788. * bdrv_close() or if someone calls bdrv_unref_child().
  2789. *
  2790. * On failure NULL is returned, errp is set and the reference to
  2791. * child_bs is also dropped.
  2792. */
  2793. BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
  2794. BlockDriverState *child_bs,
  2795. const char *child_name,
  2796. const BdrvChildClass *child_class,
  2797. BdrvChildRole child_role,
  2798. Error **errp)
  2799. {
  2800. int ret;
  2801. BdrvChild *child;
  2802. Transaction *tran = tran_new();
  2803. GLOBAL_STATE_CODE();
  2804. child = bdrv_attach_child_noperm(parent_bs, child_bs, child_name,
  2805. child_class, child_role, tran, errp);
  2806. if (!child) {
  2807. ret = -EINVAL;
  2808. goto out;
  2809. }
  2810. ret = bdrv_refresh_perms(parent_bs, tran, errp);
  2811. if (ret < 0) {
  2812. goto out;
  2813. }
  2814. out:
  2815. tran_finalize(tran, ret);
  2816. bdrv_schedule_unref(child_bs);
  2817. return ret < 0 ? NULL : child;
  2818. }
  2819. /* Callers must ensure that child->frozen is false. */
  2820. void bdrv_root_unref_child(BdrvChild *child)
  2821. {
  2822. BlockDriverState *child_bs = child->bs;
  2823. GLOBAL_STATE_CODE();
  2824. bdrv_replace_child_noperm(child, NULL);
  2825. bdrv_child_free(child);
  2826. if (child_bs) {
  2827. /*
  2828. * Update permissions for old node. We're just taking a parent away, so
  2829. * we're loosening restrictions. Errors of permission update are not
  2830. * fatal in this case, ignore them.
  2831. */
  2832. bdrv_refresh_perms(child_bs, NULL, NULL);
  2833. /*
  2834. * When the parent requiring a non-default AioContext is removed, the
  2835. * node moves back to the main AioContext
  2836. */
  2837. bdrv_try_change_aio_context(child_bs, qemu_get_aio_context(), NULL,
  2838. NULL);
  2839. }
  2840. bdrv_schedule_unref(child_bs);
  2841. }
  2842. typedef struct BdrvSetInheritsFrom {
  2843. BlockDriverState *bs;
  2844. BlockDriverState *old_inherits_from;
  2845. } BdrvSetInheritsFrom;
  2846. static void bdrv_set_inherits_from_abort(void *opaque)
  2847. {
  2848. BdrvSetInheritsFrom *s = opaque;
  2849. s->bs->inherits_from = s->old_inherits_from;
  2850. }
  2851. static TransactionActionDrv bdrv_set_inherits_from_drv = {
  2852. .abort = bdrv_set_inherits_from_abort,
  2853. .clean = g_free,
  2854. };
  2855. /* @tran is allowed to be NULL. In this case no rollback is possible */
  2856. static void bdrv_set_inherits_from(BlockDriverState *bs,
  2857. BlockDriverState *new_inherits_from,
  2858. Transaction *tran)
  2859. {
  2860. if (tran) {
  2861. BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
  2862. *s = (BdrvSetInheritsFrom) {
  2863. .bs = bs,
  2864. .old_inherits_from = bs->inherits_from,
  2865. };
  2866. tran_add(tran, &bdrv_set_inherits_from_drv, s);
  2867. }
  2868. bs->inherits_from = new_inherits_from;
  2869. }
  2870. /**
  2871. * Clear all inherits_from pointers from children and grandchildren of
  2872. * @root that point to @root, where necessary.
  2873. * @tran is allowed to be NULL. In this case no rollback is possible
  2874. */
  2875. static void GRAPH_WRLOCK
  2876. bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
  2877. Transaction *tran)
  2878. {
  2879. BdrvChild *c;
  2880. if (child->bs->inherits_from == root) {
  2881. /*
  2882. * Remove inherits_from only when the last reference between root and
  2883. * child->bs goes away.
  2884. */
  2885. QLIST_FOREACH(c, &root->children, next) {
  2886. if (c != child && c->bs == child->bs) {
  2887. break;
  2888. }
  2889. }
  2890. if (c == NULL) {
  2891. bdrv_set_inherits_from(child->bs, NULL, tran);
  2892. }
  2893. }
  2894. QLIST_FOREACH(c, &child->bs->children, next) {
  2895. bdrv_unset_inherits_from(root, c, tran);
  2896. }
  2897. }
  2898. /* Callers must ensure that child->frozen is false. */
  2899. void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
  2900. {
  2901. GLOBAL_STATE_CODE();
  2902. if (child == NULL) {
  2903. return;
  2904. }
  2905. bdrv_unset_inherits_from(parent, child, NULL);
  2906. bdrv_root_unref_child(child);
  2907. }
  2908. static void GRAPH_RDLOCK
  2909. bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
  2910. {
  2911. BdrvChild *c;
  2912. GLOBAL_STATE_CODE();
  2913. QLIST_FOREACH(c, &bs->parents, next_parent) {
  2914. if (c->klass->change_media) {
  2915. c->klass->change_media(c, load);
  2916. }
  2917. }
  2918. }
  2919. /* Return true if you can reach parent going through child->inherits_from
  2920. * recursively. If parent or child are NULL, return false */
  2921. static bool bdrv_inherits_from_recursive(BlockDriverState *child,
  2922. BlockDriverState *parent)
  2923. {
  2924. while (child && child != parent) {
  2925. child = child->inherits_from;
  2926. }
  2927. return child != NULL;
  2928. }
  2929. /*
  2930. * Return the BdrvChildRole for @bs's backing child. bs->backing is
  2931. * mostly used for COW backing children (role = COW), but also for
  2932. * filtered children (role = FILTERED | PRIMARY).
  2933. */
  2934. static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
  2935. {
  2936. if (bs->drv && bs->drv->is_filter) {
  2937. return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
  2938. } else {
  2939. return BDRV_CHILD_COW;
  2940. }
  2941. }
  2942. /*
  2943. * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
  2944. * callers which don't need their own reference any more must call bdrv_unref().
  2945. *
  2946. * If the respective child is already present (i.e. we're detaching a node),
  2947. * that child node must be drained.
  2948. *
  2949. * Function doesn't update permissions, caller is responsible for this.
  2950. *
  2951. * Both @parent_bs and @child_bs can move to a different AioContext in this
  2952. * function.
  2953. *
  2954. * After calling this function, the transaction @tran may only be completed
  2955. * while holding a writer lock for the graph.
  2956. */
  2957. static int GRAPH_WRLOCK
  2958. bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
  2959. BlockDriverState *child_bs,
  2960. bool is_backing,
  2961. Transaction *tran, Error **errp)
  2962. {
  2963. bool update_inherits_from =
  2964. bdrv_inherits_from_recursive(child_bs, parent_bs);
  2965. BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
  2966. BdrvChildRole role;
  2967. GLOBAL_STATE_CODE();
  2968. if (!parent_bs->drv) {
  2969. /*
  2970. * Node without drv is an object without a class :/. TODO: finally fix
  2971. * qcow2 driver to never clear bs->drv and implement format corruption
  2972. * handling in other way.
  2973. */
  2974. error_setg(errp, "Node corrupted");
  2975. return -EINVAL;
  2976. }
  2977. if (child && child->frozen) {
  2978. error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
  2979. child->name, parent_bs->node_name, child->bs->node_name);
  2980. return -EPERM;
  2981. }
  2982. if (is_backing && !parent_bs->drv->is_filter &&
  2983. !parent_bs->drv->supports_backing)
  2984. {
  2985. error_setg(errp, "Driver '%s' of node '%s' does not support backing "
  2986. "files", parent_bs->drv->format_name, parent_bs->node_name);
  2987. return -EINVAL;
  2988. }
  2989. if (parent_bs->drv->is_filter) {
  2990. role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
  2991. } else if (is_backing) {
  2992. role = BDRV_CHILD_COW;
  2993. } else {
  2994. /*
  2995. * We only can use same role as it is in existing child. We don't have
  2996. * infrastructure to determine role of file child in generic way
  2997. */
  2998. if (!child) {
  2999. error_setg(errp, "Cannot set file child to format node without "
  3000. "file child");
  3001. return -EINVAL;
  3002. }
  3003. role = child->role;
  3004. }
  3005. if (child) {
  3006. assert(child->bs->quiesce_counter);
  3007. bdrv_unset_inherits_from(parent_bs, child, tran);
  3008. bdrv_remove_child(child, tran);
  3009. }
  3010. if (!child_bs) {
  3011. goto out;
  3012. }
  3013. child = bdrv_attach_child_noperm(parent_bs, child_bs,
  3014. is_backing ? "backing" : "file",
  3015. &child_of_bds, role,
  3016. tran, errp);
  3017. if (!child) {
  3018. return -EINVAL;
  3019. }
  3020. /*
  3021. * If inherits_from pointed recursively to bs then let's update it to
  3022. * point directly to bs (else it will become NULL).
  3023. */
  3024. if (update_inherits_from) {
  3025. bdrv_set_inherits_from(child_bs, parent_bs, tran);
  3026. }
  3027. out:
  3028. bdrv_refresh_limits(parent_bs, tran, NULL);
  3029. return 0;
  3030. }
  3031. /*
  3032. * Both @bs and @backing_hd can move to a different AioContext in this
  3033. * function.
  3034. *
  3035. * If a backing child is already present (i.e. we're detaching a node), that
  3036. * child node must be drained.
  3037. */
  3038. int bdrv_set_backing_hd_drained(BlockDriverState *bs,
  3039. BlockDriverState *backing_hd,
  3040. Error **errp)
  3041. {
  3042. int ret;
  3043. Transaction *tran = tran_new();
  3044. GLOBAL_STATE_CODE();
  3045. assert(bs->quiesce_counter > 0);
  3046. if (bs->backing) {
  3047. assert(bs->backing->bs->quiesce_counter > 0);
  3048. }
  3049. ret = bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
  3050. if (ret < 0) {
  3051. goto out;
  3052. }
  3053. ret = bdrv_refresh_perms(bs, tran, errp);
  3054. out:
  3055. tran_finalize(tran, ret);
  3056. return ret;
  3057. }
  3058. int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
  3059. Error **errp)
  3060. {
  3061. BlockDriverState *drain_bs;
  3062. int ret;
  3063. GLOBAL_STATE_CODE();
  3064. bdrv_graph_rdlock_main_loop();
  3065. drain_bs = bs->backing ? bs->backing->bs : bs;
  3066. bdrv_graph_rdunlock_main_loop();
  3067. bdrv_ref(drain_bs);
  3068. bdrv_drained_begin(drain_bs);
  3069. bdrv_graph_wrlock();
  3070. ret = bdrv_set_backing_hd_drained(bs, backing_hd, errp);
  3071. bdrv_graph_wrunlock();
  3072. bdrv_drained_end(drain_bs);
  3073. bdrv_unref(drain_bs);
  3074. return ret;
  3075. }
  3076. /*
  3077. * Opens the backing file for a BlockDriverState if not yet open
  3078. *
  3079. * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
  3080. * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
  3081. * itself, all options starting with "${bdref_key}." are considered part of the
  3082. * BlockdevRef.
  3083. *
  3084. * TODO Can this be unified with bdrv_open_image()?
  3085. */
  3086. int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
  3087. const char *bdref_key, Error **errp)
  3088. {
  3089. ERRP_GUARD();
  3090. char *backing_filename = NULL;
  3091. char *bdref_key_dot;
  3092. const char *reference = NULL;
  3093. int ret = 0;
  3094. bool implicit_backing = false;
  3095. BlockDriverState *backing_hd;
  3096. QDict *options;
  3097. QDict *tmp_parent_options = NULL;
  3098. Error *local_err = NULL;
  3099. GLOBAL_STATE_CODE();
  3100. GRAPH_RDLOCK_GUARD_MAINLOOP();
  3101. if (bs->backing != NULL) {
  3102. goto free_exit;
  3103. }
  3104. /* NULL means an empty set of options */
  3105. if (parent_options == NULL) {
  3106. tmp_parent_options = qdict_new();
  3107. parent_options = tmp_parent_options;
  3108. }
  3109. bs->open_flags &= ~BDRV_O_NO_BACKING;
  3110. bdref_key_dot = g_strdup_printf("%s.", bdref_key);
  3111. qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
  3112. g_free(bdref_key_dot);
  3113. /*
  3114. * Caution: while qdict_get_try_str() is fine, getting non-string
  3115. * types would require more care. When @parent_options come from
  3116. * -blockdev or blockdev_add, its members are typed according to
  3117. * the QAPI schema, but when they come from -drive, they're all
  3118. * QString.
  3119. */
  3120. reference = qdict_get_try_str(parent_options, bdref_key);
  3121. if (reference || qdict_haskey(options, "file.filename")) {
  3122. /* keep backing_filename NULL */
  3123. } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
  3124. qobject_unref(options);
  3125. goto free_exit;
  3126. } else {
  3127. if (qdict_size(options) == 0) {
  3128. /* If the user specifies options that do not modify the
  3129. * backing file's behavior, we might still consider it the
  3130. * implicit backing file. But it's easier this way, and
  3131. * just specifying some of the backing BDS's options is
  3132. * only possible with -drive anyway (otherwise the QAPI
  3133. * schema forces the user to specify everything). */
  3134. implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
  3135. }
  3136. backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
  3137. if (local_err) {
  3138. ret = -EINVAL;
  3139. error_propagate(errp, local_err);
  3140. qobject_unref(options);
  3141. goto free_exit;
  3142. }
  3143. }
  3144. if (!bs->drv || !bs->drv->supports_backing) {
  3145. ret = -EINVAL;
  3146. error_setg(errp, "Driver doesn't support backing files");
  3147. qobject_unref(options);
  3148. goto free_exit;
  3149. }
  3150. if (!reference &&
  3151. bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
  3152. qdict_put_str(options, "driver", bs->backing_format);
  3153. }
  3154. backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
  3155. &child_of_bds, bdrv_backing_role(bs), true,
  3156. errp);
  3157. if (!backing_hd) {
  3158. bs->open_flags |= BDRV_O_NO_BACKING;
  3159. error_prepend(errp, "Could not open backing file: ");
  3160. ret = -EINVAL;
  3161. goto free_exit;
  3162. }
  3163. if (implicit_backing) {
  3164. bdrv_refresh_filename(backing_hd);
  3165. pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
  3166. backing_hd->filename);
  3167. }
  3168. /* Hook up the backing file link; drop our reference, bs owns the
  3169. * backing_hd reference now */
  3170. ret = bdrv_set_backing_hd(bs, backing_hd, errp);
  3171. bdrv_unref(backing_hd);
  3172. if (ret < 0) {
  3173. goto free_exit;
  3174. }
  3175. qdict_del(parent_options, bdref_key);
  3176. free_exit:
  3177. g_free(backing_filename);
  3178. qobject_unref(tmp_parent_options);
  3179. return ret;
  3180. }
  3181. static BlockDriverState *
  3182. bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
  3183. BlockDriverState *parent, const BdrvChildClass *child_class,
  3184. BdrvChildRole child_role, bool allow_none,
  3185. bool parse_filename, Error **errp)
  3186. {
  3187. BlockDriverState *bs = NULL;
  3188. QDict *image_options;
  3189. char *bdref_key_dot;
  3190. const char *reference;
  3191. assert(child_class != NULL);
  3192. bdref_key_dot = g_strdup_printf("%s.", bdref_key);
  3193. qdict_extract_subqdict(options, &image_options, bdref_key_dot);
  3194. g_free(bdref_key_dot);
  3195. /*
  3196. * Caution: while qdict_get_try_str() is fine, getting non-string
  3197. * types would require more care. When @options come from
  3198. * -blockdev or blockdev_add, its members are typed according to
  3199. * the QAPI schema, but when they come from -drive, they're all
  3200. * QString.
  3201. */
  3202. reference = qdict_get_try_str(options, bdref_key);
  3203. if (!filename && !reference && !qdict_size(image_options)) {
  3204. if (!allow_none) {
  3205. error_setg(errp, "A block device must be specified for \"%s\"",
  3206. bdref_key);
  3207. }
  3208. qobject_unref(image_options);
  3209. goto done;
  3210. }
  3211. bs = bdrv_open_inherit(filename, reference, image_options, 0,
  3212. parent, child_class, child_role, parse_filename,
  3213. errp);
  3214. if (!bs) {
  3215. goto done;
  3216. }
  3217. done:
  3218. qdict_del(options, bdref_key);
  3219. return bs;
  3220. }
  3221. static BdrvChild *bdrv_open_child_common(const char *filename,
  3222. QDict *options, const char *bdref_key,
  3223. BlockDriverState *parent,
  3224. const BdrvChildClass *child_class,
  3225. BdrvChildRole child_role,
  3226. bool allow_none, bool parse_filename,
  3227. Error **errp)
  3228. {
  3229. BlockDriverState *bs;
  3230. BdrvChild *child;
  3231. GLOBAL_STATE_CODE();
  3232. bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
  3233. child_role, allow_none, parse_filename, errp);
  3234. if (bs == NULL) {
  3235. return NULL;
  3236. }
  3237. bdrv_graph_wrlock();
  3238. child = bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
  3239. errp);
  3240. bdrv_graph_wrunlock();
  3241. return child;
  3242. }
  3243. /*
  3244. * Opens a disk image whose options are given as BlockdevRef in another block
  3245. * device's options.
  3246. *
  3247. * If allow_none is true, no image will be opened if filename is false and no
  3248. * BlockdevRef is given. NULL will be returned, but errp remains unset.
  3249. *
  3250. * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
  3251. * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
  3252. * itself, all options starting with "${bdref_key}." are considered part of the
  3253. * BlockdevRef.
  3254. *
  3255. * The BlockdevRef will be removed from the options QDict.
  3256. *
  3257. * @parent can move to a different AioContext in this function.
  3258. */
  3259. BdrvChild *bdrv_open_child(const char *filename,
  3260. QDict *options, const char *bdref_key,
  3261. BlockDriverState *parent,
  3262. const BdrvChildClass *child_class,
  3263. BdrvChildRole child_role,
  3264. bool allow_none, Error **errp)
  3265. {
  3266. return bdrv_open_child_common(filename, options, bdref_key, parent,
  3267. child_class, child_role, allow_none, false,
  3268. errp);
  3269. }
  3270. /*
  3271. * This does mostly the same as bdrv_open_child(), but for opening the primary
  3272. * child of a node. A notable difference from bdrv_open_child() is that it
  3273. * enables filename parsing for protocol names (including json:).
  3274. *
  3275. * @parent can move to a different AioContext in this function.
  3276. */
  3277. int bdrv_open_file_child(const char *filename,
  3278. QDict *options, const char *bdref_key,
  3279. BlockDriverState *parent, Error **errp)
  3280. {
  3281. BdrvChildRole role;
  3282. /* commit_top and mirror_top don't use this function */
  3283. assert(!parent->drv->filtered_child_is_backing);
  3284. role = parent->drv->is_filter ?
  3285. (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
  3286. if (!bdrv_open_child_common(filename, options, bdref_key, parent,
  3287. &child_of_bds, role, false, true, errp))
  3288. {
  3289. return -EINVAL;
  3290. }
  3291. return 0;
  3292. }
  3293. /*
  3294. * TODO Future callers may need to specify parent/child_class in order for
  3295. * option inheritance to work. Existing callers use it for the root node.
  3296. */
  3297. BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
  3298. {
  3299. BlockDriverState *bs = NULL;
  3300. QObject *obj = NULL;
  3301. QDict *qdict = NULL;
  3302. const char *reference = NULL;
  3303. Visitor *v = NULL;
  3304. GLOBAL_STATE_CODE();
  3305. if (ref->type == QTYPE_QSTRING) {
  3306. reference = ref->u.reference;
  3307. } else {
  3308. BlockdevOptions *options = &ref->u.definition;
  3309. assert(ref->type == QTYPE_QDICT);
  3310. v = qobject_output_visitor_new(&obj);
  3311. visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
  3312. visit_complete(v, &obj);
  3313. qdict = qobject_to(QDict, obj);
  3314. qdict_flatten(qdict);
  3315. /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
  3316. * compatibility with other callers) rather than what we want as the
  3317. * real defaults. Apply the defaults here instead. */
  3318. qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
  3319. qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
  3320. qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
  3321. qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
  3322. }
  3323. bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, false,
  3324. errp);
  3325. obj = NULL;
  3326. qobject_unref(obj);
  3327. visit_free(v);
  3328. return bs;
  3329. }
  3330. static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
  3331. int flags,
  3332. QDict *snapshot_options,
  3333. Error **errp)
  3334. {
  3335. ERRP_GUARD();
  3336. g_autofree char *tmp_filename = NULL;
  3337. int64_t total_size;
  3338. QemuOpts *opts = NULL;
  3339. BlockDriverState *bs_snapshot = NULL;
  3340. int ret;
  3341. GLOBAL_STATE_CODE();
  3342. /* if snapshot, we create a temporary backing file and open it
  3343. instead of opening 'filename' directly */
  3344. /* Get the required size from the image */
  3345. total_size = bdrv_getlength(bs);
  3346. if (total_size < 0) {
  3347. error_setg_errno(errp, -total_size, "Could not get image size");
  3348. goto out;
  3349. }
  3350. /* Create the temporary image */
  3351. tmp_filename = create_tmp_file(errp);
  3352. if (!tmp_filename) {
  3353. goto out;
  3354. }
  3355. opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
  3356. &error_abort);
  3357. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
  3358. ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
  3359. qemu_opts_del(opts);
  3360. if (ret < 0) {
  3361. error_prepend(errp, "Could not create temporary overlay '%s': ",
  3362. tmp_filename);
  3363. goto out;
  3364. }
  3365. /* Prepare options QDict for the temporary file */
  3366. qdict_put_str(snapshot_options, "file.driver", "file");
  3367. qdict_put_str(snapshot_options, "file.filename", tmp_filename);
  3368. qdict_put_str(snapshot_options, "driver", "qcow2");
  3369. bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
  3370. snapshot_options = NULL;
  3371. if (!bs_snapshot) {
  3372. goto out;
  3373. }
  3374. ret = bdrv_append(bs_snapshot, bs, errp);
  3375. if (ret < 0) {
  3376. bs_snapshot = NULL;
  3377. goto out;
  3378. }
  3379. out:
  3380. qobject_unref(snapshot_options);
  3381. return bs_snapshot;
  3382. }
  3383. /*
  3384. * Opens a disk image (raw, qcow2, vmdk, ...)
  3385. *
  3386. * options is a QDict of options to pass to the block drivers, or NULL for an
  3387. * empty set of options. The reference to the QDict belongs to the block layer
  3388. * after the call (even on failure), so if the caller intends to reuse the
  3389. * dictionary, it needs to use qobject_ref() before calling bdrv_open.
  3390. *
  3391. * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
  3392. * If it is not NULL, the referenced BDS will be reused.
  3393. *
  3394. * The reference parameter may be used to specify an existing block device which
  3395. * should be opened. If specified, neither options nor a filename may be given,
  3396. * nor can an existing BDS be reused (that is, *pbs has to be NULL).
  3397. */
  3398. static BlockDriverState * no_coroutine_fn
  3399. bdrv_open_inherit(const char *filename, const char *reference, QDict *options,
  3400. int flags, BlockDriverState *parent,
  3401. const BdrvChildClass *child_class, BdrvChildRole child_role,
  3402. bool parse_filename, Error **errp)
  3403. {
  3404. int ret;
  3405. BlockBackend *file = NULL;
  3406. BlockDriverState *bs;
  3407. BlockDriver *drv = NULL;
  3408. BdrvChild *child;
  3409. const char *drvname;
  3410. const char *backing;
  3411. Error *local_err = NULL;
  3412. QDict *snapshot_options = NULL;
  3413. int snapshot_flags = 0;
  3414. assert(!child_class || !flags);
  3415. assert(!child_class == !parent);
  3416. GLOBAL_STATE_CODE();
  3417. assert(!qemu_in_coroutine());
  3418. /* TODO We'll eventually have to take a writer lock in this function */
  3419. GRAPH_RDLOCK_GUARD_MAINLOOP();
  3420. if (reference) {
  3421. bool options_non_empty = options ? qdict_size(options) : false;
  3422. qobject_unref(options);
  3423. if (filename || options_non_empty) {
  3424. error_setg(errp, "Cannot reference an existing block device with "
  3425. "additional options or a new filename");
  3426. return NULL;
  3427. }
  3428. bs = bdrv_lookup_bs(reference, reference, errp);
  3429. if (!bs) {
  3430. return NULL;
  3431. }
  3432. bdrv_ref(bs);
  3433. return bs;
  3434. }
  3435. bs = bdrv_new();
  3436. /* NULL means an empty set of options */
  3437. if (options == NULL) {
  3438. options = qdict_new();
  3439. }
  3440. /* json: syntax counts as explicit options, as if in the QDict */
  3441. if (parse_filename) {
  3442. parse_json_protocol(options, &filename, &local_err);
  3443. if (local_err) {
  3444. goto fail;
  3445. }
  3446. }
  3447. bs->explicit_options = qdict_clone_shallow(options);
  3448. if (child_class) {
  3449. bool parent_is_format;
  3450. if (parent->drv) {
  3451. parent_is_format = parent->drv->is_format;
  3452. } else {
  3453. /*
  3454. * parent->drv is not set yet because this node is opened for
  3455. * (potential) format probing. That means that @parent is going
  3456. * to be a format node.
  3457. */
  3458. parent_is_format = true;
  3459. }
  3460. bs->inherits_from = parent;
  3461. child_class->inherit_options(child_role, parent_is_format,
  3462. &flags, options,
  3463. parent->open_flags, parent->options);
  3464. }
  3465. ret = bdrv_fill_options(&options, filename, &flags, parse_filename,
  3466. &local_err);
  3467. if (ret < 0) {
  3468. goto fail;
  3469. }
  3470. /*
  3471. * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
  3472. * Caution: getting a boolean member of @options requires care.
  3473. * When @options come from -blockdev or blockdev_add, members are
  3474. * typed according to the QAPI schema, but when they come from
  3475. * -drive, they're all QString.
  3476. */
  3477. if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
  3478. !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
  3479. flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
  3480. } else {
  3481. flags &= ~BDRV_O_RDWR;
  3482. }
  3483. if (flags & BDRV_O_SNAPSHOT) {
  3484. snapshot_options = qdict_new();
  3485. bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
  3486. flags, options);
  3487. /* Let bdrv_backing_options() override "read-only" */
  3488. qdict_del(options, BDRV_OPT_READ_ONLY);
  3489. bdrv_inherited_options(BDRV_CHILD_COW, true,
  3490. &flags, options, flags, options);
  3491. }
  3492. bs->open_flags = flags;
  3493. bs->options = options;
  3494. options = qdict_clone_shallow(options);
  3495. /* Find the right image format driver */
  3496. /* See cautionary note on accessing @options above */
  3497. drvname = qdict_get_try_str(options, "driver");
  3498. if (drvname) {
  3499. drv = bdrv_find_format(drvname);
  3500. if (!drv) {
  3501. error_setg(errp, "Unknown driver: '%s'", drvname);
  3502. goto fail;
  3503. }
  3504. }
  3505. assert(drvname || !(flags & BDRV_O_PROTOCOL));
  3506. /* See cautionary note on accessing @options above */
  3507. backing = qdict_get_try_str(options, "backing");
  3508. if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
  3509. (backing && *backing == '\0'))
  3510. {
  3511. if (backing) {
  3512. warn_report("Use of \"backing\": \"\" is deprecated; "
  3513. "use \"backing\": null instead");
  3514. }
  3515. flags |= BDRV_O_NO_BACKING;
  3516. qdict_del(bs->explicit_options, "backing");
  3517. qdict_del(bs->options, "backing");
  3518. qdict_del(options, "backing");
  3519. }
  3520. /* Open image file without format layer. This BlockBackend is only used for
  3521. * probing, the block drivers will do their own bdrv_open_child() for the
  3522. * same BDS, which is why we put the node name back into options. */
  3523. if ((flags & BDRV_O_PROTOCOL) == 0) {
  3524. BlockDriverState *file_bs;
  3525. file_bs = bdrv_open_child_bs(filename, options, "file", bs,
  3526. &child_of_bds, BDRV_CHILD_IMAGE,
  3527. true, true, &local_err);
  3528. if (local_err) {
  3529. goto fail;
  3530. }
  3531. if (file_bs != NULL) {
  3532. /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
  3533. * looking at the header to guess the image format. This works even
  3534. * in cases where a guest would not see a consistent state. */
  3535. AioContext *ctx = bdrv_get_aio_context(file_bs);
  3536. file = blk_new(ctx, 0, BLK_PERM_ALL);
  3537. blk_insert_bs(file, file_bs, &local_err);
  3538. bdrv_unref(file_bs);
  3539. if (local_err) {
  3540. goto fail;
  3541. }
  3542. qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
  3543. }
  3544. }
  3545. /* Image format probing */
  3546. bs->probed = !drv;
  3547. if (!drv && file) {
  3548. ret = find_image_format(file, filename, &drv, &local_err);
  3549. if (ret < 0) {
  3550. goto fail;
  3551. }
  3552. /*
  3553. * This option update would logically belong in bdrv_fill_options(),
  3554. * but we first need to open bs->file for the probing to work, while
  3555. * opening bs->file already requires the (mostly) final set of options
  3556. * so that cache mode etc. can be inherited.
  3557. *
  3558. * Adding the driver later is somewhat ugly, but it's not an option
  3559. * that would ever be inherited, so it's correct. We just need to make
  3560. * sure to update both bs->options (which has the full effective
  3561. * options for bs) and options (which has file.* already removed).
  3562. */
  3563. qdict_put_str(bs->options, "driver", drv->format_name);
  3564. qdict_put_str(options, "driver", drv->format_name);
  3565. } else if (!drv) {
  3566. error_setg(errp, "Must specify either driver or file");
  3567. goto fail;
  3568. }
  3569. /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
  3570. assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->protocol_name);
  3571. /* file must be NULL if a protocol BDS is about to be created
  3572. * (the inverse results in an error message from bdrv_open_common()) */
  3573. assert(!(flags & BDRV_O_PROTOCOL) || !file);
  3574. /* Open the image */
  3575. ret = bdrv_open_common(bs, file, options, &local_err);
  3576. if (ret < 0) {
  3577. goto fail;
  3578. }
  3579. if (file) {
  3580. blk_unref(file);
  3581. file = NULL;
  3582. }
  3583. /* If there is a backing file, use it */
  3584. if ((flags & BDRV_O_NO_BACKING) == 0) {
  3585. ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
  3586. if (ret < 0) {
  3587. goto close_and_fail;
  3588. }
  3589. }
  3590. /* Remove all children options and references
  3591. * from bs->options and bs->explicit_options */
  3592. QLIST_FOREACH(child, &bs->children, next) {
  3593. char *child_key_dot;
  3594. child_key_dot = g_strdup_printf("%s.", child->name);
  3595. qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
  3596. qdict_extract_subqdict(bs->options, NULL, child_key_dot);
  3597. qdict_del(bs->explicit_options, child->name);
  3598. qdict_del(bs->options, child->name);
  3599. g_free(child_key_dot);
  3600. }
  3601. /* Check if any unknown options were used */
  3602. if (qdict_size(options) != 0) {
  3603. const QDictEntry *entry = qdict_first(options);
  3604. if (flags & BDRV_O_PROTOCOL) {
  3605. error_setg(errp, "Block protocol '%s' doesn't support the option "
  3606. "'%s'", drv->format_name, entry->key);
  3607. } else {
  3608. error_setg(errp,
  3609. "Block format '%s' does not support the option '%s'",
  3610. drv->format_name, entry->key);
  3611. }
  3612. goto close_and_fail;
  3613. }
  3614. bdrv_parent_cb_change_media(bs, true);
  3615. qobject_unref(options);
  3616. options = NULL;
  3617. /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
  3618. * temporary snapshot afterwards. */
  3619. if (snapshot_flags) {
  3620. BlockDriverState *snapshot_bs;
  3621. snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
  3622. snapshot_options, &local_err);
  3623. snapshot_options = NULL;
  3624. if (local_err) {
  3625. goto close_and_fail;
  3626. }
  3627. /* We are not going to return bs but the overlay on top of it
  3628. * (snapshot_bs); thus, we have to drop the strong reference to bs
  3629. * (which we obtained by calling bdrv_new()). bs will not be deleted,
  3630. * though, because the overlay still has a reference to it. */
  3631. bdrv_unref(bs);
  3632. bs = snapshot_bs;
  3633. }
  3634. return bs;
  3635. fail:
  3636. blk_unref(file);
  3637. qobject_unref(snapshot_options);
  3638. qobject_unref(bs->explicit_options);
  3639. qobject_unref(bs->options);
  3640. qobject_unref(options);
  3641. bs->options = NULL;
  3642. bs->explicit_options = NULL;
  3643. bdrv_unref(bs);
  3644. error_propagate(errp, local_err);
  3645. return NULL;
  3646. close_and_fail:
  3647. bdrv_unref(bs);
  3648. qobject_unref(snapshot_options);
  3649. qobject_unref(options);
  3650. error_propagate(errp, local_err);
  3651. return NULL;
  3652. }
  3653. BlockDriverState *bdrv_open(const char *filename, const char *reference,
  3654. QDict *options, int flags, Error **errp)
  3655. {
  3656. GLOBAL_STATE_CODE();
  3657. return bdrv_open_inherit(filename, reference, options, flags, NULL,
  3658. NULL, 0, true, errp);
  3659. }
  3660. /* Return true if the NULL-terminated @list contains @str */
  3661. static bool is_str_in_list(const char *str, const char *const *list)
  3662. {
  3663. if (str && list) {
  3664. int i;
  3665. for (i = 0; list[i] != NULL; i++) {
  3666. if (!strcmp(str, list[i])) {
  3667. return true;
  3668. }
  3669. }
  3670. }
  3671. return false;
  3672. }
  3673. /*
  3674. * Check that every option set in @bs->options is also set in
  3675. * @new_opts.
  3676. *
  3677. * Options listed in the common_options list and in
  3678. * @bs->drv->mutable_opts are skipped.
  3679. *
  3680. * Return 0 on success, otherwise return -EINVAL and set @errp.
  3681. */
  3682. static int bdrv_reset_options_allowed(BlockDriverState *bs,
  3683. const QDict *new_opts, Error **errp)
  3684. {
  3685. const QDictEntry *e;
  3686. /* These options are common to all block drivers and are handled
  3687. * in bdrv_reopen_prepare() so they can be left out of @new_opts */
  3688. const char *const common_options[] = {
  3689. "node-name", "discard", "cache.direct", "cache.no-flush",
  3690. "read-only", "auto-read-only", "detect-zeroes", NULL
  3691. };
  3692. for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
  3693. if (!qdict_haskey(new_opts, e->key) &&
  3694. !is_str_in_list(e->key, common_options) &&
  3695. !is_str_in_list(e->key, bs->drv->mutable_opts)) {
  3696. error_setg(errp, "Option '%s' cannot be reset "
  3697. "to its default value", e->key);
  3698. return -EINVAL;
  3699. }
  3700. }
  3701. return 0;
  3702. }
  3703. /*
  3704. * Returns true if @child can be reached recursively from @bs
  3705. */
  3706. static bool GRAPH_RDLOCK
  3707. bdrv_recurse_has_child(BlockDriverState *bs, BlockDriverState *child)
  3708. {
  3709. BdrvChild *c;
  3710. if (bs == child) {
  3711. return true;
  3712. }
  3713. QLIST_FOREACH(c, &bs->children, next) {
  3714. if (bdrv_recurse_has_child(c->bs, child)) {
  3715. return true;
  3716. }
  3717. }
  3718. return false;
  3719. }
  3720. /*
  3721. * Adds a BlockDriverState to a simple queue for an atomic, transactional
  3722. * reopen of multiple devices.
  3723. *
  3724. * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
  3725. * already performed, or alternatively may be NULL a new BlockReopenQueue will
  3726. * be created and initialized. This newly created BlockReopenQueue should be
  3727. * passed back in for subsequent calls that are intended to be of the same
  3728. * atomic 'set'.
  3729. *
  3730. * bs is the BlockDriverState to add to the reopen queue.
  3731. *
  3732. * options contains the changed options for the associated bs
  3733. * (the BlockReopenQueue takes ownership)
  3734. *
  3735. * flags contains the open flags for the associated bs
  3736. *
  3737. * returns a pointer to bs_queue, which is either the newly allocated
  3738. * bs_queue, or the existing bs_queue being used.
  3739. *
  3740. * bs is drained here and undrained by bdrv_reopen_queue_free().
  3741. *
  3742. * To be called with bs->aio_context locked.
  3743. */
  3744. static BlockReopenQueue * GRAPH_RDLOCK
  3745. bdrv_reopen_queue_child(BlockReopenQueue *bs_queue, BlockDriverState *bs,
  3746. QDict *options, const BdrvChildClass *klass,
  3747. BdrvChildRole role, bool parent_is_format,
  3748. QDict *parent_options, int parent_flags,
  3749. bool keep_old_opts)
  3750. {
  3751. assert(bs != NULL);
  3752. BlockReopenQueueEntry *bs_entry;
  3753. BdrvChild *child;
  3754. QDict *old_options, *explicit_options, *options_copy;
  3755. int flags;
  3756. QemuOpts *opts;
  3757. GLOBAL_STATE_CODE();
  3758. /*
  3759. * Strictly speaking, draining is illegal under GRAPH_RDLOCK. We know that
  3760. * we've been called with bdrv_graph_rdlock_main_loop(), though, so it's ok
  3761. * in practice.
  3762. */
  3763. bdrv_drained_begin(bs);
  3764. if (bs_queue == NULL) {
  3765. bs_queue = g_new0(BlockReopenQueue, 1);
  3766. QTAILQ_INIT(bs_queue);
  3767. }
  3768. if (!options) {
  3769. options = qdict_new();
  3770. }
  3771. /* Check if this BlockDriverState is already in the queue */
  3772. QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
  3773. if (bs == bs_entry->state.bs) {
  3774. break;
  3775. }
  3776. }
  3777. /*
  3778. * Precedence of options:
  3779. * 1. Explicitly passed in options (highest)
  3780. * 2. Retained from explicitly set options of bs
  3781. * 3. Inherited from parent node
  3782. * 4. Retained from effective options of bs
  3783. */
  3784. /* Old explicitly set values (don't overwrite by inherited value) */
  3785. if (bs_entry || keep_old_opts) {
  3786. old_options = qdict_clone_shallow(bs_entry ?
  3787. bs_entry->state.explicit_options :
  3788. bs->explicit_options);
  3789. bdrv_join_options(bs, options, old_options);
  3790. qobject_unref(old_options);
  3791. }
  3792. explicit_options = qdict_clone_shallow(options);
  3793. /* Inherit from parent node */
  3794. if (parent_options) {
  3795. flags = 0;
  3796. klass->inherit_options(role, parent_is_format, &flags, options,
  3797. parent_flags, parent_options);
  3798. } else {
  3799. flags = bdrv_get_flags(bs);
  3800. }
  3801. if (keep_old_opts) {
  3802. /* Old values are used for options that aren't set yet */
  3803. old_options = qdict_clone_shallow(bs->options);
  3804. bdrv_join_options(bs, options, old_options);
  3805. qobject_unref(old_options);
  3806. }
  3807. /* We have the final set of options so let's update the flags */
  3808. options_copy = qdict_clone_shallow(options);
  3809. opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
  3810. qemu_opts_absorb_qdict(opts, options_copy, NULL);
  3811. update_flags_from_options(&flags, opts);
  3812. qemu_opts_del(opts);
  3813. qobject_unref(options_copy);
  3814. /* bdrv_open_inherit() sets and clears some additional flags internally */
  3815. flags &= ~BDRV_O_PROTOCOL;
  3816. if (flags & BDRV_O_RDWR) {
  3817. flags |= BDRV_O_ALLOW_RDWR;
  3818. }
  3819. if (!bs_entry) {
  3820. bs_entry = g_new0(BlockReopenQueueEntry, 1);
  3821. QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
  3822. } else {
  3823. qobject_unref(bs_entry->state.options);
  3824. qobject_unref(bs_entry->state.explicit_options);
  3825. }
  3826. bs_entry->state.bs = bs;
  3827. bs_entry->state.options = options;
  3828. bs_entry->state.explicit_options = explicit_options;
  3829. bs_entry->state.flags = flags;
  3830. /*
  3831. * If keep_old_opts is false then it means that unspecified
  3832. * options must be reset to their original value. We don't allow
  3833. * resetting 'backing' but we need to know if the option is
  3834. * missing in order to decide if we have to return an error.
  3835. */
  3836. if (!keep_old_opts) {
  3837. bs_entry->state.backing_missing =
  3838. !qdict_haskey(options, "backing") &&
  3839. !qdict_haskey(options, "backing.driver");
  3840. }
  3841. QLIST_FOREACH(child, &bs->children, next) {
  3842. QDict *new_child_options = NULL;
  3843. bool child_keep_old = keep_old_opts;
  3844. /* reopen can only change the options of block devices that were
  3845. * implicitly created and inherited options. For other (referenced)
  3846. * block devices, a syntax like "backing.foo" results in an error. */
  3847. if (child->bs->inherits_from != bs) {
  3848. continue;
  3849. }
  3850. /* Check if the options contain a child reference */
  3851. if (qdict_haskey(options, child->name)) {
  3852. const char *childref = qdict_get_try_str(options, child->name);
  3853. /*
  3854. * The current child must not be reopened if the child
  3855. * reference is null or points to a different node.
  3856. */
  3857. if (g_strcmp0(childref, child->bs->node_name)) {
  3858. continue;
  3859. }
  3860. /*
  3861. * If the child reference points to the current child then
  3862. * reopen it with its existing set of options (note that
  3863. * it can still inherit new options from the parent).
  3864. */
  3865. child_keep_old = true;
  3866. } else {
  3867. /* Extract child options ("child-name.*") */
  3868. char *child_key_dot = g_strdup_printf("%s.", child->name);
  3869. qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
  3870. qdict_extract_subqdict(options, &new_child_options, child_key_dot);
  3871. g_free(child_key_dot);
  3872. }
  3873. bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
  3874. child->klass, child->role, bs->drv->is_format,
  3875. options, flags, child_keep_old);
  3876. }
  3877. return bs_queue;
  3878. }
  3879. /* To be called with bs->aio_context locked */
  3880. BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
  3881. BlockDriverState *bs,
  3882. QDict *options, bool keep_old_opts)
  3883. {
  3884. GLOBAL_STATE_CODE();
  3885. GRAPH_RDLOCK_GUARD_MAINLOOP();
  3886. return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
  3887. NULL, 0, keep_old_opts);
  3888. }
  3889. void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
  3890. {
  3891. GLOBAL_STATE_CODE();
  3892. if (bs_queue) {
  3893. BlockReopenQueueEntry *bs_entry, *next;
  3894. QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
  3895. bdrv_drained_end(bs_entry->state.bs);
  3896. qobject_unref(bs_entry->state.explicit_options);
  3897. qobject_unref(bs_entry->state.options);
  3898. g_free(bs_entry);
  3899. }
  3900. g_free(bs_queue);
  3901. }
  3902. }
  3903. /*
  3904. * Reopen multiple BlockDriverStates atomically & transactionally.
  3905. *
  3906. * The queue passed in (bs_queue) must have been built up previous
  3907. * via bdrv_reopen_queue().
  3908. *
  3909. * Reopens all BDS specified in the queue, with the appropriate
  3910. * flags. All devices are prepared for reopen, and failure of any
  3911. * device will cause all device changes to be abandoned, and intermediate
  3912. * data cleaned up.
  3913. *
  3914. * If all devices prepare successfully, then the changes are committed
  3915. * to all devices.
  3916. *
  3917. * All affected nodes must be drained between bdrv_reopen_queue() and
  3918. * bdrv_reopen_multiple().
  3919. *
  3920. * To be called from the main thread, with all other AioContexts unlocked.
  3921. */
  3922. int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
  3923. {
  3924. int ret = -1;
  3925. BlockReopenQueueEntry *bs_entry, *next;
  3926. Transaction *tran = tran_new();
  3927. g_autoptr(GSList) refresh_list = NULL;
  3928. assert(qemu_get_current_aio_context() == qemu_get_aio_context());
  3929. assert(bs_queue != NULL);
  3930. GLOBAL_STATE_CODE();
  3931. QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
  3932. ret = bdrv_flush(bs_entry->state.bs);
  3933. if (ret < 0) {
  3934. error_setg_errno(errp, -ret, "Error flushing drive");
  3935. goto abort;
  3936. }
  3937. }
  3938. QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
  3939. assert(bs_entry->state.bs->quiesce_counter > 0);
  3940. ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
  3941. if (ret < 0) {
  3942. goto abort;
  3943. }
  3944. bs_entry->prepared = true;
  3945. }
  3946. QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
  3947. BDRVReopenState *state = &bs_entry->state;
  3948. refresh_list = g_slist_prepend(refresh_list, state->bs);
  3949. if (state->old_backing_bs) {
  3950. refresh_list = g_slist_prepend(refresh_list, state->old_backing_bs);
  3951. }
  3952. if (state->old_file_bs) {
  3953. refresh_list = g_slist_prepend(refresh_list, state->old_file_bs);
  3954. }
  3955. }
  3956. /*
  3957. * Note that file-posix driver rely on permission update done during reopen
  3958. * (even if no permission changed), because it wants "new" permissions for
  3959. * reconfiguring the fd and that's why it does it in raw_check_perm(), not
  3960. * in raw_reopen_prepare() which is called with "old" permissions.
  3961. */
  3962. bdrv_graph_rdlock_main_loop();
  3963. ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
  3964. bdrv_graph_rdunlock_main_loop();
  3965. if (ret < 0) {
  3966. goto abort;
  3967. }
  3968. /*
  3969. * If we reach this point, we have success and just need to apply the
  3970. * changes.
  3971. *
  3972. * Reverse order is used to comfort qcow2 driver: on commit it need to write
  3973. * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
  3974. * children are usually goes after parents in reopen-queue, so go from last
  3975. * to first element.
  3976. */
  3977. QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
  3978. bdrv_reopen_commit(&bs_entry->state);
  3979. }
  3980. bdrv_graph_wrlock();
  3981. tran_commit(tran);
  3982. bdrv_graph_wrunlock();
  3983. QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
  3984. BlockDriverState *bs = bs_entry->state.bs;
  3985. if (bs->drv->bdrv_reopen_commit_post) {
  3986. bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
  3987. }
  3988. }
  3989. ret = 0;
  3990. goto cleanup;
  3991. abort:
  3992. bdrv_graph_wrlock();
  3993. tran_abort(tran);
  3994. bdrv_graph_wrunlock();
  3995. QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
  3996. if (bs_entry->prepared) {
  3997. bdrv_reopen_abort(&bs_entry->state);
  3998. }
  3999. }
  4000. cleanup:
  4001. bdrv_reopen_queue_free(bs_queue);
  4002. return ret;
  4003. }
  4004. int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
  4005. Error **errp)
  4006. {
  4007. BlockReopenQueue *queue;
  4008. GLOBAL_STATE_CODE();
  4009. queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
  4010. return bdrv_reopen_multiple(queue, errp);
  4011. }
  4012. int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
  4013. Error **errp)
  4014. {
  4015. QDict *opts = qdict_new();
  4016. GLOBAL_STATE_CODE();
  4017. qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
  4018. return bdrv_reopen(bs, opts, true, errp);
  4019. }
  4020. /*
  4021. * Take a BDRVReopenState and check if the value of 'backing' in the
  4022. * reopen_state->options QDict is valid or not.
  4023. *
  4024. * If 'backing' is missing from the QDict then return 0.
  4025. *
  4026. * If 'backing' contains the node name of the backing file of
  4027. * reopen_state->bs then return 0.
  4028. *
  4029. * If 'backing' contains a different node name (or is null) then check
  4030. * whether the current backing file can be replaced with the new one.
  4031. * If that's the case then reopen_state->replace_backing_bs is set to
  4032. * true and reopen_state->new_backing_bs contains a pointer to the new
  4033. * backing BlockDriverState (or NULL).
  4034. *
  4035. * After calling this function, the transaction @tran may only be completed
  4036. * while holding a writer lock for the graph.
  4037. *
  4038. * Return 0 on success, otherwise return < 0 and set @errp.
  4039. *
  4040. * @reopen_state->bs can move to a different AioContext in this function.
  4041. */
  4042. static int GRAPH_UNLOCKED
  4043. bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
  4044. bool is_backing, Transaction *tran,
  4045. Error **errp)
  4046. {
  4047. BlockDriverState *bs = reopen_state->bs;
  4048. BlockDriverState *new_child_bs;
  4049. BlockDriverState *old_child_bs;
  4050. const char *child_name = is_backing ? "backing" : "file";
  4051. QObject *value;
  4052. const char *str;
  4053. bool has_child;
  4054. int ret;
  4055. GLOBAL_STATE_CODE();
  4056. value = qdict_get(reopen_state->options, child_name);
  4057. if (value == NULL) {
  4058. return 0;
  4059. }
  4060. bdrv_graph_rdlock_main_loop();
  4061. switch (qobject_type(value)) {
  4062. case QTYPE_QNULL:
  4063. assert(is_backing); /* The 'file' option does not allow a null value */
  4064. new_child_bs = NULL;
  4065. break;
  4066. case QTYPE_QSTRING:
  4067. str = qstring_get_str(qobject_to(QString, value));
  4068. new_child_bs = bdrv_lookup_bs(NULL, str, errp);
  4069. if (new_child_bs == NULL) {
  4070. ret = -EINVAL;
  4071. goto out_rdlock;
  4072. }
  4073. has_child = bdrv_recurse_has_child(new_child_bs, bs);
  4074. if (has_child) {
  4075. error_setg(errp, "Making '%s' a %s child of '%s' would create a "
  4076. "cycle", str, child_name, bs->node_name);
  4077. ret = -EINVAL;
  4078. goto out_rdlock;
  4079. }
  4080. break;
  4081. default:
  4082. /*
  4083. * The options QDict has been flattened, so 'backing' and 'file'
  4084. * do not allow any other data type here.
  4085. */
  4086. g_assert_not_reached();
  4087. }
  4088. old_child_bs = is_backing ? child_bs(bs->backing) : child_bs(bs->file);
  4089. if (old_child_bs == new_child_bs) {
  4090. ret = 0;
  4091. goto out_rdlock;
  4092. }
  4093. if (old_child_bs) {
  4094. if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
  4095. ret = 0;
  4096. goto out_rdlock;
  4097. }
  4098. if (old_child_bs->implicit) {
  4099. error_setg(errp, "Cannot replace implicit %s child of %s",
  4100. child_name, bs->node_name);
  4101. ret = -EPERM;
  4102. goto out_rdlock;
  4103. }
  4104. }
  4105. if (bs->drv->is_filter && !old_child_bs) {
  4106. /*
  4107. * Filters always have a file or a backing child, so we are trying to
  4108. * change wrong child
  4109. */
  4110. error_setg(errp, "'%s' is a %s filter node that does not support a "
  4111. "%s child", bs->node_name, bs->drv->format_name, child_name);
  4112. ret = -EINVAL;
  4113. goto out_rdlock;
  4114. }
  4115. if (is_backing) {
  4116. reopen_state->old_backing_bs = old_child_bs;
  4117. } else {
  4118. reopen_state->old_file_bs = old_child_bs;
  4119. }
  4120. if (old_child_bs) {
  4121. bdrv_ref(old_child_bs);
  4122. bdrv_drained_begin(old_child_bs);
  4123. }
  4124. bdrv_graph_rdunlock_main_loop();
  4125. bdrv_graph_wrlock();
  4126. ret = bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
  4127. tran, errp);
  4128. bdrv_graph_wrunlock();
  4129. if (old_child_bs) {
  4130. bdrv_drained_end(old_child_bs);
  4131. bdrv_unref(old_child_bs);
  4132. }
  4133. return ret;
  4134. out_rdlock:
  4135. bdrv_graph_rdunlock_main_loop();
  4136. return ret;
  4137. }
  4138. /*
  4139. * Prepares a BlockDriverState for reopen. All changes are staged in the
  4140. * 'opaque' field of the BDRVReopenState, which is used and allocated by
  4141. * the block driver layer .bdrv_reopen_prepare()
  4142. *
  4143. * bs is the BlockDriverState to reopen
  4144. * flags are the new open flags
  4145. * queue is the reopen queue
  4146. *
  4147. * Returns 0 on success, non-zero on error. On error errp will be set
  4148. * as well.
  4149. *
  4150. * On failure, bdrv_reopen_abort() will be called to clean up any data.
  4151. * It is the responsibility of the caller to then call the abort() or
  4152. * commit() for any other BDS that have been left in a prepare() state
  4153. *
  4154. * After calling this function, the transaction @change_child_tran may only be
  4155. * completed while holding a writer lock for the graph.
  4156. */
  4157. static int GRAPH_UNLOCKED
  4158. bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
  4159. Transaction *change_child_tran, Error **errp)
  4160. {
  4161. int ret = -1;
  4162. int old_flags;
  4163. Error *local_err = NULL;
  4164. BlockDriver *drv;
  4165. QemuOpts *opts;
  4166. QDict *orig_reopen_opts;
  4167. char *discard = NULL;
  4168. bool read_only;
  4169. bool drv_prepared = false;
  4170. assert(reopen_state != NULL);
  4171. assert(reopen_state->bs->drv != NULL);
  4172. GLOBAL_STATE_CODE();
  4173. drv = reopen_state->bs->drv;
  4174. /* This function and each driver's bdrv_reopen_prepare() remove
  4175. * entries from reopen_state->options as they are processed, so
  4176. * we need to make a copy of the original QDict. */
  4177. orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
  4178. /* Process generic block layer options */
  4179. opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
  4180. if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
  4181. ret = -EINVAL;
  4182. goto error;
  4183. }
  4184. /* This was already called in bdrv_reopen_queue_child() so the flags
  4185. * are up-to-date. This time we simply want to remove the options from
  4186. * QemuOpts in order to indicate that they have been processed. */
  4187. old_flags = reopen_state->flags;
  4188. update_flags_from_options(&reopen_state->flags, opts);
  4189. assert(old_flags == reopen_state->flags);
  4190. discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
  4191. if (discard != NULL) {
  4192. if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
  4193. error_setg(errp, "Invalid discard option");
  4194. ret = -EINVAL;
  4195. goto error;
  4196. }
  4197. }
  4198. reopen_state->detect_zeroes =
  4199. bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
  4200. if (local_err) {
  4201. error_propagate(errp, local_err);
  4202. ret = -EINVAL;
  4203. goto error;
  4204. }
  4205. /* All other options (including node-name and driver) must be unchanged.
  4206. * Put them back into the QDict, so that they are checked at the end
  4207. * of this function. */
  4208. qemu_opts_to_qdict(opts, reopen_state->options);
  4209. /* If we are to stay read-only, do not allow permission change
  4210. * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
  4211. * not set, or if the BDS still has copy_on_read enabled */
  4212. read_only = !(reopen_state->flags & BDRV_O_RDWR);
  4213. bdrv_graph_rdlock_main_loop();
  4214. ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
  4215. bdrv_graph_rdunlock_main_loop();
  4216. if (local_err) {
  4217. error_propagate(errp, local_err);
  4218. goto error;
  4219. }
  4220. if (drv->bdrv_reopen_prepare) {
  4221. /*
  4222. * If a driver-specific option is missing, it means that we
  4223. * should reset it to its default value.
  4224. * But not all options allow that, so we need to check it first.
  4225. */
  4226. ret = bdrv_reset_options_allowed(reopen_state->bs,
  4227. reopen_state->options, errp);
  4228. if (ret) {
  4229. goto error;
  4230. }
  4231. ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
  4232. if (ret) {
  4233. if (local_err != NULL) {
  4234. error_propagate(errp, local_err);
  4235. } else {
  4236. bdrv_graph_rdlock_main_loop();
  4237. bdrv_refresh_filename(reopen_state->bs);
  4238. bdrv_graph_rdunlock_main_loop();
  4239. error_setg(errp, "failed while preparing to reopen image '%s'",
  4240. reopen_state->bs->filename);
  4241. }
  4242. goto error;
  4243. }
  4244. } else {
  4245. /* It is currently mandatory to have a bdrv_reopen_prepare()
  4246. * handler for each supported drv. */
  4247. bdrv_graph_rdlock_main_loop();
  4248. error_setg(errp, "Block format '%s' used by node '%s' "
  4249. "does not support reopening files", drv->format_name,
  4250. bdrv_get_device_or_node_name(reopen_state->bs));
  4251. bdrv_graph_rdunlock_main_loop();
  4252. ret = -1;
  4253. goto error;
  4254. }
  4255. drv_prepared = true;
  4256. /*
  4257. * We must provide the 'backing' option if the BDS has a backing
  4258. * file or if the image file has a backing file name as part of
  4259. * its metadata. Otherwise the 'backing' option can be omitted.
  4260. */
  4261. bdrv_graph_rdlock_main_loop();
  4262. if (drv->supports_backing && reopen_state->backing_missing &&
  4263. (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
  4264. error_setg(errp, "backing is missing for '%s'",
  4265. reopen_state->bs->node_name);
  4266. bdrv_graph_rdunlock_main_loop();
  4267. ret = -EINVAL;
  4268. goto error;
  4269. }
  4270. bdrv_graph_rdunlock_main_loop();
  4271. /*
  4272. * Allow changing the 'backing' option. The new value can be
  4273. * either a reference to an existing node (using its node name)
  4274. * or NULL to simply detach the current backing file.
  4275. */
  4276. ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
  4277. change_child_tran, errp);
  4278. if (ret < 0) {
  4279. goto error;
  4280. }
  4281. qdict_del(reopen_state->options, "backing");
  4282. /* Allow changing the 'file' option. In this case NULL is not allowed */
  4283. ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
  4284. change_child_tran, errp);
  4285. if (ret < 0) {
  4286. goto error;
  4287. }
  4288. qdict_del(reopen_state->options, "file");
  4289. /* Options that are not handled are only okay if they are unchanged
  4290. * compared to the old state. It is expected that some options are only
  4291. * used for the initial open, but not reopen (e.g. filename) */
  4292. if (qdict_size(reopen_state->options)) {
  4293. const QDictEntry *entry = qdict_first(reopen_state->options);
  4294. GRAPH_RDLOCK_GUARD_MAINLOOP();
  4295. do {
  4296. QObject *new = entry->value;
  4297. QObject *old = qdict_get(reopen_state->bs->options, entry->key);
  4298. /* Allow child references (child_name=node_name) as long as they
  4299. * point to the current child (i.e. everything stays the same). */
  4300. if (qobject_type(new) == QTYPE_QSTRING) {
  4301. BdrvChild *child;
  4302. QLIST_FOREACH(child, &reopen_state->bs->children, next) {
  4303. if (!strcmp(child->name, entry->key)) {
  4304. break;
  4305. }
  4306. }
  4307. if (child) {
  4308. if (!strcmp(child->bs->node_name,
  4309. qstring_get_str(qobject_to(QString, new)))) {
  4310. continue; /* Found child with this name, skip option */
  4311. }
  4312. }
  4313. }
  4314. /*
  4315. * TODO: When using -drive to specify blockdev options, all values
  4316. * will be strings; however, when using -blockdev, blockdev-add or
  4317. * filenames using the json:{} pseudo-protocol, they will be
  4318. * correctly typed.
  4319. * In contrast, reopening options are (currently) always strings
  4320. * (because you can only specify them through qemu-io; all other
  4321. * callers do not specify any options).
  4322. * Therefore, when using anything other than -drive to create a BDS,
  4323. * this cannot detect non-string options as unchanged, because
  4324. * qobject_is_equal() always returns false for objects of different
  4325. * type. In the future, this should be remedied by correctly typing
  4326. * all options. For now, this is not too big of an issue because
  4327. * the user can simply omit options which cannot be changed anyway,
  4328. * so they will stay unchanged.
  4329. */
  4330. if (!qobject_is_equal(new, old)) {
  4331. error_setg(errp, "Cannot change the option '%s'", entry->key);
  4332. ret = -EINVAL;
  4333. goto error;
  4334. }
  4335. } while ((entry = qdict_next(reopen_state->options, entry)));
  4336. }
  4337. ret = 0;
  4338. /* Restore the original reopen_state->options QDict */
  4339. qobject_unref(reopen_state->options);
  4340. reopen_state->options = qobject_ref(orig_reopen_opts);
  4341. error:
  4342. if (ret < 0 && drv_prepared) {
  4343. /* drv->bdrv_reopen_prepare() has succeeded, so we need to
  4344. * call drv->bdrv_reopen_abort() before signaling an error
  4345. * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
  4346. * when the respective bdrv_reopen_prepare() has failed) */
  4347. if (drv->bdrv_reopen_abort) {
  4348. drv->bdrv_reopen_abort(reopen_state);
  4349. }
  4350. }
  4351. qemu_opts_del(opts);
  4352. qobject_unref(orig_reopen_opts);
  4353. g_free(discard);
  4354. return ret;
  4355. }
  4356. /*
  4357. * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
  4358. * makes them final by swapping the staging BlockDriverState contents into
  4359. * the active BlockDriverState contents.
  4360. */
  4361. static void GRAPH_UNLOCKED bdrv_reopen_commit(BDRVReopenState *reopen_state)
  4362. {
  4363. BlockDriver *drv;
  4364. BlockDriverState *bs;
  4365. BdrvChild *child;
  4366. assert(reopen_state != NULL);
  4367. bs = reopen_state->bs;
  4368. drv = bs->drv;
  4369. assert(drv != NULL);
  4370. GLOBAL_STATE_CODE();
  4371. /* If there are any driver level actions to take */
  4372. if (drv->bdrv_reopen_commit) {
  4373. drv->bdrv_reopen_commit(reopen_state);
  4374. }
  4375. GRAPH_RDLOCK_GUARD_MAINLOOP();
  4376. /* set BDS specific flags now */
  4377. qobject_unref(bs->explicit_options);
  4378. qobject_unref(bs->options);
  4379. qobject_ref(reopen_state->explicit_options);
  4380. qobject_ref(reopen_state->options);
  4381. bs->explicit_options = reopen_state->explicit_options;
  4382. bs->options = reopen_state->options;
  4383. bs->open_flags = reopen_state->flags;
  4384. bs->detect_zeroes = reopen_state->detect_zeroes;
  4385. /* Remove child references from bs->options and bs->explicit_options.
  4386. * Child options were already removed in bdrv_reopen_queue_child() */
  4387. QLIST_FOREACH(child, &bs->children, next) {
  4388. qdict_del(bs->explicit_options, child->name);
  4389. qdict_del(bs->options, child->name);
  4390. }
  4391. /* backing is probably removed, so it's not handled by previous loop */
  4392. qdict_del(bs->explicit_options, "backing");
  4393. qdict_del(bs->options, "backing");
  4394. bdrv_refresh_limits(bs, NULL, NULL);
  4395. bdrv_refresh_total_sectors(bs, bs->total_sectors);
  4396. }
  4397. /*
  4398. * Abort the reopen, and delete and free the staged changes in
  4399. * reopen_state
  4400. */
  4401. static void GRAPH_UNLOCKED bdrv_reopen_abort(BDRVReopenState *reopen_state)
  4402. {
  4403. BlockDriver *drv;
  4404. assert(reopen_state != NULL);
  4405. drv = reopen_state->bs->drv;
  4406. assert(drv != NULL);
  4407. GLOBAL_STATE_CODE();
  4408. if (drv->bdrv_reopen_abort) {
  4409. drv->bdrv_reopen_abort(reopen_state);
  4410. }
  4411. }
  4412. static void bdrv_close(BlockDriverState *bs)
  4413. {
  4414. BdrvAioNotifier *ban, *ban_next;
  4415. BdrvChild *child, *next;
  4416. GLOBAL_STATE_CODE();
  4417. assert(!bs->refcnt);
  4418. bdrv_drained_begin(bs); /* complete I/O */
  4419. bdrv_flush(bs);
  4420. bdrv_drain(bs); /* in case flush left pending I/O */
  4421. if (bs->drv) {
  4422. if (bs->drv->bdrv_close) {
  4423. /* Must unfreeze all children, so bdrv_unref_child() works */
  4424. bs->drv->bdrv_close(bs);
  4425. }
  4426. bs->drv = NULL;
  4427. }
  4428. bdrv_graph_wrlock();
  4429. QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
  4430. bdrv_unref_child(bs, child);
  4431. }
  4432. assert(!bs->backing);
  4433. assert(!bs->file);
  4434. bdrv_graph_wrunlock();
  4435. g_free(bs->opaque);
  4436. bs->opaque = NULL;
  4437. qatomic_set(&bs->copy_on_read, 0);
  4438. bs->backing_file[0] = '\0';
  4439. bs->backing_format[0] = '\0';
  4440. bs->total_sectors = 0;
  4441. bs->encrypted = false;
  4442. bs->sg = false;
  4443. qobject_unref(bs->options);
  4444. qobject_unref(bs->explicit_options);
  4445. bs->options = NULL;
  4446. bs->explicit_options = NULL;
  4447. qobject_unref(bs->full_open_options);
  4448. bs->full_open_options = NULL;
  4449. g_free(bs->block_status_cache);
  4450. bs->block_status_cache = NULL;
  4451. bdrv_release_named_dirty_bitmaps(bs);
  4452. assert(QLIST_EMPTY(&bs->dirty_bitmaps));
  4453. QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
  4454. g_free(ban);
  4455. }
  4456. QLIST_INIT(&bs->aio_notifiers);
  4457. bdrv_drained_end(bs);
  4458. /*
  4459. * If we're still inside some bdrv_drain_all_begin()/end() sections, end
  4460. * them now since this BDS won't exist anymore when bdrv_drain_all_end()
  4461. * gets called.
  4462. */
  4463. if (bs->quiesce_counter) {
  4464. bdrv_drain_all_end_quiesce(bs);
  4465. }
  4466. }
  4467. void bdrv_close_all(void)
  4468. {
  4469. GLOBAL_STATE_CODE();
  4470. assert(job_next(NULL) == NULL);
  4471. /* Drop references from requests still in flight, such as canceled block
  4472. * jobs whose AIO context has not been polled yet */
  4473. bdrv_drain_all();
  4474. blk_remove_all_bs();
  4475. blockdev_close_all_bdrv_states();
  4476. assert(QTAILQ_EMPTY(&all_bdrv_states));
  4477. }
  4478. static bool GRAPH_RDLOCK should_update_child(BdrvChild *c, BlockDriverState *to)
  4479. {
  4480. GQueue *queue;
  4481. GHashTable *found;
  4482. bool ret;
  4483. if (c->klass->stay_at_node) {
  4484. return false;
  4485. }
  4486. /* If the child @c belongs to the BDS @to, replacing the current
  4487. * c->bs by @to would mean to create a loop.
  4488. *
  4489. * Such a case occurs when appending a BDS to a backing chain.
  4490. * For instance, imagine the following chain:
  4491. *
  4492. * guest device -> node A -> further backing chain...
  4493. *
  4494. * Now we create a new BDS B which we want to put on top of this
  4495. * chain, so we first attach A as its backing node:
  4496. *
  4497. * node B
  4498. * |
  4499. * v
  4500. * guest device -> node A -> further backing chain...
  4501. *
  4502. * Finally we want to replace A by B. When doing that, we want to
  4503. * replace all pointers to A by pointers to B -- except for the
  4504. * pointer from B because (1) that would create a loop, and (2)
  4505. * that pointer should simply stay intact:
  4506. *
  4507. * guest device -> node B
  4508. * |
  4509. * v
  4510. * node A -> further backing chain...
  4511. *
  4512. * In general, when replacing a node A (c->bs) by a node B (@to),
  4513. * if A is a child of B, that means we cannot replace A by B there
  4514. * because that would create a loop. Silently detaching A from B
  4515. * is also not really an option. So overall just leaving A in
  4516. * place there is the most sensible choice.
  4517. *
  4518. * We would also create a loop in any cases where @c is only
  4519. * indirectly referenced by @to. Prevent this by returning false
  4520. * if @c is found (by breadth-first search) anywhere in the whole
  4521. * subtree of @to.
  4522. */
  4523. ret = true;
  4524. found = g_hash_table_new(NULL, NULL);
  4525. g_hash_table_add(found, to);
  4526. queue = g_queue_new();
  4527. g_queue_push_tail(queue, to);
  4528. while (!g_queue_is_empty(queue)) {
  4529. BlockDriverState *v = g_queue_pop_head(queue);
  4530. BdrvChild *c2;
  4531. QLIST_FOREACH(c2, &v->children, next) {
  4532. if (c2 == c) {
  4533. ret = false;
  4534. break;
  4535. }
  4536. if (g_hash_table_contains(found, c2->bs)) {
  4537. continue;
  4538. }
  4539. g_queue_push_tail(queue, c2->bs);
  4540. g_hash_table_add(found, c2->bs);
  4541. }
  4542. }
  4543. g_queue_free(queue);
  4544. g_hash_table_destroy(found);
  4545. return ret;
  4546. }
  4547. static void bdrv_remove_child_commit(void *opaque)
  4548. {
  4549. GLOBAL_STATE_CODE();
  4550. bdrv_child_free(opaque);
  4551. }
  4552. static TransactionActionDrv bdrv_remove_child_drv = {
  4553. .commit = bdrv_remove_child_commit,
  4554. };
  4555. /*
  4556. * Function doesn't update permissions, caller is responsible for this.
  4557. *
  4558. * @child->bs (if non-NULL) must be drained.
  4559. *
  4560. * After calling this function, the transaction @tran may only be completed
  4561. * while holding a writer lock for the graph.
  4562. */
  4563. static void GRAPH_WRLOCK bdrv_remove_child(BdrvChild *child, Transaction *tran)
  4564. {
  4565. if (!child) {
  4566. return;
  4567. }
  4568. if (child->bs) {
  4569. assert(child->quiesced_parent);
  4570. bdrv_replace_child_tran(child, NULL, tran);
  4571. }
  4572. tran_add(tran, &bdrv_remove_child_drv, child);
  4573. }
  4574. /*
  4575. * Both @from and @to (if non-NULL) must be drained. @to must be kept drained
  4576. * until the transaction is completed.
  4577. *
  4578. * After calling this function, the transaction @tran may only be completed
  4579. * while holding a writer lock for the graph.
  4580. */
  4581. static int GRAPH_WRLOCK
  4582. bdrv_replace_node_noperm(BlockDriverState *from,
  4583. BlockDriverState *to,
  4584. bool auto_skip, Transaction *tran,
  4585. Error **errp)
  4586. {
  4587. BdrvChild *c, *next;
  4588. GLOBAL_STATE_CODE();
  4589. assert(from->quiesce_counter);
  4590. assert(to->quiesce_counter);
  4591. QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
  4592. assert(c->bs == from);
  4593. if (!should_update_child(c, to)) {
  4594. if (auto_skip) {
  4595. continue;
  4596. }
  4597. error_setg(errp, "Should not change '%s' link to '%s'",
  4598. c->name, from->node_name);
  4599. return -EINVAL;
  4600. }
  4601. if (c->frozen) {
  4602. error_setg(errp, "Cannot change '%s' link to '%s'",
  4603. c->name, from->node_name);
  4604. return -EPERM;
  4605. }
  4606. bdrv_replace_child_tran(c, to, tran);
  4607. }
  4608. return 0;
  4609. }
  4610. /*
  4611. * Switch all parents of @from to point to @to instead. @from and @to must be in
  4612. * the same AioContext and both must be drained.
  4613. *
  4614. * With auto_skip=true bdrv_replace_node_common skips updating from parents
  4615. * if it creates a parent-child relation loop or if parent is block-job.
  4616. *
  4617. * With auto_skip=false the error is returned if from has a parent which should
  4618. * not be updated.
  4619. *
  4620. * With @detach_subchain=true @to must be in a backing chain of @from. In this
  4621. * case backing link of the cow-parent of @to is removed.
  4622. */
  4623. static int GRAPH_WRLOCK
  4624. bdrv_replace_node_common(BlockDriverState *from, BlockDriverState *to,
  4625. bool auto_skip, bool detach_subchain, Error **errp)
  4626. {
  4627. Transaction *tran = tran_new();
  4628. g_autoptr(GSList) refresh_list = NULL;
  4629. BlockDriverState *to_cow_parent = NULL;
  4630. int ret;
  4631. GLOBAL_STATE_CODE();
  4632. assert(from->quiesce_counter);
  4633. assert(to->quiesce_counter);
  4634. assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
  4635. if (detach_subchain) {
  4636. assert(bdrv_chain_contains(from, to));
  4637. assert(from != to);
  4638. for (to_cow_parent = from;
  4639. bdrv_filter_or_cow_bs(to_cow_parent) != to;
  4640. to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
  4641. {
  4642. ;
  4643. }
  4644. }
  4645. /*
  4646. * Do the replacement without permission update.
  4647. * Replacement may influence the permissions, we should calculate new
  4648. * permissions based on new graph. If we fail, we'll roll-back the
  4649. * replacement.
  4650. */
  4651. ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
  4652. if (ret < 0) {
  4653. goto out;
  4654. }
  4655. if (detach_subchain) {
  4656. /* to_cow_parent is already drained because from is drained */
  4657. bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent), tran);
  4658. }
  4659. refresh_list = g_slist_prepend(refresh_list, to);
  4660. refresh_list = g_slist_prepend(refresh_list, from);
  4661. ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
  4662. if (ret < 0) {
  4663. goto out;
  4664. }
  4665. ret = 0;
  4666. out:
  4667. tran_finalize(tran, ret);
  4668. return ret;
  4669. }
  4670. int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
  4671. Error **errp)
  4672. {
  4673. return bdrv_replace_node_common(from, to, true, false, errp);
  4674. }
  4675. int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
  4676. {
  4677. BlockDriverState *child_bs;
  4678. int ret;
  4679. GLOBAL_STATE_CODE();
  4680. bdrv_graph_rdlock_main_loop();
  4681. child_bs = bdrv_filter_or_cow_bs(bs);
  4682. bdrv_graph_rdunlock_main_loop();
  4683. bdrv_drained_begin(child_bs);
  4684. bdrv_graph_wrlock();
  4685. ret = bdrv_replace_node_common(bs, child_bs, true, true, errp);
  4686. bdrv_graph_wrunlock();
  4687. bdrv_drained_end(child_bs);
  4688. return ret;
  4689. }
  4690. /*
  4691. * Add new bs contents at the top of an image chain while the chain is
  4692. * live, while keeping required fields on the top layer.
  4693. *
  4694. * This will modify the BlockDriverState fields, and swap contents
  4695. * between bs_new and bs_top. Both bs_new and bs_top are modified.
  4696. *
  4697. * bs_new must not be attached to a BlockBackend and must not have backing
  4698. * child.
  4699. *
  4700. * This function does not create any image files.
  4701. */
  4702. int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
  4703. Error **errp)
  4704. {
  4705. int ret;
  4706. BdrvChild *child;
  4707. Transaction *tran = tran_new();
  4708. GLOBAL_STATE_CODE();
  4709. bdrv_graph_rdlock_main_loop();
  4710. assert(!bs_new->backing);
  4711. bdrv_graph_rdunlock_main_loop();
  4712. bdrv_drained_begin(bs_top);
  4713. bdrv_drained_begin(bs_new);
  4714. bdrv_graph_wrlock();
  4715. child = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
  4716. &child_of_bds, bdrv_backing_role(bs_new),
  4717. tran, errp);
  4718. if (!child) {
  4719. ret = -EINVAL;
  4720. goto out;
  4721. }
  4722. ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
  4723. if (ret < 0) {
  4724. goto out;
  4725. }
  4726. ret = bdrv_refresh_perms(bs_new, tran, errp);
  4727. out:
  4728. tran_finalize(tran, ret);
  4729. bdrv_refresh_limits(bs_top, NULL, NULL);
  4730. bdrv_graph_wrunlock();
  4731. bdrv_drained_end(bs_top);
  4732. bdrv_drained_end(bs_new);
  4733. return ret;
  4734. }
  4735. /* Not for empty child */
  4736. int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
  4737. Error **errp)
  4738. {
  4739. int ret;
  4740. Transaction *tran = tran_new();
  4741. g_autoptr(GSList) refresh_list = NULL;
  4742. BlockDriverState *old_bs = child->bs;
  4743. GLOBAL_STATE_CODE();
  4744. bdrv_ref(old_bs);
  4745. bdrv_drained_begin(old_bs);
  4746. bdrv_drained_begin(new_bs);
  4747. bdrv_graph_wrlock();
  4748. bdrv_replace_child_tran(child, new_bs, tran);
  4749. refresh_list = g_slist_prepend(refresh_list, old_bs);
  4750. refresh_list = g_slist_prepend(refresh_list, new_bs);
  4751. ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
  4752. tran_finalize(tran, ret);
  4753. bdrv_graph_wrunlock();
  4754. bdrv_drained_end(old_bs);
  4755. bdrv_drained_end(new_bs);
  4756. bdrv_unref(old_bs);
  4757. return ret;
  4758. }
  4759. static void bdrv_delete(BlockDriverState *bs)
  4760. {
  4761. assert(bdrv_op_blocker_is_empty(bs));
  4762. assert(!bs->refcnt);
  4763. GLOBAL_STATE_CODE();
  4764. /* remove from list, if necessary */
  4765. if (bs->node_name[0] != '\0') {
  4766. QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
  4767. }
  4768. QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
  4769. bdrv_close(bs);
  4770. qemu_mutex_destroy(&bs->reqs_lock);
  4771. g_free(bs);
  4772. }
  4773. /*
  4774. * Replace @bs by newly created block node.
  4775. *
  4776. * @options is a QDict of options to pass to the block drivers, or NULL for an
  4777. * empty set of options. The reference to the QDict belongs to the block layer
  4778. * after the call (even on failure), so if the caller intends to reuse the
  4779. * dictionary, it needs to use qobject_ref() before calling bdrv_open.
  4780. *
  4781. * The caller must make sure that @bs stays in the same AioContext, i.e.
  4782. * @options must not refer to nodes in a different AioContext.
  4783. */
  4784. BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
  4785. int flags, Error **errp)
  4786. {
  4787. ERRP_GUARD();
  4788. int ret;
  4789. AioContext *ctx = bdrv_get_aio_context(bs);
  4790. BlockDriverState *new_node_bs = NULL;
  4791. const char *drvname, *node_name;
  4792. BlockDriver *drv;
  4793. drvname = qdict_get_try_str(options, "driver");
  4794. if (!drvname) {
  4795. error_setg(errp, "driver is not specified");
  4796. goto fail;
  4797. }
  4798. drv = bdrv_find_format(drvname);
  4799. if (!drv) {
  4800. error_setg(errp, "Unknown driver: '%s'", drvname);
  4801. goto fail;
  4802. }
  4803. node_name = qdict_get_try_str(options, "node-name");
  4804. GLOBAL_STATE_CODE();
  4805. new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
  4806. errp);
  4807. assert(bdrv_get_aio_context(bs) == ctx);
  4808. options = NULL; /* bdrv_new_open_driver() eats options */
  4809. if (!new_node_bs) {
  4810. error_prepend(errp, "Could not create node: ");
  4811. goto fail;
  4812. }
  4813. /*
  4814. * Make sure that @bs doesn't go away until we have successfully attached
  4815. * all of its parents to @new_node_bs and undrained it again.
  4816. */
  4817. bdrv_ref(bs);
  4818. bdrv_drained_begin(bs);
  4819. bdrv_drained_begin(new_node_bs);
  4820. bdrv_graph_wrlock();
  4821. ret = bdrv_replace_node(bs, new_node_bs, errp);
  4822. bdrv_graph_wrunlock();
  4823. bdrv_drained_end(new_node_bs);
  4824. bdrv_drained_end(bs);
  4825. bdrv_unref(bs);
  4826. if (ret < 0) {
  4827. error_prepend(errp, "Could not replace node: ");
  4828. goto fail;
  4829. }
  4830. return new_node_bs;
  4831. fail:
  4832. qobject_unref(options);
  4833. bdrv_unref(new_node_bs);
  4834. return NULL;
  4835. }
  4836. /*
  4837. * Run consistency checks on an image
  4838. *
  4839. * Returns 0 if the check could be completed (it doesn't mean that the image is
  4840. * free of errors) or -errno when an internal error occurred. The results of the
  4841. * check are stored in res.
  4842. */
  4843. int coroutine_fn bdrv_co_check(BlockDriverState *bs,
  4844. BdrvCheckResult *res, BdrvCheckMode fix)
  4845. {
  4846. IO_CODE();
  4847. assert_bdrv_graph_readable();
  4848. if (bs->drv == NULL) {
  4849. return -ENOMEDIUM;
  4850. }
  4851. if (bs->drv->bdrv_co_check == NULL) {
  4852. return -ENOTSUP;
  4853. }
  4854. memset(res, 0, sizeof(*res));
  4855. return bs->drv->bdrv_co_check(bs, res, fix);
  4856. }
  4857. /*
  4858. * Return values:
  4859. * 0 - success
  4860. * -EINVAL - backing format specified, but no file
  4861. * -ENOSPC - can't update the backing file because no space is left in the
  4862. * image file header
  4863. * -ENOTSUP - format driver doesn't support changing the backing file
  4864. */
  4865. int coroutine_fn
  4866. bdrv_co_change_backing_file(BlockDriverState *bs, const char *backing_file,
  4867. const char *backing_fmt, bool require)
  4868. {
  4869. BlockDriver *drv = bs->drv;
  4870. int ret;
  4871. IO_CODE();
  4872. if (!drv) {
  4873. return -ENOMEDIUM;
  4874. }
  4875. /* Backing file format doesn't make sense without a backing file */
  4876. if (backing_fmt && !backing_file) {
  4877. return -EINVAL;
  4878. }
  4879. if (require && backing_file && !backing_fmt) {
  4880. return -EINVAL;
  4881. }
  4882. if (drv->bdrv_co_change_backing_file != NULL) {
  4883. ret = drv->bdrv_co_change_backing_file(bs, backing_file, backing_fmt);
  4884. } else {
  4885. ret = -ENOTSUP;
  4886. }
  4887. if (ret == 0) {
  4888. pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
  4889. pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
  4890. pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
  4891. backing_file ?: "");
  4892. }
  4893. return ret;
  4894. }
  4895. /*
  4896. * Finds the first non-filter node above bs in the chain between
  4897. * active and bs. The returned node is either an immediate parent of
  4898. * bs, or there are only filter nodes between the two.
  4899. *
  4900. * Returns NULL if bs is not found in active's image chain,
  4901. * or if active == bs.
  4902. *
  4903. * Returns the bottommost base image if bs == NULL.
  4904. */
  4905. BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
  4906. BlockDriverState *bs)
  4907. {
  4908. GLOBAL_STATE_CODE();
  4909. bs = bdrv_skip_filters(bs);
  4910. active = bdrv_skip_filters(active);
  4911. while (active) {
  4912. BlockDriverState *next = bdrv_backing_chain_next(active);
  4913. if (bs == next) {
  4914. return active;
  4915. }
  4916. active = next;
  4917. }
  4918. return NULL;
  4919. }
  4920. /* Given a BDS, searches for the base layer. */
  4921. BlockDriverState *bdrv_find_base(BlockDriverState *bs)
  4922. {
  4923. GLOBAL_STATE_CODE();
  4924. return bdrv_find_overlay(bs, NULL);
  4925. }
  4926. /*
  4927. * Return true if at least one of the COW (backing) and filter links
  4928. * between @bs and @base is frozen. @errp is set if that's the case.
  4929. * @base must be reachable from @bs, or NULL.
  4930. */
  4931. static bool GRAPH_RDLOCK
  4932. bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
  4933. Error **errp)
  4934. {
  4935. BlockDriverState *i;
  4936. BdrvChild *child;
  4937. GLOBAL_STATE_CODE();
  4938. for (i = bs; i != base; i = child_bs(child)) {
  4939. child = bdrv_filter_or_cow_child(i);
  4940. if (child && child->frozen) {
  4941. error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
  4942. child->name, i->node_name, child->bs->node_name);
  4943. return true;
  4944. }
  4945. }
  4946. return false;
  4947. }
  4948. /*
  4949. * Freeze all COW (backing) and filter links between @bs and @base.
  4950. * If any of the links is already frozen the operation is aborted and
  4951. * none of the links are modified.
  4952. * @base must be reachable from @bs, or NULL.
  4953. * Returns 0 on success. On failure returns < 0 and sets @errp.
  4954. */
  4955. int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
  4956. Error **errp)
  4957. {
  4958. BlockDriverState *i;
  4959. BdrvChild *child;
  4960. GLOBAL_STATE_CODE();
  4961. if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
  4962. return -EPERM;
  4963. }
  4964. for (i = bs; i != base; i = child_bs(child)) {
  4965. child = bdrv_filter_or_cow_child(i);
  4966. if (child && child->bs->never_freeze) {
  4967. error_setg(errp, "Cannot freeze '%s' link to '%s'",
  4968. child->name, child->bs->node_name);
  4969. return -EPERM;
  4970. }
  4971. }
  4972. for (i = bs; i != base; i = child_bs(child)) {
  4973. child = bdrv_filter_or_cow_child(i);
  4974. if (child) {
  4975. child->frozen = true;
  4976. }
  4977. }
  4978. return 0;
  4979. }
  4980. /*
  4981. * Unfreeze all COW (backing) and filter links between @bs and @base.
  4982. * The caller must ensure that all links are frozen before using this
  4983. * function.
  4984. * @base must be reachable from @bs, or NULL.
  4985. */
  4986. void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
  4987. {
  4988. BlockDriverState *i;
  4989. BdrvChild *child;
  4990. GLOBAL_STATE_CODE();
  4991. for (i = bs; i != base; i = child_bs(child)) {
  4992. child = bdrv_filter_or_cow_child(i);
  4993. if (child) {
  4994. assert(child->frozen);
  4995. child->frozen = false;
  4996. }
  4997. }
  4998. }
  4999. /*
  5000. * Drops images above 'base' up to and including 'top', and sets the image
  5001. * above 'top' to have base as its backing file.
  5002. *
  5003. * Requires that the overlay to 'top' is opened r/w, so that the backing file
  5004. * information in 'bs' can be properly updated.
  5005. *
  5006. * E.g., this will convert the following chain:
  5007. * bottom <- base <- intermediate <- top <- active
  5008. *
  5009. * to
  5010. *
  5011. * bottom <- base <- active
  5012. *
  5013. * It is allowed for bottom==base, in which case it converts:
  5014. *
  5015. * base <- intermediate <- top <- active
  5016. *
  5017. * to
  5018. *
  5019. * base <- active
  5020. *
  5021. * If backing_file_str is non-NULL, it will be used when modifying top's
  5022. * overlay image metadata.
  5023. *
  5024. * Error conditions:
  5025. * if active == top, that is considered an error
  5026. *
  5027. */
  5028. int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
  5029. const char *backing_file_str,
  5030. bool backing_mask_protocol)
  5031. {
  5032. BlockDriverState *explicit_top = top;
  5033. bool update_inherits_from;
  5034. BdrvChild *c;
  5035. Error *local_err = NULL;
  5036. int ret = -EIO;
  5037. g_autoptr(GSList) updated_children = NULL;
  5038. GSList *p;
  5039. GLOBAL_STATE_CODE();
  5040. bdrv_ref(top);
  5041. bdrv_drained_begin(base);
  5042. bdrv_graph_wrlock();
  5043. if (!top->drv || !base->drv) {
  5044. goto exit_wrlock;
  5045. }
  5046. /* Make sure that base is in the backing chain of top */
  5047. if (!bdrv_chain_contains(top, base)) {
  5048. goto exit_wrlock;
  5049. }
  5050. /* If 'base' recursively inherits from 'top' then we should set
  5051. * base->inherits_from to top->inherits_from after 'top' and all
  5052. * other intermediate nodes have been dropped.
  5053. * If 'top' is an implicit node (e.g. "commit_top") we should skip
  5054. * it because no one inherits from it. We use explicit_top for that. */
  5055. explicit_top = bdrv_skip_implicit_filters(explicit_top);
  5056. update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
  5057. /* success - we can delete the intermediate states, and link top->base */
  5058. if (!backing_file_str) {
  5059. bdrv_refresh_filename(base);
  5060. backing_file_str = base->filename;
  5061. }
  5062. QLIST_FOREACH(c, &top->parents, next_parent) {
  5063. updated_children = g_slist_prepend(updated_children, c);
  5064. }
  5065. /*
  5066. * It seems correct to pass detach_subchain=true here, but it triggers
  5067. * one more yet not fixed bug, when due to nested aio_poll loop we switch to
  5068. * another drained section, which modify the graph (for example, removing
  5069. * the child, which we keep in updated_children list). So, it's a TODO.
  5070. *
  5071. * Note, bug triggered if pass detach_subchain=true here and run
  5072. * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
  5073. * That's a FIXME.
  5074. */
  5075. bdrv_replace_node_common(top, base, false, false, &local_err);
  5076. bdrv_graph_wrunlock();
  5077. if (local_err) {
  5078. error_report_err(local_err);
  5079. goto exit;
  5080. }
  5081. for (p = updated_children; p; p = p->next) {
  5082. c = p->data;
  5083. if (c->klass->update_filename) {
  5084. ret = c->klass->update_filename(c, base, backing_file_str,
  5085. backing_mask_protocol,
  5086. &local_err);
  5087. if (ret < 0) {
  5088. /*
  5089. * TODO: Actually, we want to rollback all previous iterations
  5090. * of this loop, and (which is almost impossible) previous
  5091. * bdrv_replace_node()...
  5092. *
  5093. * Note, that c->klass->update_filename may lead to permission
  5094. * update, so it's a bad idea to call it inside permission
  5095. * update transaction of bdrv_replace_node.
  5096. */
  5097. error_report_err(local_err);
  5098. goto exit;
  5099. }
  5100. }
  5101. }
  5102. if (update_inherits_from) {
  5103. base->inherits_from = explicit_top->inherits_from;
  5104. }
  5105. ret = 0;
  5106. goto exit;
  5107. exit_wrlock:
  5108. bdrv_graph_wrunlock();
  5109. exit:
  5110. bdrv_drained_end(base);
  5111. bdrv_unref(top);
  5112. return ret;
  5113. }
  5114. /**
  5115. * Implementation of BlockDriver.bdrv_co_get_allocated_file_size() that
  5116. * sums the size of all data-bearing children. (This excludes backing
  5117. * children.)
  5118. */
  5119. static int64_t coroutine_fn GRAPH_RDLOCK
  5120. bdrv_sum_allocated_file_size(BlockDriverState *bs)
  5121. {
  5122. BdrvChild *child;
  5123. int64_t child_size, sum = 0;
  5124. QLIST_FOREACH(child, &bs->children, next) {
  5125. if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
  5126. BDRV_CHILD_FILTERED))
  5127. {
  5128. child_size = bdrv_co_get_allocated_file_size(child->bs);
  5129. if (child_size < 0) {
  5130. return child_size;
  5131. }
  5132. sum += child_size;
  5133. }
  5134. }
  5135. return sum;
  5136. }
  5137. /**
  5138. * Length of a allocated file in bytes. Sparse files are counted by actual
  5139. * allocated space. Return < 0 if error or unknown.
  5140. */
  5141. int64_t coroutine_fn bdrv_co_get_allocated_file_size(BlockDriverState *bs)
  5142. {
  5143. BlockDriver *drv = bs->drv;
  5144. IO_CODE();
  5145. assert_bdrv_graph_readable();
  5146. if (!drv) {
  5147. return -ENOMEDIUM;
  5148. }
  5149. if (drv->bdrv_co_get_allocated_file_size) {
  5150. return drv->bdrv_co_get_allocated_file_size(bs);
  5151. }
  5152. if (drv->protocol_name) {
  5153. /*
  5154. * Protocol drivers default to -ENOTSUP (most of their data is
  5155. * not stored in any of their children (if they even have any),
  5156. * so there is no generic way to figure it out).
  5157. */
  5158. return -ENOTSUP;
  5159. } else if (drv->is_filter) {
  5160. /* Filter drivers default to the size of their filtered child */
  5161. return bdrv_co_get_allocated_file_size(bdrv_filter_bs(bs));
  5162. } else {
  5163. /* Other drivers default to summing their children's sizes */
  5164. return bdrv_sum_allocated_file_size(bs);
  5165. }
  5166. }
  5167. /*
  5168. * bdrv_measure:
  5169. * @drv: Format driver
  5170. * @opts: Creation options for new image
  5171. * @in_bs: Existing image containing data for new image (may be NULL)
  5172. * @errp: Error object
  5173. * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
  5174. * or NULL on error
  5175. *
  5176. * Calculate file size required to create a new image.
  5177. *
  5178. * If @in_bs is given then space for allocated clusters and zero clusters
  5179. * from that image are included in the calculation. If @opts contains a
  5180. * backing file that is shared by @in_bs then backing clusters may be omitted
  5181. * from the calculation.
  5182. *
  5183. * If @in_bs is NULL then the calculation includes no allocated clusters
  5184. * unless a preallocation option is given in @opts.
  5185. *
  5186. * Note that @in_bs may use a different BlockDriver from @drv.
  5187. *
  5188. * If an error occurs the @errp pointer is set.
  5189. */
  5190. BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
  5191. BlockDriverState *in_bs, Error **errp)
  5192. {
  5193. IO_CODE();
  5194. if (!drv->bdrv_measure) {
  5195. error_setg(errp, "Block driver '%s' does not support size measurement",
  5196. drv->format_name);
  5197. return NULL;
  5198. }
  5199. return drv->bdrv_measure(opts, in_bs, errp);
  5200. }
  5201. /**
  5202. * Return number of sectors on success, -errno on error.
  5203. */
  5204. int64_t coroutine_fn bdrv_co_nb_sectors(BlockDriverState *bs)
  5205. {
  5206. BlockDriver *drv = bs->drv;
  5207. IO_CODE();
  5208. assert_bdrv_graph_readable();
  5209. if (!drv)
  5210. return -ENOMEDIUM;
  5211. if (bs->bl.has_variable_length) {
  5212. int ret = bdrv_co_refresh_total_sectors(bs, bs->total_sectors);
  5213. if (ret < 0) {
  5214. return ret;
  5215. }
  5216. }
  5217. return bs->total_sectors;
  5218. }
  5219. /*
  5220. * This wrapper is written by hand because this function is in the hot I/O path,
  5221. * via blk_get_geometry.
  5222. */
  5223. int64_t coroutine_mixed_fn bdrv_nb_sectors(BlockDriverState *bs)
  5224. {
  5225. BlockDriver *drv = bs->drv;
  5226. IO_CODE();
  5227. if (!drv)
  5228. return -ENOMEDIUM;
  5229. if (bs->bl.has_variable_length) {
  5230. int ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
  5231. if (ret < 0) {
  5232. return ret;
  5233. }
  5234. }
  5235. return bs->total_sectors;
  5236. }
  5237. /**
  5238. * Return length in bytes on success, -errno on error.
  5239. * The length is always a multiple of BDRV_SECTOR_SIZE.
  5240. */
  5241. int64_t coroutine_fn bdrv_co_getlength(BlockDriverState *bs)
  5242. {
  5243. int64_t ret;
  5244. IO_CODE();
  5245. assert_bdrv_graph_readable();
  5246. ret = bdrv_co_nb_sectors(bs);
  5247. if (ret < 0) {
  5248. return ret;
  5249. }
  5250. if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
  5251. return -EFBIG;
  5252. }
  5253. return ret * BDRV_SECTOR_SIZE;
  5254. }
  5255. bool bdrv_is_sg(BlockDriverState *bs)
  5256. {
  5257. IO_CODE();
  5258. return bs->sg;
  5259. }
  5260. /**
  5261. * Return whether the given node supports compressed writes.
  5262. */
  5263. bool bdrv_supports_compressed_writes(BlockDriverState *bs)
  5264. {
  5265. BlockDriverState *filtered;
  5266. IO_CODE();
  5267. if (!bs->drv || !block_driver_can_compress(bs->drv)) {
  5268. return false;
  5269. }
  5270. filtered = bdrv_filter_bs(bs);
  5271. if (filtered) {
  5272. /*
  5273. * Filters can only forward compressed writes, so we have to
  5274. * check the child.
  5275. */
  5276. return bdrv_supports_compressed_writes(filtered);
  5277. }
  5278. return true;
  5279. }
  5280. const char *bdrv_get_format_name(BlockDriverState *bs)
  5281. {
  5282. IO_CODE();
  5283. return bs->drv ? bs->drv->format_name : NULL;
  5284. }
  5285. static int qsort_strcmp(const void *a, const void *b)
  5286. {
  5287. return strcmp(*(char *const *)a, *(char *const *)b);
  5288. }
  5289. void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
  5290. void *opaque, bool read_only)
  5291. {
  5292. BlockDriver *drv;
  5293. int count = 0;
  5294. int i;
  5295. const char **formats = NULL;
  5296. GLOBAL_STATE_CODE();
  5297. QLIST_FOREACH(drv, &bdrv_drivers, list) {
  5298. if (drv->format_name) {
  5299. bool found = false;
  5300. if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
  5301. continue;
  5302. }
  5303. i = count;
  5304. while (formats && i && !found) {
  5305. found = !strcmp(formats[--i], drv->format_name);
  5306. }
  5307. if (!found) {
  5308. formats = g_renew(const char *, formats, count + 1);
  5309. formats[count++] = drv->format_name;
  5310. }
  5311. }
  5312. }
  5313. for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
  5314. const char *format_name = block_driver_modules[i].format_name;
  5315. if (format_name) {
  5316. bool found = false;
  5317. int j = count;
  5318. if (use_bdrv_whitelist &&
  5319. !bdrv_format_is_whitelisted(format_name, read_only)) {
  5320. continue;
  5321. }
  5322. while (formats && j && !found) {
  5323. found = !strcmp(formats[--j], format_name);
  5324. }
  5325. if (!found) {
  5326. formats = g_renew(const char *, formats, count + 1);
  5327. formats[count++] = format_name;
  5328. }
  5329. }
  5330. }
  5331. qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
  5332. for (i = 0; i < count; i++) {
  5333. it(opaque, formats[i]);
  5334. }
  5335. g_free(formats);
  5336. }
  5337. /* This function is to find a node in the bs graph */
  5338. BlockDriverState *bdrv_find_node(const char *node_name)
  5339. {
  5340. BlockDriverState *bs;
  5341. assert(node_name);
  5342. GLOBAL_STATE_CODE();
  5343. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  5344. if (!strcmp(node_name, bs->node_name)) {
  5345. return bs;
  5346. }
  5347. }
  5348. return NULL;
  5349. }
  5350. /* Put this QMP function here so it can access the static graph_bdrv_states. */
  5351. BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
  5352. Error **errp)
  5353. {
  5354. BlockDeviceInfoList *list;
  5355. BlockDriverState *bs;
  5356. GLOBAL_STATE_CODE();
  5357. GRAPH_RDLOCK_GUARD_MAINLOOP();
  5358. list = NULL;
  5359. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  5360. BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
  5361. if (!info) {
  5362. qapi_free_BlockDeviceInfoList(list);
  5363. return NULL;
  5364. }
  5365. QAPI_LIST_PREPEND(list, info);
  5366. }
  5367. return list;
  5368. }
  5369. typedef struct XDbgBlockGraphConstructor {
  5370. XDbgBlockGraph *graph;
  5371. GHashTable *graph_nodes;
  5372. } XDbgBlockGraphConstructor;
  5373. static XDbgBlockGraphConstructor *xdbg_graph_new(void)
  5374. {
  5375. XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
  5376. gr->graph = g_new0(XDbgBlockGraph, 1);
  5377. gr->graph_nodes = g_hash_table_new(NULL, NULL);
  5378. return gr;
  5379. }
  5380. static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
  5381. {
  5382. XDbgBlockGraph *graph = gr->graph;
  5383. g_hash_table_destroy(gr->graph_nodes);
  5384. g_free(gr);
  5385. return graph;
  5386. }
  5387. static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
  5388. {
  5389. uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
  5390. if (ret != 0) {
  5391. return ret;
  5392. }
  5393. /*
  5394. * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
  5395. * answer of g_hash_table_lookup.
  5396. */
  5397. ret = g_hash_table_size(gr->graph_nodes) + 1;
  5398. g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
  5399. return ret;
  5400. }
  5401. static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
  5402. XDbgBlockGraphNodeType type, const char *name)
  5403. {
  5404. XDbgBlockGraphNode *n;
  5405. n = g_new0(XDbgBlockGraphNode, 1);
  5406. n->id = xdbg_graph_node_num(gr, node);
  5407. n->type = type;
  5408. n->name = g_strdup(name);
  5409. QAPI_LIST_PREPEND(gr->graph->nodes, n);
  5410. }
  5411. static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
  5412. const BdrvChild *child)
  5413. {
  5414. BlockPermission qapi_perm;
  5415. XDbgBlockGraphEdge *edge;
  5416. GLOBAL_STATE_CODE();
  5417. edge = g_new0(XDbgBlockGraphEdge, 1);
  5418. edge->parent = xdbg_graph_node_num(gr, parent);
  5419. edge->child = xdbg_graph_node_num(gr, child->bs);
  5420. edge->name = g_strdup(child->name);
  5421. for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
  5422. uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
  5423. if (flag & child->perm) {
  5424. QAPI_LIST_PREPEND(edge->perm, qapi_perm);
  5425. }
  5426. if (flag & child->shared_perm) {
  5427. QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
  5428. }
  5429. }
  5430. QAPI_LIST_PREPEND(gr->graph->edges, edge);
  5431. }
  5432. XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
  5433. {
  5434. BlockBackend *blk;
  5435. BlockJob *job;
  5436. BlockDriverState *bs;
  5437. BdrvChild *child;
  5438. XDbgBlockGraphConstructor *gr = xdbg_graph_new();
  5439. GLOBAL_STATE_CODE();
  5440. for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
  5441. char *allocated_name = NULL;
  5442. const char *name = blk_name(blk);
  5443. if (!*name) {
  5444. name = allocated_name = blk_get_attached_dev_id(blk);
  5445. }
  5446. xdbg_graph_add_node(gr, blk, XDBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
  5447. name);
  5448. g_free(allocated_name);
  5449. if (blk_root(blk)) {
  5450. xdbg_graph_add_edge(gr, blk, blk_root(blk));
  5451. }
  5452. }
  5453. WITH_JOB_LOCK_GUARD() {
  5454. for (job = block_job_next_locked(NULL); job;
  5455. job = block_job_next_locked(job)) {
  5456. GSList *el;
  5457. xdbg_graph_add_node(gr, job, XDBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
  5458. job->job.id);
  5459. for (el = job->nodes; el; el = el->next) {
  5460. xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
  5461. }
  5462. }
  5463. }
  5464. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  5465. xdbg_graph_add_node(gr, bs, XDBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
  5466. bs->node_name);
  5467. QLIST_FOREACH(child, &bs->children, next) {
  5468. xdbg_graph_add_edge(gr, bs, child);
  5469. }
  5470. }
  5471. return xdbg_graph_finalize(gr);
  5472. }
  5473. BlockDriverState *bdrv_lookup_bs(const char *device,
  5474. const char *node_name,
  5475. Error **errp)
  5476. {
  5477. BlockBackend *blk;
  5478. BlockDriverState *bs;
  5479. GLOBAL_STATE_CODE();
  5480. if (device) {
  5481. blk = blk_by_name(device);
  5482. if (blk) {
  5483. bs = blk_bs(blk);
  5484. if (!bs) {
  5485. error_setg(errp, "Device '%s' has no medium", device);
  5486. }
  5487. return bs;
  5488. }
  5489. }
  5490. if (node_name) {
  5491. bs = bdrv_find_node(node_name);
  5492. if (bs) {
  5493. return bs;
  5494. }
  5495. }
  5496. error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
  5497. device ? device : "",
  5498. node_name ? node_name : "");
  5499. return NULL;
  5500. }
  5501. /* If 'base' is in the same chain as 'top', return true. Otherwise,
  5502. * return false. If either argument is NULL, return false. */
  5503. bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
  5504. {
  5505. GLOBAL_STATE_CODE();
  5506. while (top && top != base) {
  5507. top = bdrv_filter_or_cow_bs(top);
  5508. }
  5509. return top != NULL;
  5510. }
  5511. BlockDriverState *bdrv_next_node(BlockDriverState *bs)
  5512. {
  5513. GLOBAL_STATE_CODE();
  5514. if (!bs) {
  5515. return QTAILQ_FIRST(&graph_bdrv_states);
  5516. }
  5517. return QTAILQ_NEXT(bs, node_list);
  5518. }
  5519. BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
  5520. {
  5521. GLOBAL_STATE_CODE();
  5522. if (!bs) {
  5523. return QTAILQ_FIRST(&all_bdrv_states);
  5524. }
  5525. return QTAILQ_NEXT(bs, bs_list);
  5526. }
  5527. const char *bdrv_get_node_name(const BlockDriverState *bs)
  5528. {
  5529. IO_CODE();
  5530. return bs->node_name;
  5531. }
  5532. const char *bdrv_get_parent_name(const BlockDriverState *bs)
  5533. {
  5534. BdrvChild *c;
  5535. const char *name;
  5536. IO_CODE();
  5537. /* If multiple parents have a name, just pick the first one. */
  5538. QLIST_FOREACH(c, &bs->parents, next_parent) {
  5539. if (c->klass->get_name) {
  5540. name = c->klass->get_name(c);
  5541. if (name && *name) {
  5542. return name;
  5543. }
  5544. }
  5545. }
  5546. return NULL;
  5547. }
  5548. /* TODO check what callers really want: bs->node_name or blk_name() */
  5549. const char *bdrv_get_device_name(const BlockDriverState *bs)
  5550. {
  5551. IO_CODE();
  5552. return bdrv_get_parent_name(bs) ?: "";
  5553. }
  5554. /* This can be used to identify nodes that might not have a device
  5555. * name associated. Since node and device names live in the same
  5556. * namespace, the result is unambiguous. The exception is if both are
  5557. * absent, then this returns an empty (non-null) string. */
  5558. const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
  5559. {
  5560. IO_CODE();
  5561. return bdrv_get_parent_name(bs) ?: bs->node_name;
  5562. }
  5563. int bdrv_get_flags(BlockDriverState *bs)
  5564. {
  5565. IO_CODE();
  5566. return bs->open_flags;
  5567. }
  5568. int bdrv_has_zero_init_1(BlockDriverState *bs)
  5569. {
  5570. GLOBAL_STATE_CODE();
  5571. return 1;
  5572. }
  5573. int coroutine_mixed_fn bdrv_has_zero_init(BlockDriverState *bs)
  5574. {
  5575. BlockDriverState *filtered;
  5576. GLOBAL_STATE_CODE();
  5577. if (!bs->drv) {
  5578. return 0;
  5579. }
  5580. /* If BS is a copy on write image, it is initialized to
  5581. the contents of the base image, which may not be zeroes. */
  5582. if (bdrv_cow_child(bs)) {
  5583. return 0;
  5584. }
  5585. if (bs->drv->bdrv_has_zero_init) {
  5586. return bs->drv->bdrv_has_zero_init(bs);
  5587. }
  5588. filtered = bdrv_filter_bs(bs);
  5589. if (filtered) {
  5590. return bdrv_has_zero_init(filtered);
  5591. }
  5592. /* safe default */
  5593. return 0;
  5594. }
  5595. bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
  5596. {
  5597. IO_CODE();
  5598. if (!(bs->open_flags & BDRV_O_UNMAP)) {
  5599. return false;
  5600. }
  5601. return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
  5602. }
  5603. void bdrv_get_backing_filename(BlockDriverState *bs,
  5604. char *filename, int filename_size)
  5605. {
  5606. IO_CODE();
  5607. pstrcpy(filename, filename_size, bs->backing_file);
  5608. }
  5609. int coroutine_fn bdrv_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
  5610. {
  5611. int ret;
  5612. BlockDriver *drv = bs->drv;
  5613. IO_CODE();
  5614. assert_bdrv_graph_readable();
  5615. /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
  5616. if (!drv) {
  5617. return -ENOMEDIUM;
  5618. }
  5619. if (!drv->bdrv_co_get_info) {
  5620. BlockDriverState *filtered = bdrv_filter_bs(bs);
  5621. if (filtered) {
  5622. return bdrv_co_get_info(filtered, bdi);
  5623. }
  5624. return -ENOTSUP;
  5625. }
  5626. memset(bdi, 0, sizeof(*bdi));
  5627. ret = drv->bdrv_co_get_info(bs, bdi);
  5628. if (bdi->subcluster_size == 0) {
  5629. /*
  5630. * If the driver left this unset, subclusters are not supported.
  5631. * Then it is safe to treat each cluster as having only one subcluster.
  5632. */
  5633. bdi->subcluster_size = bdi->cluster_size;
  5634. }
  5635. if (ret < 0) {
  5636. return ret;
  5637. }
  5638. if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
  5639. return -EINVAL;
  5640. }
  5641. return 0;
  5642. }
  5643. ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
  5644. Error **errp)
  5645. {
  5646. BlockDriver *drv = bs->drv;
  5647. IO_CODE();
  5648. if (drv && drv->bdrv_get_specific_info) {
  5649. return drv->bdrv_get_specific_info(bs, errp);
  5650. }
  5651. return NULL;
  5652. }
  5653. BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
  5654. {
  5655. BlockDriver *drv = bs->drv;
  5656. IO_CODE();
  5657. if (!drv || !drv->bdrv_get_specific_stats) {
  5658. return NULL;
  5659. }
  5660. return drv->bdrv_get_specific_stats(bs);
  5661. }
  5662. void coroutine_fn bdrv_co_debug_event(BlockDriverState *bs, BlkdebugEvent event)
  5663. {
  5664. IO_CODE();
  5665. assert_bdrv_graph_readable();
  5666. if (!bs || !bs->drv || !bs->drv->bdrv_co_debug_event) {
  5667. return;
  5668. }
  5669. bs->drv->bdrv_co_debug_event(bs, event);
  5670. }
  5671. static BlockDriverState * GRAPH_RDLOCK
  5672. bdrv_find_debug_node(BlockDriverState *bs)
  5673. {
  5674. GLOBAL_STATE_CODE();
  5675. while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
  5676. bs = bdrv_primary_bs(bs);
  5677. }
  5678. if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
  5679. assert(bs->drv->bdrv_debug_remove_breakpoint);
  5680. return bs;
  5681. }
  5682. return NULL;
  5683. }
  5684. int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
  5685. const char *tag)
  5686. {
  5687. GLOBAL_STATE_CODE();
  5688. GRAPH_RDLOCK_GUARD_MAINLOOP();
  5689. bs = bdrv_find_debug_node(bs);
  5690. if (bs) {
  5691. return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
  5692. }
  5693. return -ENOTSUP;
  5694. }
  5695. int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
  5696. {
  5697. GLOBAL_STATE_CODE();
  5698. GRAPH_RDLOCK_GUARD_MAINLOOP();
  5699. bs = bdrv_find_debug_node(bs);
  5700. if (bs) {
  5701. return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
  5702. }
  5703. return -ENOTSUP;
  5704. }
  5705. int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
  5706. {
  5707. GLOBAL_STATE_CODE();
  5708. GRAPH_RDLOCK_GUARD_MAINLOOP();
  5709. while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
  5710. bs = bdrv_primary_bs(bs);
  5711. }
  5712. if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
  5713. return bs->drv->bdrv_debug_resume(bs, tag);
  5714. }
  5715. return -ENOTSUP;
  5716. }
  5717. bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
  5718. {
  5719. GLOBAL_STATE_CODE();
  5720. GRAPH_RDLOCK_GUARD_MAINLOOP();
  5721. while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
  5722. bs = bdrv_primary_bs(bs);
  5723. }
  5724. if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
  5725. return bs->drv->bdrv_debug_is_suspended(bs, tag);
  5726. }
  5727. return false;
  5728. }
  5729. /* backing_file can either be relative, or absolute, or a protocol. If it is
  5730. * relative, it must be relative to the chain. So, passing in bs->filename
  5731. * from a BDS as backing_file should not be done, as that may be relative to
  5732. * the CWD rather than the chain. */
  5733. BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
  5734. const char *backing_file)
  5735. {
  5736. char *filename_full = NULL;
  5737. char *backing_file_full = NULL;
  5738. char *filename_tmp = NULL;
  5739. int is_protocol = 0;
  5740. bool filenames_refreshed = false;
  5741. BlockDriverState *curr_bs = NULL;
  5742. BlockDriverState *retval = NULL;
  5743. BlockDriverState *bs_below;
  5744. GLOBAL_STATE_CODE();
  5745. GRAPH_RDLOCK_GUARD_MAINLOOP();
  5746. if (!bs || !bs->drv || !backing_file) {
  5747. return NULL;
  5748. }
  5749. filename_full = g_malloc(PATH_MAX);
  5750. backing_file_full = g_malloc(PATH_MAX);
  5751. is_protocol = path_has_protocol(backing_file);
  5752. /*
  5753. * Being largely a legacy function, skip any filters here
  5754. * (because filters do not have normal filenames, so they cannot
  5755. * match anyway; and allowing json:{} filenames is a bit out of
  5756. * scope).
  5757. */
  5758. for (curr_bs = bdrv_skip_filters(bs);
  5759. bdrv_cow_child(curr_bs) != NULL;
  5760. curr_bs = bs_below)
  5761. {
  5762. bs_below = bdrv_backing_chain_next(curr_bs);
  5763. if (bdrv_backing_overridden(curr_bs)) {
  5764. /*
  5765. * If the backing file was overridden, we can only compare
  5766. * directly against the backing node's filename.
  5767. */
  5768. if (!filenames_refreshed) {
  5769. /*
  5770. * This will automatically refresh all of the
  5771. * filenames in the rest of the backing chain, so we
  5772. * only need to do this once.
  5773. */
  5774. bdrv_refresh_filename(bs_below);
  5775. filenames_refreshed = true;
  5776. }
  5777. if (strcmp(backing_file, bs_below->filename) == 0) {
  5778. retval = bs_below;
  5779. break;
  5780. }
  5781. } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
  5782. /*
  5783. * If either of the filename paths is actually a protocol, then
  5784. * compare unmodified paths; otherwise make paths relative.
  5785. */
  5786. char *backing_file_full_ret;
  5787. if (strcmp(backing_file, curr_bs->backing_file) == 0) {
  5788. retval = bs_below;
  5789. break;
  5790. }
  5791. /* Also check against the full backing filename for the image */
  5792. backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
  5793. NULL);
  5794. if (backing_file_full_ret) {
  5795. bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
  5796. g_free(backing_file_full_ret);
  5797. if (equal) {
  5798. retval = bs_below;
  5799. break;
  5800. }
  5801. }
  5802. } else {
  5803. /* If not an absolute filename path, make it relative to the current
  5804. * image's filename path */
  5805. filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
  5806. NULL);
  5807. /* We are going to compare canonicalized absolute pathnames */
  5808. if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
  5809. g_free(filename_tmp);
  5810. continue;
  5811. }
  5812. g_free(filename_tmp);
  5813. /* We need to make sure the backing filename we are comparing against
  5814. * is relative to the current image filename (or absolute) */
  5815. filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
  5816. if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
  5817. g_free(filename_tmp);
  5818. continue;
  5819. }
  5820. g_free(filename_tmp);
  5821. if (strcmp(backing_file_full, filename_full) == 0) {
  5822. retval = bs_below;
  5823. break;
  5824. }
  5825. }
  5826. }
  5827. g_free(filename_full);
  5828. g_free(backing_file_full);
  5829. return retval;
  5830. }
  5831. void bdrv_init(void)
  5832. {
  5833. #ifdef CONFIG_BDRV_WHITELIST_TOOLS
  5834. use_bdrv_whitelist = 1;
  5835. #endif
  5836. module_call_init(MODULE_INIT_BLOCK);
  5837. }
  5838. void bdrv_init_with_whitelist(void)
  5839. {
  5840. use_bdrv_whitelist = 1;
  5841. bdrv_init();
  5842. }
  5843. bool bdrv_is_inactive(BlockDriverState *bs) {
  5844. return bs->open_flags & BDRV_O_INACTIVE;
  5845. }
  5846. int bdrv_activate(BlockDriverState *bs, Error **errp)
  5847. {
  5848. BdrvChild *child, *parent;
  5849. Error *local_err = NULL;
  5850. int ret;
  5851. BdrvDirtyBitmap *bm;
  5852. GLOBAL_STATE_CODE();
  5853. GRAPH_RDLOCK_GUARD_MAINLOOP();
  5854. if (!bs->drv) {
  5855. return -ENOMEDIUM;
  5856. }
  5857. QLIST_FOREACH(child, &bs->children, next) {
  5858. bdrv_activate(child->bs, &local_err);
  5859. if (local_err) {
  5860. error_propagate(errp, local_err);
  5861. return -EINVAL;
  5862. }
  5863. }
  5864. /*
  5865. * Update permissions, they may differ for inactive nodes.
  5866. *
  5867. * Note that the required permissions of inactive images are always a
  5868. * subset of the permissions required after activating the image. This
  5869. * allows us to just get the permissions upfront without restricting
  5870. * bdrv_co_invalidate_cache().
  5871. *
  5872. * It also means that in error cases, we don't have to try and revert to
  5873. * the old permissions (which is an operation that could fail, too). We can
  5874. * just keep the extended permissions for the next time that an activation
  5875. * of the image is tried.
  5876. */
  5877. if (bs->open_flags & BDRV_O_INACTIVE) {
  5878. bs->open_flags &= ~BDRV_O_INACTIVE;
  5879. ret = bdrv_refresh_perms(bs, NULL, errp);
  5880. if (ret < 0) {
  5881. bs->open_flags |= BDRV_O_INACTIVE;
  5882. return ret;
  5883. }
  5884. ret = bdrv_invalidate_cache(bs, errp);
  5885. if (ret < 0) {
  5886. bs->open_flags |= BDRV_O_INACTIVE;
  5887. return ret;
  5888. }
  5889. FOR_EACH_DIRTY_BITMAP(bs, bm) {
  5890. bdrv_dirty_bitmap_skip_store(bm, false);
  5891. }
  5892. ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
  5893. if (ret < 0) {
  5894. bs->open_flags |= BDRV_O_INACTIVE;
  5895. error_setg_errno(errp, -ret, "Could not refresh total sector count");
  5896. return ret;
  5897. }
  5898. }
  5899. QLIST_FOREACH(parent, &bs->parents, next_parent) {
  5900. if (parent->klass->activate) {
  5901. parent->klass->activate(parent, &local_err);
  5902. if (local_err) {
  5903. bs->open_flags |= BDRV_O_INACTIVE;
  5904. error_propagate(errp, local_err);
  5905. return -EINVAL;
  5906. }
  5907. }
  5908. }
  5909. return 0;
  5910. }
  5911. int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
  5912. {
  5913. Error *local_err = NULL;
  5914. IO_CODE();
  5915. assert(!(bs->open_flags & BDRV_O_INACTIVE));
  5916. assert_bdrv_graph_readable();
  5917. if (bs->drv->bdrv_co_invalidate_cache) {
  5918. bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
  5919. if (local_err) {
  5920. error_propagate(errp, local_err);
  5921. return -EINVAL;
  5922. }
  5923. }
  5924. return 0;
  5925. }
  5926. void bdrv_activate_all(Error **errp)
  5927. {
  5928. BlockDriverState *bs;
  5929. BdrvNextIterator it;
  5930. GLOBAL_STATE_CODE();
  5931. GRAPH_RDLOCK_GUARD_MAINLOOP();
  5932. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  5933. int ret;
  5934. ret = bdrv_activate(bs, errp);
  5935. if (ret < 0) {
  5936. bdrv_next_cleanup(&it);
  5937. return;
  5938. }
  5939. }
  5940. }
  5941. static bool GRAPH_RDLOCK
  5942. bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
  5943. {
  5944. BdrvChild *parent;
  5945. GLOBAL_STATE_CODE();
  5946. QLIST_FOREACH(parent, &bs->parents, next_parent) {
  5947. if (parent->klass->parent_is_bds) {
  5948. BlockDriverState *parent_bs = parent->opaque;
  5949. if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
  5950. return true;
  5951. }
  5952. }
  5953. }
  5954. return false;
  5955. }
  5956. static int GRAPH_RDLOCK
  5957. bdrv_inactivate_recurse(BlockDriverState *bs, bool top_level)
  5958. {
  5959. BdrvChild *child, *parent;
  5960. int ret;
  5961. uint64_t cumulative_perms, cumulative_shared_perms;
  5962. GLOBAL_STATE_CODE();
  5963. if (!bs->drv) {
  5964. return -ENOMEDIUM;
  5965. }
  5966. /* Make sure that we don't inactivate a child before its parent.
  5967. * It will be covered by recursion from the yet active parent. */
  5968. if (bdrv_has_bds_parent(bs, true)) {
  5969. return 0;
  5970. }
  5971. /*
  5972. * Inactivating an already inactive node on user request is harmless, but if
  5973. * a child is already inactive before its parent, that's bad.
  5974. */
  5975. if (bs->open_flags & BDRV_O_INACTIVE) {
  5976. assert(top_level);
  5977. return 0;
  5978. }
  5979. /* Inactivate this node */
  5980. if (bs->drv->bdrv_inactivate) {
  5981. ret = bs->drv->bdrv_inactivate(bs);
  5982. if (ret < 0) {
  5983. return ret;
  5984. }
  5985. }
  5986. QLIST_FOREACH(parent, &bs->parents, next_parent) {
  5987. if (parent->klass->inactivate) {
  5988. ret = parent->klass->inactivate(parent);
  5989. if (ret < 0) {
  5990. return ret;
  5991. }
  5992. }
  5993. }
  5994. bdrv_get_cumulative_perm(bs, &cumulative_perms,
  5995. &cumulative_shared_perms);
  5996. if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
  5997. /* Our inactive parents still need write access. Inactivation failed. */
  5998. return -EPERM;
  5999. }
  6000. bdrv_drained_begin(bs);
  6001. bs->open_flags |= BDRV_O_INACTIVE;
  6002. bdrv_drained_end(bs);
  6003. /*
  6004. * Update permissions, they may differ for inactive nodes.
  6005. * We only tried to loosen restrictions, so errors are not fatal, ignore
  6006. * them.
  6007. */
  6008. bdrv_refresh_perms(bs, NULL, NULL);
  6009. /* Recursively inactivate children */
  6010. QLIST_FOREACH(child, &bs->children, next) {
  6011. ret = bdrv_inactivate_recurse(child->bs, false);
  6012. if (ret < 0) {
  6013. return ret;
  6014. }
  6015. }
  6016. return 0;
  6017. }
  6018. int bdrv_inactivate(BlockDriverState *bs, Error **errp)
  6019. {
  6020. int ret;
  6021. GLOBAL_STATE_CODE();
  6022. GRAPH_RDLOCK_GUARD_MAINLOOP();
  6023. if (bdrv_has_bds_parent(bs, true)) {
  6024. error_setg(errp, "Node has active parent node");
  6025. return -EPERM;
  6026. }
  6027. ret = bdrv_inactivate_recurse(bs, true);
  6028. if (ret < 0) {
  6029. error_setg_errno(errp, -ret, "Failed to inactivate node");
  6030. return ret;
  6031. }
  6032. return 0;
  6033. }
  6034. int bdrv_inactivate_all(void)
  6035. {
  6036. BlockDriverState *bs = NULL;
  6037. BdrvNextIterator it;
  6038. int ret = 0;
  6039. GLOBAL_STATE_CODE();
  6040. GRAPH_RDLOCK_GUARD_MAINLOOP();
  6041. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  6042. /* Nodes with BDS parents are covered by recursion from the last
  6043. * parent that gets inactivated. Don't inactivate them a second
  6044. * time if that has already happened. */
  6045. if (bdrv_has_bds_parent(bs, false)) {
  6046. continue;
  6047. }
  6048. ret = bdrv_inactivate_recurse(bs, true);
  6049. if (ret < 0) {
  6050. bdrv_next_cleanup(&it);
  6051. break;
  6052. }
  6053. }
  6054. return ret;
  6055. }
  6056. /**************************************************************/
  6057. /* removable device support */
  6058. /**
  6059. * Return TRUE if the media is present
  6060. */
  6061. bool coroutine_fn bdrv_co_is_inserted(BlockDriverState *bs)
  6062. {
  6063. BlockDriver *drv = bs->drv;
  6064. BdrvChild *child;
  6065. IO_CODE();
  6066. assert_bdrv_graph_readable();
  6067. if (!drv) {
  6068. return false;
  6069. }
  6070. if (drv->bdrv_co_is_inserted) {
  6071. return drv->bdrv_co_is_inserted(bs);
  6072. }
  6073. QLIST_FOREACH(child, &bs->children, next) {
  6074. if (!bdrv_co_is_inserted(child->bs)) {
  6075. return false;
  6076. }
  6077. }
  6078. return true;
  6079. }
  6080. /**
  6081. * If eject_flag is TRUE, eject the media. Otherwise, close the tray
  6082. */
  6083. void coroutine_fn bdrv_co_eject(BlockDriverState *bs, bool eject_flag)
  6084. {
  6085. BlockDriver *drv = bs->drv;
  6086. IO_CODE();
  6087. assert_bdrv_graph_readable();
  6088. if (drv && drv->bdrv_co_eject) {
  6089. drv->bdrv_co_eject(bs, eject_flag);
  6090. }
  6091. }
  6092. /**
  6093. * Lock or unlock the media (if it is locked, the user won't be able
  6094. * to eject it manually).
  6095. */
  6096. void coroutine_fn bdrv_co_lock_medium(BlockDriverState *bs, bool locked)
  6097. {
  6098. BlockDriver *drv = bs->drv;
  6099. IO_CODE();
  6100. assert_bdrv_graph_readable();
  6101. trace_bdrv_lock_medium(bs, locked);
  6102. if (drv && drv->bdrv_co_lock_medium) {
  6103. drv->bdrv_co_lock_medium(bs, locked);
  6104. }
  6105. }
  6106. /* Get a reference to bs */
  6107. void bdrv_ref(BlockDriverState *bs)
  6108. {
  6109. GLOBAL_STATE_CODE();
  6110. bs->refcnt++;
  6111. }
  6112. /* Release a previously grabbed reference to bs.
  6113. * If after releasing, reference count is zero, the BlockDriverState is
  6114. * deleted. */
  6115. void bdrv_unref(BlockDriverState *bs)
  6116. {
  6117. GLOBAL_STATE_CODE();
  6118. if (!bs) {
  6119. return;
  6120. }
  6121. assert(bs->refcnt > 0);
  6122. if (--bs->refcnt == 0) {
  6123. bdrv_delete(bs);
  6124. }
  6125. }
  6126. static void bdrv_schedule_unref_bh(void *opaque)
  6127. {
  6128. BlockDriverState *bs = opaque;
  6129. bdrv_unref(bs);
  6130. }
  6131. /*
  6132. * Release a BlockDriverState reference while holding the graph write lock.
  6133. *
  6134. * Calling bdrv_unref() directly is forbidden while holding the graph lock
  6135. * because bdrv_close() both involves polling and taking the graph lock
  6136. * internally. bdrv_schedule_unref() instead delays decreasing the refcount and
  6137. * possibly closing @bs until the graph lock is released.
  6138. */
  6139. void bdrv_schedule_unref(BlockDriverState *bs)
  6140. {
  6141. if (!bs) {
  6142. return;
  6143. }
  6144. aio_bh_schedule_oneshot(qemu_get_aio_context(), bdrv_schedule_unref_bh, bs);
  6145. }
  6146. struct BdrvOpBlocker {
  6147. Error *reason;
  6148. QLIST_ENTRY(BdrvOpBlocker) list;
  6149. };
  6150. bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
  6151. {
  6152. BdrvOpBlocker *blocker;
  6153. GLOBAL_STATE_CODE();
  6154. assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
  6155. if (!QLIST_EMPTY(&bs->op_blockers[op])) {
  6156. blocker = QLIST_FIRST(&bs->op_blockers[op]);
  6157. error_propagate_prepend(errp, error_copy(blocker->reason),
  6158. "Node '%s' is busy: ",
  6159. bdrv_get_device_or_node_name(bs));
  6160. return true;
  6161. }
  6162. return false;
  6163. }
  6164. void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
  6165. {
  6166. BdrvOpBlocker *blocker;
  6167. GLOBAL_STATE_CODE();
  6168. assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
  6169. blocker = g_new0(BdrvOpBlocker, 1);
  6170. blocker->reason = reason;
  6171. QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
  6172. }
  6173. void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
  6174. {
  6175. BdrvOpBlocker *blocker, *next;
  6176. GLOBAL_STATE_CODE();
  6177. assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
  6178. QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
  6179. if (blocker->reason == reason) {
  6180. QLIST_REMOVE(blocker, list);
  6181. g_free(blocker);
  6182. }
  6183. }
  6184. }
  6185. void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
  6186. {
  6187. int i;
  6188. GLOBAL_STATE_CODE();
  6189. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  6190. bdrv_op_block(bs, i, reason);
  6191. }
  6192. }
  6193. void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
  6194. {
  6195. int i;
  6196. GLOBAL_STATE_CODE();
  6197. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  6198. bdrv_op_unblock(bs, i, reason);
  6199. }
  6200. }
  6201. bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
  6202. {
  6203. int i;
  6204. GLOBAL_STATE_CODE();
  6205. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  6206. if (!QLIST_EMPTY(&bs->op_blockers[i])) {
  6207. return false;
  6208. }
  6209. }
  6210. return true;
  6211. }
  6212. /*
  6213. * Must not be called while holding the lock of an AioContext other than the
  6214. * current one.
  6215. */
  6216. void bdrv_img_create(const char *filename, const char *fmt,
  6217. const char *base_filename, const char *base_fmt,
  6218. char *options, uint64_t img_size, int flags, bool quiet,
  6219. Error **errp)
  6220. {
  6221. QemuOptsList *create_opts = NULL;
  6222. QemuOpts *opts = NULL;
  6223. const char *backing_fmt, *backing_file;
  6224. int64_t size;
  6225. BlockDriver *drv, *proto_drv;
  6226. Error *local_err = NULL;
  6227. int ret = 0;
  6228. GLOBAL_STATE_CODE();
  6229. /* Find driver and parse its options */
  6230. drv = bdrv_find_format(fmt);
  6231. if (!drv) {
  6232. error_setg(errp, "Unknown file format '%s'", fmt);
  6233. return;
  6234. }
  6235. proto_drv = bdrv_find_protocol(filename, true, errp);
  6236. if (!proto_drv) {
  6237. return;
  6238. }
  6239. if (!drv->create_opts) {
  6240. error_setg(errp, "Format driver '%s' does not support image creation",
  6241. drv->format_name);
  6242. return;
  6243. }
  6244. if (!proto_drv->create_opts) {
  6245. error_setg(errp, "Protocol driver '%s' does not support image creation",
  6246. proto_drv->format_name);
  6247. return;
  6248. }
  6249. /* Create parameter list */
  6250. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  6251. create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
  6252. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  6253. /* Parse -o options */
  6254. if (options) {
  6255. if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
  6256. goto out;
  6257. }
  6258. }
  6259. if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
  6260. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
  6261. } else if (img_size != UINT64_C(-1)) {
  6262. error_setg(errp, "The image size must be specified only once");
  6263. goto out;
  6264. }
  6265. if (base_filename) {
  6266. if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
  6267. NULL)) {
  6268. error_setg(errp, "Backing file not supported for file format '%s'",
  6269. fmt);
  6270. goto out;
  6271. }
  6272. }
  6273. if (base_fmt) {
  6274. if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
  6275. error_setg(errp, "Backing file format not supported for file "
  6276. "format '%s'", fmt);
  6277. goto out;
  6278. }
  6279. }
  6280. backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
  6281. if (backing_file) {
  6282. if (!strcmp(filename, backing_file)) {
  6283. error_setg(errp, "Error: Trying to create an image with the "
  6284. "same filename as the backing file");
  6285. goto out;
  6286. }
  6287. if (backing_file[0] == '\0') {
  6288. error_setg(errp, "Expected backing file name, got empty string");
  6289. goto out;
  6290. }
  6291. }
  6292. backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
  6293. /* The size for the image must always be specified, unless we have a backing
  6294. * file and we have not been forbidden from opening it. */
  6295. size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
  6296. if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
  6297. BlockDriverState *bs;
  6298. char *full_backing;
  6299. int back_flags;
  6300. QDict *backing_options = NULL;
  6301. full_backing =
  6302. bdrv_get_full_backing_filename_from_filename(filename, backing_file,
  6303. &local_err);
  6304. if (local_err) {
  6305. goto out;
  6306. }
  6307. assert(full_backing);
  6308. /*
  6309. * No need to do I/O here, which allows us to open encrypted
  6310. * backing images without needing the secret
  6311. */
  6312. back_flags = flags;
  6313. back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
  6314. back_flags |= BDRV_O_NO_IO;
  6315. backing_options = qdict_new();
  6316. if (backing_fmt) {
  6317. qdict_put_str(backing_options, "driver", backing_fmt);
  6318. }
  6319. qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
  6320. bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
  6321. &local_err);
  6322. g_free(full_backing);
  6323. if (!bs) {
  6324. error_append_hint(&local_err, "Could not open backing image.\n");
  6325. goto out;
  6326. } else {
  6327. if (!backing_fmt) {
  6328. error_setg(&local_err,
  6329. "Backing file specified without backing format");
  6330. error_append_hint(&local_err, "Detected format of %s.\n",
  6331. bs->drv->format_name);
  6332. goto out;
  6333. }
  6334. if (size == -1) {
  6335. /* Opened BS, have no size */
  6336. size = bdrv_getlength(bs);
  6337. if (size < 0) {
  6338. error_setg_errno(errp, -size, "Could not get size of '%s'",
  6339. backing_file);
  6340. bdrv_unref(bs);
  6341. goto out;
  6342. }
  6343. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
  6344. }
  6345. bdrv_unref(bs);
  6346. }
  6347. /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
  6348. } else if (backing_file && !backing_fmt) {
  6349. error_setg(&local_err,
  6350. "Backing file specified without backing format");
  6351. goto out;
  6352. }
  6353. /* Parameter 'size' is not needed for detached LUKS header */
  6354. if (size == -1 &&
  6355. !(!strcmp(fmt, "luks") &&
  6356. qemu_opt_get_bool(opts, "detached-header", false))) {
  6357. error_setg(errp, "Image creation needs a size parameter");
  6358. goto out;
  6359. }
  6360. if (!quiet) {
  6361. printf("Formatting '%s', fmt=%s ", filename, fmt);
  6362. qemu_opts_print(opts, " ");
  6363. puts("");
  6364. fflush(stdout);
  6365. }
  6366. ret = bdrv_create(drv, filename, opts, &local_err);
  6367. if (ret == -EFBIG) {
  6368. /* This is generally a better message than whatever the driver would
  6369. * deliver (especially because of the cluster_size_hint), since that
  6370. * is most probably not much different from "image too large". */
  6371. const char *cluster_size_hint = "";
  6372. if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
  6373. cluster_size_hint = " (try using a larger cluster size)";
  6374. }
  6375. error_setg(errp, "The image size is too large for file format '%s'"
  6376. "%s", fmt, cluster_size_hint);
  6377. error_free(local_err);
  6378. local_err = NULL;
  6379. }
  6380. out:
  6381. qemu_opts_del(opts);
  6382. qemu_opts_free(create_opts);
  6383. error_propagate(errp, local_err);
  6384. }
  6385. AioContext *bdrv_get_aio_context(BlockDriverState *bs)
  6386. {
  6387. IO_CODE();
  6388. return bs ? bs->aio_context : qemu_get_aio_context();
  6389. }
  6390. AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
  6391. {
  6392. Coroutine *self = qemu_coroutine_self();
  6393. AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
  6394. AioContext *new_ctx;
  6395. IO_CODE();
  6396. /*
  6397. * Increase bs->in_flight to ensure that this operation is completed before
  6398. * moving the node to a different AioContext. Read new_ctx only afterwards.
  6399. */
  6400. bdrv_inc_in_flight(bs);
  6401. new_ctx = bdrv_get_aio_context(bs);
  6402. aio_co_reschedule_self(new_ctx);
  6403. return old_ctx;
  6404. }
  6405. void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
  6406. {
  6407. IO_CODE();
  6408. aio_co_reschedule_self(old_ctx);
  6409. bdrv_dec_in_flight(bs);
  6410. }
  6411. static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
  6412. {
  6413. GLOBAL_STATE_CODE();
  6414. QLIST_REMOVE(ban, list);
  6415. g_free(ban);
  6416. }
  6417. static void bdrv_detach_aio_context(BlockDriverState *bs)
  6418. {
  6419. BdrvAioNotifier *baf, *baf_tmp;
  6420. assert(!bs->walking_aio_notifiers);
  6421. GLOBAL_STATE_CODE();
  6422. bs->walking_aio_notifiers = true;
  6423. QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
  6424. if (baf->deleted) {
  6425. bdrv_do_remove_aio_context_notifier(baf);
  6426. } else {
  6427. baf->detach_aio_context(baf->opaque);
  6428. }
  6429. }
  6430. /* Never mind iterating again to check for ->deleted. bdrv_close() will
  6431. * remove remaining aio notifiers if we aren't called again.
  6432. */
  6433. bs->walking_aio_notifiers = false;
  6434. if (bs->drv && bs->drv->bdrv_detach_aio_context) {
  6435. bs->drv->bdrv_detach_aio_context(bs);
  6436. }
  6437. bs->aio_context = NULL;
  6438. }
  6439. static void bdrv_attach_aio_context(BlockDriverState *bs,
  6440. AioContext *new_context)
  6441. {
  6442. BdrvAioNotifier *ban, *ban_tmp;
  6443. GLOBAL_STATE_CODE();
  6444. bs->aio_context = new_context;
  6445. if (bs->drv && bs->drv->bdrv_attach_aio_context) {
  6446. bs->drv->bdrv_attach_aio_context(bs, new_context);
  6447. }
  6448. assert(!bs->walking_aio_notifiers);
  6449. bs->walking_aio_notifiers = true;
  6450. QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
  6451. if (ban->deleted) {
  6452. bdrv_do_remove_aio_context_notifier(ban);
  6453. } else {
  6454. ban->attached_aio_context(new_context, ban->opaque);
  6455. }
  6456. }
  6457. bs->walking_aio_notifiers = false;
  6458. }
  6459. typedef struct BdrvStateSetAioContext {
  6460. AioContext *new_ctx;
  6461. BlockDriverState *bs;
  6462. } BdrvStateSetAioContext;
  6463. static bool bdrv_parent_change_aio_context(BdrvChild *c, AioContext *ctx,
  6464. GHashTable *visited,
  6465. Transaction *tran,
  6466. Error **errp)
  6467. {
  6468. GLOBAL_STATE_CODE();
  6469. if (g_hash_table_contains(visited, c)) {
  6470. return true;
  6471. }
  6472. g_hash_table_add(visited, c);
  6473. /*
  6474. * A BdrvChildClass that doesn't handle AioContext changes cannot
  6475. * tolerate any AioContext changes
  6476. */
  6477. if (!c->klass->change_aio_ctx) {
  6478. char *user = bdrv_child_user_desc(c);
  6479. error_setg(errp, "Changing iothreads is not supported by %s", user);
  6480. g_free(user);
  6481. return false;
  6482. }
  6483. if (!c->klass->change_aio_ctx(c, ctx, visited, tran, errp)) {
  6484. assert(!errp || *errp);
  6485. return false;
  6486. }
  6487. return true;
  6488. }
  6489. bool bdrv_child_change_aio_context(BdrvChild *c, AioContext *ctx,
  6490. GHashTable *visited, Transaction *tran,
  6491. Error **errp)
  6492. {
  6493. GLOBAL_STATE_CODE();
  6494. if (g_hash_table_contains(visited, c)) {
  6495. return true;
  6496. }
  6497. g_hash_table_add(visited, c);
  6498. return bdrv_change_aio_context(c->bs, ctx, visited, tran, errp);
  6499. }
  6500. static void bdrv_set_aio_context_clean(void *opaque)
  6501. {
  6502. BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
  6503. BlockDriverState *bs = (BlockDriverState *) state->bs;
  6504. /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
  6505. bdrv_drained_end(bs);
  6506. g_free(state);
  6507. }
  6508. static void bdrv_set_aio_context_commit(void *opaque)
  6509. {
  6510. BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
  6511. BlockDriverState *bs = (BlockDriverState *) state->bs;
  6512. AioContext *new_context = state->new_ctx;
  6513. bdrv_detach_aio_context(bs);
  6514. bdrv_attach_aio_context(bs, new_context);
  6515. }
  6516. static TransactionActionDrv set_aio_context = {
  6517. .commit = bdrv_set_aio_context_commit,
  6518. .clean = bdrv_set_aio_context_clean,
  6519. };
  6520. /*
  6521. * Changes the AioContext used for fd handlers, timers, and BHs by this
  6522. * BlockDriverState and all its children and parents.
  6523. *
  6524. * Must be called from the main AioContext.
  6525. *
  6526. * @visited will accumulate all visited BdrvChild objects. The caller is
  6527. * responsible for freeing the list afterwards.
  6528. */
  6529. static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
  6530. GHashTable *visited, Transaction *tran,
  6531. Error **errp)
  6532. {
  6533. BdrvChild *c;
  6534. BdrvStateSetAioContext *state;
  6535. GLOBAL_STATE_CODE();
  6536. if (bdrv_get_aio_context(bs) == ctx) {
  6537. return true;
  6538. }
  6539. bdrv_graph_rdlock_main_loop();
  6540. QLIST_FOREACH(c, &bs->parents, next_parent) {
  6541. if (!bdrv_parent_change_aio_context(c, ctx, visited, tran, errp)) {
  6542. bdrv_graph_rdunlock_main_loop();
  6543. return false;
  6544. }
  6545. }
  6546. QLIST_FOREACH(c, &bs->children, next) {
  6547. if (!bdrv_child_change_aio_context(c, ctx, visited, tran, errp)) {
  6548. bdrv_graph_rdunlock_main_loop();
  6549. return false;
  6550. }
  6551. }
  6552. bdrv_graph_rdunlock_main_loop();
  6553. state = g_new(BdrvStateSetAioContext, 1);
  6554. *state = (BdrvStateSetAioContext) {
  6555. .new_ctx = ctx,
  6556. .bs = bs,
  6557. };
  6558. /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
  6559. bdrv_drained_begin(bs);
  6560. tran_add(tran, &set_aio_context, state);
  6561. return true;
  6562. }
  6563. /*
  6564. * Change bs's and recursively all of its parents' and children's AioContext
  6565. * to the given new context, returning an error if that isn't possible.
  6566. *
  6567. * If ignore_child is not NULL, that child (and its subgraph) will not
  6568. * be touched.
  6569. */
  6570. int bdrv_try_change_aio_context(BlockDriverState *bs, AioContext *ctx,
  6571. BdrvChild *ignore_child, Error **errp)
  6572. {
  6573. Transaction *tran;
  6574. GHashTable *visited;
  6575. int ret;
  6576. GLOBAL_STATE_CODE();
  6577. /*
  6578. * Recursion phase: go through all nodes of the graph.
  6579. * Take care of checking that all nodes support changing AioContext
  6580. * and drain them, building a linear list of callbacks to run if everything
  6581. * is successful (the transaction itself).
  6582. */
  6583. tran = tran_new();
  6584. visited = g_hash_table_new(NULL, NULL);
  6585. if (ignore_child) {
  6586. g_hash_table_add(visited, ignore_child);
  6587. }
  6588. ret = bdrv_change_aio_context(bs, ctx, visited, tran, errp);
  6589. g_hash_table_destroy(visited);
  6590. /*
  6591. * Linear phase: go through all callbacks collected in the transaction.
  6592. * Run all callbacks collected in the recursion to switch every node's
  6593. * AioContext (transaction commit), or undo all changes done in the
  6594. * recursion (transaction abort).
  6595. */
  6596. if (!ret) {
  6597. /* Just run clean() callbacks. No AioContext changed. */
  6598. tran_abort(tran);
  6599. return -EPERM;
  6600. }
  6601. tran_commit(tran);
  6602. return 0;
  6603. }
  6604. void bdrv_add_aio_context_notifier(BlockDriverState *bs,
  6605. void (*attached_aio_context)(AioContext *new_context, void *opaque),
  6606. void (*detach_aio_context)(void *opaque), void *opaque)
  6607. {
  6608. BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
  6609. *ban = (BdrvAioNotifier){
  6610. .attached_aio_context = attached_aio_context,
  6611. .detach_aio_context = detach_aio_context,
  6612. .opaque = opaque
  6613. };
  6614. GLOBAL_STATE_CODE();
  6615. QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
  6616. }
  6617. void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
  6618. void (*attached_aio_context)(AioContext *,
  6619. void *),
  6620. void (*detach_aio_context)(void *),
  6621. void *opaque)
  6622. {
  6623. BdrvAioNotifier *ban, *ban_next;
  6624. GLOBAL_STATE_CODE();
  6625. QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
  6626. if (ban->attached_aio_context == attached_aio_context &&
  6627. ban->detach_aio_context == detach_aio_context &&
  6628. ban->opaque == opaque &&
  6629. ban->deleted == false)
  6630. {
  6631. if (bs->walking_aio_notifiers) {
  6632. ban->deleted = true;
  6633. } else {
  6634. bdrv_do_remove_aio_context_notifier(ban);
  6635. }
  6636. return;
  6637. }
  6638. }
  6639. abort();
  6640. }
  6641. int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
  6642. BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
  6643. bool force,
  6644. Error **errp)
  6645. {
  6646. GLOBAL_STATE_CODE();
  6647. if (!bs->drv) {
  6648. error_setg(errp, "Node is ejected");
  6649. return -ENOMEDIUM;
  6650. }
  6651. if (!bs->drv->bdrv_amend_options) {
  6652. error_setg(errp, "Block driver '%s' does not support option amendment",
  6653. bs->drv->format_name);
  6654. return -ENOTSUP;
  6655. }
  6656. return bs->drv->bdrv_amend_options(bs, opts, status_cb,
  6657. cb_opaque, force, errp);
  6658. }
  6659. /*
  6660. * This function checks whether the given @to_replace is allowed to be
  6661. * replaced by a node that always shows the same data as @bs. This is
  6662. * used for example to verify whether the mirror job can replace
  6663. * @to_replace by the target mirrored from @bs.
  6664. * To be replaceable, @bs and @to_replace may either be guaranteed to
  6665. * always show the same data (because they are only connected through
  6666. * filters), or some driver may allow replacing one of its children
  6667. * because it can guarantee that this child's data is not visible at
  6668. * all (for example, for dissenting quorum children that have no other
  6669. * parents).
  6670. */
  6671. bool bdrv_recurse_can_replace(BlockDriverState *bs,
  6672. BlockDriverState *to_replace)
  6673. {
  6674. BlockDriverState *filtered;
  6675. GLOBAL_STATE_CODE();
  6676. if (!bs || !bs->drv) {
  6677. return false;
  6678. }
  6679. if (bs == to_replace) {
  6680. return true;
  6681. }
  6682. /* See what the driver can do */
  6683. if (bs->drv->bdrv_recurse_can_replace) {
  6684. return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
  6685. }
  6686. /* For filters without an own implementation, we can recurse on our own */
  6687. filtered = bdrv_filter_bs(bs);
  6688. if (filtered) {
  6689. return bdrv_recurse_can_replace(filtered, to_replace);
  6690. }
  6691. /* Safe default */
  6692. return false;
  6693. }
  6694. /*
  6695. * Check whether the given @node_name can be replaced by a node that
  6696. * has the same data as @parent_bs. If so, return @node_name's BDS;
  6697. * NULL otherwise.
  6698. *
  6699. * @node_name must be a (recursive) *child of @parent_bs (or this
  6700. * function will return NULL).
  6701. *
  6702. * The result (whether the node can be replaced or not) is only valid
  6703. * for as long as no graph or permission changes occur.
  6704. */
  6705. BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
  6706. const char *node_name, Error **errp)
  6707. {
  6708. BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
  6709. GLOBAL_STATE_CODE();
  6710. if (!to_replace_bs) {
  6711. error_setg(errp, "Failed to find node with node-name='%s'", node_name);
  6712. return NULL;
  6713. }
  6714. if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
  6715. return NULL;
  6716. }
  6717. /* We don't want arbitrary node of the BDS chain to be replaced only the top
  6718. * most non filter in order to prevent data corruption.
  6719. * Another benefit is that this tests exclude backing files which are
  6720. * blocked by the backing blockers.
  6721. */
  6722. if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
  6723. error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
  6724. "because it cannot be guaranteed that doing so would not "
  6725. "lead to an abrupt change of visible data",
  6726. node_name, parent_bs->node_name);
  6727. return NULL;
  6728. }
  6729. return to_replace_bs;
  6730. }
  6731. /**
  6732. * Iterates through the list of runtime option keys that are said to
  6733. * be "strong" for a BDS. An option is called "strong" if it changes
  6734. * a BDS's data. For example, the null block driver's "size" and
  6735. * "read-zeroes" options are strong, but its "latency-ns" option is
  6736. * not.
  6737. *
  6738. * If a key returned by this function ends with a dot, all options
  6739. * starting with that prefix are strong.
  6740. */
  6741. static const char *const *strong_options(BlockDriverState *bs,
  6742. const char *const *curopt)
  6743. {
  6744. static const char *const global_options[] = {
  6745. "driver", "filename", NULL
  6746. };
  6747. if (!curopt) {
  6748. return &global_options[0];
  6749. }
  6750. curopt++;
  6751. if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
  6752. curopt = bs->drv->strong_runtime_opts;
  6753. }
  6754. return (curopt && *curopt) ? curopt : NULL;
  6755. }
  6756. /**
  6757. * Copies all strong runtime options from bs->options to the given
  6758. * QDict. The set of strong option keys is determined by invoking
  6759. * strong_options().
  6760. *
  6761. * Returns true iff any strong option was present in bs->options (and
  6762. * thus copied to the target QDict) with the exception of "filename"
  6763. * and "driver". The caller is expected to use this value to decide
  6764. * whether the existence of strong options prevents the generation of
  6765. * a plain filename.
  6766. */
  6767. static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
  6768. {
  6769. bool found_any = false;
  6770. const char *const *option_name = NULL;
  6771. if (!bs->drv) {
  6772. return false;
  6773. }
  6774. while ((option_name = strong_options(bs, option_name))) {
  6775. bool option_given = false;
  6776. assert(strlen(*option_name) > 0);
  6777. if ((*option_name)[strlen(*option_name) - 1] != '.') {
  6778. QObject *entry = qdict_get(bs->options, *option_name);
  6779. if (!entry) {
  6780. continue;
  6781. }
  6782. qdict_put_obj(d, *option_name, qobject_ref(entry));
  6783. option_given = true;
  6784. } else {
  6785. const QDictEntry *entry;
  6786. for (entry = qdict_first(bs->options); entry;
  6787. entry = qdict_next(bs->options, entry))
  6788. {
  6789. if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
  6790. qdict_put_obj(d, qdict_entry_key(entry),
  6791. qobject_ref(qdict_entry_value(entry)));
  6792. option_given = true;
  6793. }
  6794. }
  6795. }
  6796. /* While "driver" and "filename" need to be included in a JSON filename,
  6797. * their existence does not prohibit generation of a plain filename. */
  6798. if (!found_any && option_given &&
  6799. strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
  6800. {
  6801. found_any = true;
  6802. }
  6803. }
  6804. if (!qdict_haskey(d, "driver")) {
  6805. /* Drivers created with bdrv_new_open_driver() may not have a
  6806. * @driver option. Add it here. */
  6807. qdict_put_str(d, "driver", bs->drv->format_name);
  6808. }
  6809. return found_any;
  6810. }
  6811. /* Note: This function may return false positives; it may return true
  6812. * even if opening the backing file specified by bs's image header
  6813. * would result in exactly bs->backing. */
  6814. static bool GRAPH_RDLOCK bdrv_backing_overridden(BlockDriverState *bs)
  6815. {
  6816. GLOBAL_STATE_CODE();
  6817. if (bs->backing) {
  6818. return strcmp(bs->auto_backing_file,
  6819. bs->backing->bs->filename);
  6820. } else {
  6821. /* No backing BDS, so if the image header reports any backing
  6822. * file, it must have been suppressed */
  6823. return bs->auto_backing_file[0] != '\0';
  6824. }
  6825. }
  6826. /* Updates the following BDS fields:
  6827. * - exact_filename: A filename which may be used for opening a block device
  6828. * which (mostly) equals the given BDS (even without any
  6829. * other options; so reading and writing must return the same
  6830. * results, but caching etc. may be different)
  6831. * - full_open_options: Options which, when given when opening a block device
  6832. * (without a filename), result in a BDS (mostly)
  6833. * equalling the given one
  6834. * - filename: If exact_filename is set, it is copied here. Otherwise,
  6835. * full_open_options is converted to a JSON object, prefixed with
  6836. * "json:" (for use through the JSON pseudo protocol) and put here.
  6837. */
  6838. void bdrv_refresh_filename(BlockDriverState *bs)
  6839. {
  6840. BlockDriver *drv = bs->drv;
  6841. BdrvChild *child;
  6842. BlockDriverState *primary_child_bs;
  6843. QDict *opts;
  6844. bool backing_overridden;
  6845. bool generate_json_filename; /* Whether our default implementation should
  6846. fill exact_filename (false) or not (true) */
  6847. GLOBAL_STATE_CODE();
  6848. if (!drv) {
  6849. return;
  6850. }
  6851. /* This BDS's file name may depend on any of its children's file names, so
  6852. * refresh those first */
  6853. QLIST_FOREACH(child, &bs->children, next) {
  6854. bdrv_refresh_filename(child->bs);
  6855. }
  6856. if (bs->implicit) {
  6857. /* For implicit nodes, just copy everything from the single child */
  6858. child = QLIST_FIRST(&bs->children);
  6859. assert(QLIST_NEXT(child, next) == NULL);
  6860. pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
  6861. child->bs->exact_filename);
  6862. pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
  6863. qobject_unref(bs->full_open_options);
  6864. bs->full_open_options = qobject_ref(child->bs->full_open_options);
  6865. return;
  6866. }
  6867. backing_overridden = bdrv_backing_overridden(bs);
  6868. if (bs->open_flags & BDRV_O_NO_IO) {
  6869. /* Without I/O, the backing file does not change anything.
  6870. * Therefore, in such a case (primarily qemu-img), we can
  6871. * pretend the backing file has not been overridden even if
  6872. * it technically has been. */
  6873. backing_overridden = false;
  6874. }
  6875. /* Gather the options QDict */
  6876. opts = qdict_new();
  6877. generate_json_filename = append_strong_runtime_options(opts, bs);
  6878. generate_json_filename |= backing_overridden;
  6879. if (drv->bdrv_gather_child_options) {
  6880. /* Some block drivers may not want to present all of their children's
  6881. * options, or name them differently from BdrvChild.name */
  6882. drv->bdrv_gather_child_options(bs, opts, backing_overridden);
  6883. } else {
  6884. QLIST_FOREACH(child, &bs->children, next) {
  6885. if (child == bs->backing && !backing_overridden) {
  6886. /* We can skip the backing BDS if it has not been overridden */
  6887. continue;
  6888. }
  6889. qdict_put(opts, child->name,
  6890. qobject_ref(child->bs->full_open_options));
  6891. }
  6892. if (backing_overridden && !bs->backing) {
  6893. /* Force no backing file */
  6894. qdict_put_null(opts, "backing");
  6895. }
  6896. }
  6897. qobject_unref(bs->full_open_options);
  6898. bs->full_open_options = opts;
  6899. primary_child_bs = bdrv_primary_bs(bs);
  6900. if (drv->bdrv_refresh_filename) {
  6901. /* Obsolete information is of no use here, so drop the old file name
  6902. * information before refreshing it */
  6903. bs->exact_filename[0] = '\0';
  6904. drv->bdrv_refresh_filename(bs);
  6905. } else if (primary_child_bs) {
  6906. /*
  6907. * Try to reconstruct valid information from the underlying
  6908. * file -- this only works for format nodes (filter nodes
  6909. * cannot be probed and as such must be selected by the user
  6910. * either through an options dict, or through a special
  6911. * filename which the filter driver must construct in its
  6912. * .bdrv_refresh_filename() implementation).
  6913. */
  6914. bs->exact_filename[0] = '\0';
  6915. /*
  6916. * We can use the underlying file's filename if:
  6917. * - it has a filename,
  6918. * - the current BDS is not a filter,
  6919. * - the file is a protocol BDS, and
  6920. * - opening that file (as this BDS's format) will automatically create
  6921. * the BDS tree we have right now, that is:
  6922. * - the user did not significantly change this BDS's behavior with
  6923. * some explicit (strong) options
  6924. * - no non-file child of this BDS has been overridden by the user
  6925. * Both of these conditions are represented by generate_json_filename.
  6926. */
  6927. if (primary_child_bs->exact_filename[0] &&
  6928. primary_child_bs->drv->protocol_name &&
  6929. !drv->is_filter && !generate_json_filename)
  6930. {
  6931. strcpy(bs->exact_filename, primary_child_bs->exact_filename);
  6932. }
  6933. }
  6934. if (bs->exact_filename[0]) {
  6935. pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
  6936. } else {
  6937. GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
  6938. if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
  6939. json->str) >= sizeof(bs->filename)) {
  6940. /* Give user a hint if we truncated things. */
  6941. strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
  6942. }
  6943. g_string_free(json, true);
  6944. }
  6945. }
  6946. char *bdrv_dirname(BlockDriverState *bs, Error **errp)
  6947. {
  6948. BlockDriver *drv = bs->drv;
  6949. BlockDriverState *child_bs;
  6950. GLOBAL_STATE_CODE();
  6951. if (!drv) {
  6952. error_setg(errp, "Node '%s' is ejected", bs->node_name);
  6953. return NULL;
  6954. }
  6955. if (drv->bdrv_dirname) {
  6956. return drv->bdrv_dirname(bs, errp);
  6957. }
  6958. child_bs = bdrv_primary_bs(bs);
  6959. if (child_bs) {
  6960. return bdrv_dirname(child_bs, errp);
  6961. }
  6962. bdrv_refresh_filename(bs);
  6963. if (bs->exact_filename[0] != '\0') {
  6964. return path_combine(bs->exact_filename, "");
  6965. }
  6966. error_setg(errp, "Cannot generate a base directory for %s nodes",
  6967. drv->format_name);
  6968. return NULL;
  6969. }
  6970. /*
  6971. * Hot add/remove a BDS's child. So the user can take a child offline when
  6972. * it is broken and take a new child online
  6973. */
  6974. void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
  6975. Error **errp)
  6976. {
  6977. GLOBAL_STATE_CODE();
  6978. if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
  6979. error_setg(errp, "The node %s does not support adding a child",
  6980. bdrv_get_device_or_node_name(parent_bs));
  6981. return;
  6982. }
  6983. /*
  6984. * Non-zoned block drivers do not follow zoned storage constraints
  6985. * (i.e. sequential writes to zones). Refuse mixing zoned and non-zoned
  6986. * drivers in a graph.
  6987. */
  6988. if (!parent_bs->drv->supports_zoned_children &&
  6989. child_bs->bl.zoned == BLK_Z_HM) {
  6990. /*
  6991. * The host-aware model allows zoned storage constraints and random
  6992. * write. Allow mixing host-aware and non-zoned drivers. Using
  6993. * host-aware device as a regular device.
  6994. */
  6995. error_setg(errp, "Cannot add a %s child to a %s parent",
  6996. child_bs->bl.zoned == BLK_Z_HM ? "zoned" : "non-zoned",
  6997. parent_bs->drv->supports_zoned_children ?
  6998. "support zoned children" : "not support zoned children");
  6999. return;
  7000. }
  7001. if (!QLIST_EMPTY(&child_bs->parents)) {
  7002. error_setg(errp, "The node %s already has a parent",
  7003. child_bs->node_name);
  7004. return;
  7005. }
  7006. parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
  7007. }
  7008. void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
  7009. {
  7010. BdrvChild *tmp;
  7011. GLOBAL_STATE_CODE();
  7012. if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
  7013. error_setg(errp, "The node %s does not support removing a child",
  7014. bdrv_get_device_or_node_name(parent_bs));
  7015. return;
  7016. }
  7017. QLIST_FOREACH(tmp, &parent_bs->children, next) {
  7018. if (tmp == child) {
  7019. break;
  7020. }
  7021. }
  7022. if (!tmp) {
  7023. error_setg(errp, "The node %s does not have a child named %s",
  7024. bdrv_get_device_or_node_name(parent_bs),
  7025. bdrv_get_device_or_node_name(child->bs));
  7026. return;
  7027. }
  7028. parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
  7029. }
  7030. int bdrv_make_empty(BdrvChild *c, Error **errp)
  7031. {
  7032. BlockDriver *drv = c->bs->drv;
  7033. int ret;
  7034. GLOBAL_STATE_CODE();
  7035. assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
  7036. if (!drv->bdrv_make_empty) {
  7037. error_setg(errp, "%s does not support emptying nodes",
  7038. drv->format_name);
  7039. return -ENOTSUP;
  7040. }
  7041. ret = drv->bdrv_make_empty(c->bs);
  7042. if (ret < 0) {
  7043. error_setg_errno(errp, -ret, "Failed to empty %s",
  7044. c->bs->filename);
  7045. return ret;
  7046. }
  7047. return 0;
  7048. }
  7049. /*
  7050. * Return the child that @bs acts as an overlay for, and from which data may be
  7051. * copied in COW or COR operations. Usually this is the backing file.
  7052. */
  7053. BdrvChild *bdrv_cow_child(BlockDriverState *bs)
  7054. {
  7055. IO_CODE();
  7056. if (!bs || !bs->drv) {
  7057. return NULL;
  7058. }
  7059. if (bs->drv->is_filter) {
  7060. return NULL;
  7061. }
  7062. if (!bs->backing) {
  7063. return NULL;
  7064. }
  7065. assert(bs->backing->role & BDRV_CHILD_COW);
  7066. return bs->backing;
  7067. }
  7068. /*
  7069. * If @bs acts as a filter for exactly one of its children, return
  7070. * that child.
  7071. */
  7072. BdrvChild *bdrv_filter_child(BlockDriverState *bs)
  7073. {
  7074. BdrvChild *c;
  7075. IO_CODE();
  7076. if (!bs || !bs->drv) {
  7077. return NULL;
  7078. }
  7079. if (!bs->drv->is_filter) {
  7080. return NULL;
  7081. }
  7082. /* Only one of @backing or @file may be used */
  7083. assert(!(bs->backing && bs->file));
  7084. c = bs->backing ?: bs->file;
  7085. if (!c) {
  7086. return NULL;
  7087. }
  7088. assert(c->role & BDRV_CHILD_FILTERED);
  7089. return c;
  7090. }
  7091. /*
  7092. * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
  7093. * whichever is non-NULL.
  7094. *
  7095. * Return NULL if both are NULL.
  7096. */
  7097. BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
  7098. {
  7099. BdrvChild *cow_child = bdrv_cow_child(bs);
  7100. BdrvChild *filter_child = bdrv_filter_child(bs);
  7101. IO_CODE();
  7102. /* Filter nodes cannot have COW backing files */
  7103. assert(!(cow_child && filter_child));
  7104. return cow_child ?: filter_child;
  7105. }
  7106. /*
  7107. * Return the primary child of this node: For filters, that is the
  7108. * filtered child. For other nodes, that is usually the child storing
  7109. * metadata.
  7110. * (A generally more helpful description is that this is (usually) the
  7111. * child that has the same filename as @bs.)
  7112. *
  7113. * Drivers do not necessarily have a primary child; for example quorum
  7114. * does not.
  7115. */
  7116. BdrvChild *bdrv_primary_child(BlockDriverState *bs)
  7117. {
  7118. BdrvChild *c, *found = NULL;
  7119. IO_CODE();
  7120. QLIST_FOREACH(c, &bs->children, next) {
  7121. if (c->role & BDRV_CHILD_PRIMARY) {
  7122. assert(!found);
  7123. found = c;
  7124. }
  7125. }
  7126. return found;
  7127. }
  7128. static BlockDriverState * GRAPH_RDLOCK
  7129. bdrv_do_skip_filters(BlockDriverState *bs, bool stop_on_explicit_filter)
  7130. {
  7131. BdrvChild *c;
  7132. if (!bs) {
  7133. return NULL;
  7134. }
  7135. while (!(stop_on_explicit_filter && !bs->implicit)) {
  7136. c = bdrv_filter_child(bs);
  7137. if (!c) {
  7138. /*
  7139. * A filter that is embedded in a working block graph must
  7140. * have a child. Assert this here so this function does
  7141. * not return a filter node that is not expected by the
  7142. * caller.
  7143. */
  7144. assert(!bs->drv || !bs->drv->is_filter);
  7145. break;
  7146. }
  7147. bs = c->bs;
  7148. }
  7149. /*
  7150. * Note that this treats nodes with bs->drv == NULL as not being
  7151. * filters (bs->drv == NULL should be replaced by something else
  7152. * anyway).
  7153. * The advantage of this behavior is that this function will thus
  7154. * always return a non-NULL value (given a non-NULL @bs).
  7155. */
  7156. return bs;
  7157. }
  7158. /*
  7159. * Return the first BDS that has not been added implicitly or that
  7160. * does not have a filtered child down the chain starting from @bs
  7161. * (including @bs itself).
  7162. */
  7163. BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
  7164. {
  7165. GLOBAL_STATE_CODE();
  7166. return bdrv_do_skip_filters(bs, true);
  7167. }
  7168. /*
  7169. * Return the first BDS that does not have a filtered child down the
  7170. * chain starting from @bs (including @bs itself).
  7171. */
  7172. BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
  7173. {
  7174. IO_CODE();
  7175. return bdrv_do_skip_filters(bs, false);
  7176. }
  7177. /*
  7178. * For a backing chain, return the first non-filter backing image of
  7179. * the first non-filter image.
  7180. */
  7181. BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
  7182. {
  7183. IO_CODE();
  7184. return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
  7185. }
  7186. /**
  7187. * Check whether [offset, offset + bytes) overlaps with the cached
  7188. * block-status data region.
  7189. *
  7190. * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
  7191. * which is what bdrv_bsc_is_data()'s interface needs.
  7192. * Otherwise, *pnum is not touched.
  7193. */
  7194. static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
  7195. int64_t offset, int64_t bytes,
  7196. int64_t *pnum)
  7197. {
  7198. BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
  7199. bool overlaps;
  7200. overlaps =
  7201. qatomic_read(&bsc->valid) &&
  7202. ranges_overlap(offset, bytes, bsc->data_start,
  7203. bsc->data_end - bsc->data_start);
  7204. if (overlaps && pnum) {
  7205. *pnum = bsc->data_end - offset;
  7206. }
  7207. return overlaps;
  7208. }
  7209. /**
  7210. * See block_int.h for this function's documentation.
  7211. */
  7212. bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
  7213. {
  7214. IO_CODE();
  7215. RCU_READ_LOCK_GUARD();
  7216. return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
  7217. }
  7218. /**
  7219. * See block_int.h for this function's documentation.
  7220. */
  7221. void bdrv_bsc_invalidate_range(BlockDriverState *bs,
  7222. int64_t offset, int64_t bytes)
  7223. {
  7224. IO_CODE();
  7225. RCU_READ_LOCK_GUARD();
  7226. if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
  7227. qatomic_set(&bs->block_status_cache->valid, false);
  7228. }
  7229. }
  7230. /**
  7231. * See block_int.h for this function's documentation.
  7232. */
  7233. void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
  7234. {
  7235. BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
  7236. BdrvBlockStatusCache *old_bsc;
  7237. IO_CODE();
  7238. *new_bsc = (BdrvBlockStatusCache) {
  7239. .valid = true,
  7240. .data_start = offset,
  7241. .data_end = offset + bytes,
  7242. };
  7243. QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
  7244. old_bsc = qatomic_rcu_read(&bs->block_status_cache);
  7245. qatomic_rcu_set(&bs->block_status_cache, new_bsc);
  7246. if (old_bsc) {
  7247. g_free_rcu(old_bsc, rcu);
  7248. }
  7249. }