You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

block.c 193KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403
  1. /*
  2. * QEMU System Emulator block driver
  3. *
  4. * Copyright (c) 2003 Fabrice Bellard
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. #include "qemu/osdep.h"
  25. #include "block/trace.h"
  26. #include "block/block_int.h"
  27. #include "block/blockjob.h"
  28. #include "block/nbd.h"
  29. #include "block/qdict.h"
  30. #include "qemu/error-report.h"
  31. #include "module_block.h"
  32. #include "qemu/module.h"
  33. #include "qapi/error.h"
  34. #include "qapi/qmp/qdict.h"
  35. #include "qapi/qmp/qjson.h"
  36. #include "qapi/qmp/qnull.h"
  37. #include "qapi/qmp/qstring.h"
  38. #include "qapi/qobject-output-visitor.h"
  39. #include "qapi/qapi-visit-block-core.h"
  40. #include "sysemu/block-backend.h"
  41. #include "sysemu/sysemu.h"
  42. #include "qemu/notify.h"
  43. #include "qemu/option.h"
  44. #include "qemu/coroutine.h"
  45. #include "block/qapi.h"
  46. #include "qemu/timer.h"
  47. #include "qemu/cutils.h"
  48. #include "qemu/id.h"
  49. #ifdef CONFIG_BSD
  50. #include <sys/ioctl.h>
  51. #include <sys/queue.h>
  52. #ifndef __DragonFly__
  53. #include <sys/disk.h>
  54. #endif
  55. #endif
  56. #ifdef _WIN32
  57. #include <windows.h>
  58. #endif
  59. #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
  60. static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
  61. QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
  62. static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
  63. QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
  64. static QLIST_HEAD(, BlockDriver) bdrv_drivers =
  65. QLIST_HEAD_INITIALIZER(bdrv_drivers);
  66. static BlockDriverState *bdrv_open_inherit(const char *filename,
  67. const char *reference,
  68. QDict *options, int flags,
  69. BlockDriverState *parent,
  70. const BdrvChildRole *child_role,
  71. Error **errp);
  72. /* If non-zero, use only whitelisted block drivers */
  73. static int use_bdrv_whitelist;
  74. #ifdef _WIN32
  75. static int is_windows_drive_prefix(const char *filename)
  76. {
  77. return (((filename[0] >= 'a' && filename[0] <= 'z') ||
  78. (filename[0] >= 'A' && filename[0] <= 'Z')) &&
  79. filename[1] == ':');
  80. }
  81. int is_windows_drive(const char *filename)
  82. {
  83. if (is_windows_drive_prefix(filename) &&
  84. filename[2] == '\0')
  85. return 1;
  86. if (strstart(filename, "\\\\.\\", NULL) ||
  87. strstart(filename, "//./", NULL))
  88. return 1;
  89. return 0;
  90. }
  91. #endif
  92. size_t bdrv_opt_mem_align(BlockDriverState *bs)
  93. {
  94. if (!bs || !bs->drv) {
  95. /* page size or 4k (hdd sector size) should be on the safe side */
  96. return MAX(4096, getpagesize());
  97. }
  98. return bs->bl.opt_mem_alignment;
  99. }
  100. size_t bdrv_min_mem_align(BlockDriverState *bs)
  101. {
  102. if (!bs || !bs->drv) {
  103. /* page size or 4k (hdd sector size) should be on the safe side */
  104. return MAX(4096, getpagesize());
  105. }
  106. return bs->bl.min_mem_alignment;
  107. }
  108. /* check if the path starts with "<protocol>:" */
  109. int path_has_protocol(const char *path)
  110. {
  111. const char *p;
  112. #ifdef _WIN32
  113. if (is_windows_drive(path) ||
  114. is_windows_drive_prefix(path)) {
  115. return 0;
  116. }
  117. p = path + strcspn(path, ":/\\");
  118. #else
  119. p = path + strcspn(path, ":/");
  120. #endif
  121. return *p == ':';
  122. }
  123. int path_is_absolute(const char *path)
  124. {
  125. #ifdef _WIN32
  126. /* specific case for names like: "\\.\d:" */
  127. if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
  128. return 1;
  129. }
  130. return (*path == '/' || *path == '\\');
  131. #else
  132. return (*path == '/');
  133. #endif
  134. }
  135. /* if filename is absolute, just return its duplicate. Otherwise, build a
  136. path to it by considering it is relative to base_path. URL are
  137. supported. */
  138. char *path_combine(const char *base_path, const char *filename)
  139. {
  140. const char *protocol_stripped = NULL;
  141. const char *p, *p1;
  142. char *result;
  143. int len;
  144. if (path_is_absolute(filename)) {
  145. return g_strdup(filename);
  146. }
  147. if (path_has_protocol(base_path)) {
  148. protocol_stripped = strchr(base_path, ':');
  149. if (protocol_stripped) {
  150. protocol_stripped++;
  151. }
  152. }
  153. p = protocol_stripped ?: base_path;
  154. p1 = strrchr(base_path, '/');
  155. #ifdef _WIN32
  156. {
  157. const char *p2;
  158. p2 = strrchr(base_path, '\\');
  159. if (!p1 || p2 > p1) {
  160. p1 = p2;
  161. }
  162. }
  163. #endif
  164. if (p1) {
  165. p1++;
  166. } else {
  167. p1 = base_path;
  168. }
  169. if (p1 > p) {
  170. p = p1;
  171. }
  172. len = p - base_path;
  173. result = g_malloc(len + strlen(filename) + 1);
  174. memcpy(result, base_path, len);
  175. strcpy(result + len, filename);
  176. return result;
  177. }
  178. /*
  179. * Helper function for bdrv_parse_filename() implementations to remove optional
  180. * protocol prefixes (especially "file:") from a filename and for putting the
  181. * stripped filename into the options QDict if there is such a prefix.
  182. */
  183. void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
  184. QDict *options)
  185. {
  186. if (strstart(filename, prefix, &filename)) {
  187. /* Stripping the explicit protocol prefix may result in a protocol
  188. * prefix being (wrongly) detected (if the filename contains a colon) */
  189. if (path_has_protocol(filename)) {
  190. QString *fat_filename;
  191. /* This means there is some colon before the first slash; therefore,
  192. * this cannot be an absolute path */
  193. assert(!path_is_absolute(filename));
  194. /* And we can thus fix the protocol detection issue by prefixing it
  195. * by "./" */
  196. fat_filename = qstring_from_str("./");
  197. qstring_append(fat_filename, filename);
  198. assert(!path_has_protocol(qstring_get_str(fat_filename)));
  199. qdict_put(options, "filename", fat_filename);
  200. } else {
  201. /* If no protocol prefix was detected, we can use the shortened
  202. * filename as-is */
  203. qdict_put_str(options, "filename", filename);
  204. }
  205. }
  206. }
  207. /* Returns whether the image file is opened as read-only. Note that this can
  208. * return false and writing to the image file is still not possible because the
  209. * image is inactivated. */
  210. bool bdrv_is_read_only(BlockDriverState *bs)
  211. {
  212. return bs->read_only;
  213. }
  214. int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
  215. bool ignore_allow_rdw, Error **errp)
  216. {
  217. /* Do not set read_only if copy_on_read is enabled */
  218. if (bs->copy_on_read && read_only) {
  219. error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
  220. bdrv_get_device_or_node_name(bs));
  221. return -EINVAL;
  222. }
  223. /* Do not clear read_only if it is prohibited */
  224. if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
  225. !ignore_allow_rdw)
  226. {
  227. error_setg(errp, "Node '%s' is read only",
  228. bdrv_get_device_or_node_name(bs));
  229. return -EPERM;
  230. }
  231. return 0;
  232. }
  233. /*
  234. * Called by a driver that can only provide a read-only image.
  235. *
  236. * Returns 0 if the node is already read-only or it could switch the node to
  237. * read-only because BDRV_O_AUTO_RDONLY is set.
  238. *
  239. * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
  240. * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
  241. * is not NULL, it is used as the error message for the Error object.
  242. */
  243. int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
  244. Error **errp)
  245. {
  246. int ret = 0;
  247. if (!(bs->open_flags & BDRV_O_RDWR)) {
  248. return 0;
  249. }
  250. if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
  251. goto fail;
  252. }
  253. ret = bdrv_can_set_read_only(bs, true, false, NULL);
  254. if (ret < 0) {
  255. goto fail;
  256. }
  257. bs->read_only = true;
  258. bs->open_flags &= ~BDRV_O_RDWR;
  259. return 0;
  260. fail:
  261. error_setg(errp, "%s", errmsg ?: "Image is read-only");
  262. return -EACCES;
  263. }
  264. /*
  265. * If @backing is empty, this function returns NULL without setting
  266. * @errp. In all other cases, NULL will only be returned with @errp
  267. * set.
  268. *
  269. * Therefore, a return value of NULL without @errp set means that
  270. * there is no backing file; if @errp is set, there is one but its
  271. * absolute filename cannot be generated.
  272. */
  273. char *bdrv_get_full_backing_filename_from_filename(const char *backed,
  274. const char *backing,
  275. Error **errp)
  276. {
  277. if (backing[0] == '\0') {
  278. return NULL;
  279. } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
  280. return g_strdup(backing);
  281. } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
  282. error_setg(errp, "Cannot use relative backing file names for '%s'",
  283. backed);
  284. return NULL;
  285. } else {
  286. return path_combine(backed, backing);
  287. }
  288. }
  289. /*
  290. * If @filename is empty or NULL, this function returns NULL without
  291. * setting @errp. In all other cases, NULL will only be returned with
  292. * @errp set.
  293. */
  294. static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
  295. const char *filename, Error **errp)
  296. {
  297. char *dir, *full_name;
  298. if (!filename || filename[0] == '\0') {
  299. return NULL;
  300. } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
  301. return g_strdup(filename);
  302. }
  303. dir = bdrv_dirname(relative_to, errp);
  304. if (!dir) {
  305. return NULL;
  306. }
  307. full_name = g_strconcat(dir, filename, NULL);
  308. g_free(dir);
  309. return full_name;
  310. }
  311. char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
  312. {
  313. return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
  314. }
  315. void bdrv_register(BlockDriver *bdrv)
  316. {
  317. QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
  318. }
  319. BlockDriverState *bdrv_new(void)
  320. {
  321. BlockDriverState *bs;
  322. int i;
  323. bs = g_new0(BlockDriverState, 1);
  324. QLIST_INIT(&bs->dirty_bitmaps);
  325. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  326. QLIST_INIT(&bs->op_blockers[i]);
  327. }
  328. notifier_with_return_list_init(&bs->before_write_notifiers);
  329. qemu_co_mutex_init(&bs->reqs_lock);
  330. qemu_mutex_init(&bs->dirty_bitmap_mutex);
  331. bs->refcnt = 1;
  332. bs->aio_context = qemu_get_aio_context();
  333. qemu_co_queue_init(&bs->flush_queue);
  334. for (i = 0; i < bdrv_drain_all_count; i++) {
  335. bdrv_drained_begin(bs);
  336. }
  337. QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
  338. return bs;
  339. }
  340. static BlockDriver *bdrv_do_find_format(const char *format_name)
  341. {
  342. BlockDriver *drv1;
  343. QLIST_FOREACH(drv1, &bdrv_drivers, list) {
  344. if (!strcmp(drv1->format_name, format_name)) {
  345. return drv1;
  346. }
  347. }
  348. return NULL;
  349. }
  350. BlockDriver *bdrv_find_format(const char *format_name)
  351. {
  352. BlockDriver *drv1;
  353. int i;
  354. drv1 = bdrv_do_find_format(format_name);
  355. if (drv1) {
  356. return drv1;
  357. }
  358. /* The driver isn't registered, maybe we need to load a module */
  359. for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
  360. if (!strcmp(block_driver_modules[i].format_name, format_name)) {
  361. block_module_load_one(block_driver_modules[i].library_name);
  362. break;
  363. }
  364. }
  365. return bdrv_do_find_format(format_name);
  366. }
  367. static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
  368. {
  369. static const char *whitelist_rw[] = {
  370. CONFIG_BDRV_RW_WHITELIST
  371. };
  372. static const char *whitelist_ro[] = {
  373. CONFIG_BDRV_RO_WHITELIST
  374. };
  375. const char **p;
  376. if (!whitelist_rw[0] && !whitelist_ro[0]) {
  377. return 1; /* no whitelist, anything goes */
  378. }
  379. for (p = whitelist_rw; *p; p++) {
  380. if (!strcmp(format_name, *p)) {
  381. return 1;
  382. }
  383. }
  384. if (read_only) {
  385. for (p = whitelist_ro; *p; p++) {
  386. if (!strcmp(format_name, *p)) {
  387. return 1;
  388. }
  389. }
  390. }
  391. return 0;
  392. }
  393. int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
  394. {
  395. return bdrv_format_is_whitelisted(drv->format_name, read_only);
  396. }
  397. bool bdrv_uses_whitelist(void)
  398. {
  399. return use_bdrv_whitelist;
  400. }
  401. typedef struct CreateCo {
  402. BlockDriver *drv;
  403. char *filename;
  404. QemuOpts *opts;
  405. int ret;
  406. Error *err;
  407. } CreateCo;
  408. static void coroutine_fn bdrv_create_co_entry(void *opaque)
  409. {
  410. Error *local_err = NULL;
  411. int ret;
  412. CreateCo *cco = opaque;
  413. assert(cco->drv);
  414. ret = cco->drv->bdrv_co_create_opts(cco->filename, cco->opts, &local_err);
  415. error_propagate(&cco->err, local_err);
  416. cco->ret = ret;
  417. }
  418. int bdrv_create(BlockDriver *drv, const char* filename,
  419. QemuOpts *opts, Error **errp)
  420. {
  421. int ret;
  422. Coroutine *co;
  423. CreateCo cco = {
  424. .drv = drv,
  425. .filename = g_strdup(filename),
  426. .opts = opts,
  427. .ret = NOT_DONE,
  428. .err = NULL,
  429. };
  430. if (!drv->bdrv_co_create_opts) {
  431. error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
  432. ret = -ENOTSUP;
  433. goto out;
  434. }
  435. if (qemu_in_coroutine()) {
  436. /* Fast-path if already in coroutine context */
  437. bdrv_create_co_entry(&cco);
  438. } else {
  439. co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
  440. qemu_coroutine_enter(co);
  441. while (cco.ret == NOT_DONE) {
  442. aio_poll(qemu_get_aio_context(), true);
  443. }
  444. }
  445. ret = cco.ret;
  446. if (ret < 0) {
  447. if (cco.err) {
  448. error_propagate(errp, cco.err);
  449. } else {
  450. error_setg_errno(errp, -ret, "Could not create image");
  451. }
  452. }
  453. out:
  454. g_free(cco.filename);
  455. return ret;
  456. }
  457. int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
  458. {
  459. BlockDriver *drv;
  460. Error *local_err = NULL;
  461. int ret;
  462. drv = bdrv_find_protocol(filename, true, errp);
  463. if (drv == NULL) {
  464. return -ENOENT;
  465. }
  466. ret = bdrv_create(drv, filename, opts, &local_err);
  467. error_propagate(errp, local_err);
  468. return ret;
  469. }
  470. /**
  471. * Try to get @bs's logical and physical block size.
  472. * On success, store them in @bsz struct and return 0.
  473. * On failure return -errno.
  474. * @bs must not be empty.
  475. */
  476. int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
  477. {
  478. BlockDriver *drv = bs->drv;
  479. if (drv && drv->bdrv_probe_blocksizes) {
  480. return drv->bdrv_probe_blocksizes(bs, bsz);
  481. } else if (drv && drv->is_filter && bs->file) {
  482. return bdrv_probe_blocksizes(bs->file->bs, bsz);
  483. }
  484. return -ENOTSUP;
  485. }
  486. /**
  487. * Try to get @bs's geometry (cyls, heads, sectors).
  488. * On success, store them in @geo struct and return 0.
  489. * On failure return -errno.
  490. * @bs must not be empty.
  491. */
  492. int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
  493. {
  494. BlockDriver *drv = bs->drv;
  495. if (drv && drv->bdrv_probe_geometry) {
  496. return drv->bdrv_probe_geometry(bs, geo);
  497. } else if (drv && drv->is_filter && bs->file) {
  498. return bdrv_probe_geometry(bs->file->bs, geo);
  499. }
  500. return -ENOTSUP;
  501. }
  502. /*
  503. * Create a uniquely-named empty temporary file.
  504. * Return 0 upon success, otherwise a negative errno value.
  505. */
  506. int get_tmp_filename(char *filename, int size)
  507. {
  508. #ifdef _WIN32
  509. char temp_dir[MAX_PATH];
  510. /* GetTempFileName requires that its output buffer (4th param)
  511. have length MAX_PATH or greater. */
  512. assert(size >= MAX_PATH);
  513. return (GetTempPath(MAX_PATH, temp_dir)
  514. && GetTempFileName(temp_dir, "qem", 0, filename)
  515. ? 0 : -GetLastError());
  516. #else
  517. int fd;
  518. const char *tmpdir;
  519. tmpdir = getenv("TMPDIR");
  520. if (!tmpdir) {
  521. tmpdir = "/var/tmp";
  522. }
  523. if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
  524. return -EOVERFLOW;
  525. }
  526. fd = mkstemp(filename);
  527. if (fd < 0) {
  528. return -errno;
  529. }
  530. if (close(fd) != 0) {
  531. unlink(filename);
  532. return -errno;
  533. }
  534. return 0;
  535. #endif
  536. }
  537. /*
  538. * Detect host devices. By convention, /dev/cdrom[N] is always
  539. * recognized as a host CDROM.
  540. */
  541. static BlockDriver *find_hdev_driver(const char *filename)
  542. {
  543. int score_max = 0, score;
  544. BlockDriver *drv = NULL, *d;
  545. QLIST_FOREACH(d, &bdrv_drivers, list) {
  546. if (d->bdrv_probe_device) {
  547. score = d->bdrv_probe_device(filename);
  548. if (score > score_max) {
  549. score_max = score;
  550. drv = d;
  551. }
  552. }
  553. }
  554. return drv;
  555. }
  556. static BlockDriver *bdrv_do_find_protocol(const char *protocol)
  557. {
  558. BlockDriver *drv1;
  559. QLIST_FOREACH(drv1, &bdrv_drivers, list) {
  560. if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
  561. return drv1;
  562. }
  563. }
  564. return NULL;
  565. }
  566. BlockDriver *bdrv_find_protocol(const char *filename,
  567. bool allow_protocol_prefix,
  568. Error **errp)
  569. {
  570. BlockDriver *drv1;
  571. char protocol[128];
  572. int len;
  573. const char *p;
  574. int i;
  575. /* TODO Drivers without bdrv_file_open must be specified explicitly */
  576. /*
  577. * XXX(hch): we really should not let host device detection
  578. * override an explicit protocol specification, but moving this
  579. * later breaks access to device names with colons in them.
  580. * Thanks to the brain-dead persistent naming schemes on udev-
  581. * based Linux systems those actually are quite common.
  582. */
  583. drv1 = find_hdev_driver(filename);
  584. if (drv1) {
  585. return drv1;
  586. }
  587. if (!path_has_protocol(filename) || !allow_protocol_prefix) {
  588. return &bdrv_file;
  589. }
  590. p = strchr(filename, ':');
  591. assert(p != NULL);
  592. len = p - filename;
  593. if (len > sizeof(protocol) - 1)
  594. len = sizeof(protocol) - 1;
  595. memcpy(protocol, filename, len);
  596. protocol[len] = '\0';
  597. drv1 = bdrv_do_find_protocol(protocol);
  598. if (drv1) {
  599. return drv1;
  600. }
  601. for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
  602. if (block_driver_modules[i].protocol_name &&
  603. !strcmp(block_driver_modules[i].protocol_name, protocol)) {
  604. block_module_load_one(block_driver_modules[i].library_name);
  605. break;
  606. }
  607. }
  608. drv1 = bdrv_do_find_protocol(protocol);
  609. if (!drv1) {
  610. error_setg(errp, "Unknown protocol '%s'", protocol);
  611. }
  612. return drv1;
  613. }
  614. /*
  615. * Guess image format by probing its contents.
  616. * This is not a good idea when your image is raw (CVE-2008-2004), but
  617. * we do it anyway for backward compatibility.
  618. *
  619. * @buf contains the image's first @buf_size bytes.
  620. * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
  621. * but can be smaller if the image file is smaller)
  622. * @filename is its filename.
  623. *
  624. * For all block drivers, call the bdrv_probe() method to get its
  625. * probing score.
  626. * Return the first block driver with the highest probing score.
  627. */
  628. BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
  629. const char *filename)
  630. {
  631. int score_max = 0, score;
  632. BlockDriver *drv = NULL, *d;
  633. QLIST_FOREACH(d, &bdrv_drivers, list) {
  634. if (d->bdrv_probe) {
  635. score = d->bdrv_probe(buf, buf_size, filename);
  636. if (score > score_max) {
  637. score_max = score;
  638. drv = d;
  639. }
  640. }
  641. }
  642. return drv;
  643. }
  644. static int find_image_format(BlockBackend *file, const char *filename,
  645. BlockDriver **pdrv, Error **errp)
  646. {
  647. BlockDriver *drv;
  648. uint8_t buf[BLOCK_PROBE_BUF_SIZE];
  649. int ret = 0;
  650. /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
  651. if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
  652. *pdrv = &bdrv_raw;
  653. return ret;
  654. }
  655. ret = blk_pread(file, 0, buf, sizeof(buf));
  656. if (ret < 0) {
  657. error_setg_errno(errp, -ret, "Could not read image for determining its "
  658. "format");
  659. *pdrv = NULL;
  660. return ret;
  661. }
  662. drv = bdrv_probe_all(buf, ret, filename);
  663. if (!drv) {
  664. error_setg(errp, "Could not determine image format: No compatible "
  665. "driver found");
  666. ret = -ENOENT;
  667. }
  668. *pdrv = drv;
  669. return ret;
  670. }
  671. /**
  672. * Set the current 'total_sectors' value
  673. * Return 0 on success, -errno on error.
  674. */
  675. int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
  676. {
  677. BlockDriver *drv = bs->drv;
  678. if (!drv) {
  679. return -ENOMEDIUM;
  680. }
  681. /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
  682. if (bdrv_is_sg(bs))
  683. return 0;
  684. /* query actual device if possible, otherwise just trust the hint */
  685. if (drv->bdrv_getlength) {
  686. int64_t length = drv->bdrv_getlength(bs);
  687. if (length < 0) {
  688. return length;
  689. }
  690. hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
  691. }
  692. bs->total_sectors = hint;
  693. return 0;
  694. }
  695. /**
  696. * Combines a QDict of new block driver @options with any missing options taken
  697. * from @old_options, so that leaving out an option defaults to its old value.
  698. */
  699. static void bdrv_join_options(BlockDriverState *bs, QDict *options,
  700. QDict *old_options)
  701. {
  702. if (bs->drv && bs->drv->bdrv_join_options) {
  703. bs->drv->bdrv_join_options(options, old_options);
  704. } else {
  705. qdict_join(options, old_options, false);
  706. }
  707. }
  708. static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
  709. int open_flags,
  710. Error **errp)
  711. {
  712. Error *local_err = NULL;
  713. char *value = qemu_opt_get_del(opts, "detect-zeroes");
  714. BlockdevDetectZeroesOptions detect_zeroes =
  715. qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
  716. BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
  717. g_free(value);
  718. if (local_err) {
  719. error_propagate(errp, local_err);
  720. return detect_zeroes;
  721. }
  722. if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
  723. !(open_flags & BDRV_O_UNMAP))
  724. {
  725. error_setg(errp, "setting detect-zeroes to unmap is not allowed "
  726. "without setting discard operation to unmap");
  727. }
  728. return detect_zeroes;
  729. }
  730. /**
  731. * Set open flags for a given discard mode
  732. *
  733. * Return 0 on success, -1 if the discard mode was invalid.
  734. */
  735. int bdrv_parse_discard_flags(const char *mode, int *flags)
  736. {
  737. *flags &= ~BDRV_O_UNMAP;
  738. if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
  739. /* do nothing */
  740. } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
  741. *flags |= BDRV_O_UNMAP;
  742. } else {
  743. return -1;
  744. }
  745. return 0;
  746. }
  747. /**
  748. * Set open flags for a given cache mode
  749. *
  750. * Return 0 on success, -1 if the cache mode was invalid.
  751. */
  752. int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
  753. {
  754. *flags &= ~BDRV_O_CACHE_MASK;
  755. if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
  756. *writethrough = false;
  757. *flags |= BDRV_O_NOCACHE;
  758. } else if (!strcmp(mode, "directsync")) {
  759. *writethrough = true;
  760. *flags |= BDRV_O_NOCACHE;
  761. } else if (!strcmp(mode, "writeback")) {
  762. *writethrough = false;
  763. } else if (!strcmp(mode, "unsafe")) {
  764. *writethrough = false;
  765. *flags |= BDRV_O_NO_FLUSH;
  766. } else if (!strcmp(mode, "writethrough")) {
  767. *writethrough = true;
  768. } else {
  769. return -1;
  770. }
  771. return 0;
  772. }
  773. static char *bdrv_child_get_parent_desc(BdrvChild *c)
  774. {
  775. BlockDriverState *parent = c->opaque;
  776. return g_strdup(bdrv_get_device_or_node_name(parent));
  777. }
  778. static void bdrv_child_cb_drained_begin(BdrvChild *child)
  779. {
  780. BlockDriverState *bs = child->opaque;
  781. bdrv_do_drained_begin_quiesce(bs, NULL, false);
  782. }
  783. static bool bdrv_child_cb_drained_poll(BdrvChild *child)
  784. {
  785. BlockDriverState *bs = child->opaque;
  786. return bdrv_drain_poll(bs, false, NULL, false);
  787. }
  788. static void bdrv_child_cb_drained_end(BdrvChild *child)
  789. {
  790. BlockDriverState *bs = child->opaque;
  791. bdrv_drained_end(bs);
  792. }
  793. static void bdrv_child_cb_attach(BdrvChild *child)
  794. {
  795. BlockDriverState *bs = child->opaque;
  796. bdrv_apply_subtree_drain(child, bs);
  797. }
  798. static void bdrv_child_cb_detach(BdrvChild *child)
  799. {
  800. BlockDriverState *bs = child->opaque;
  801. bdrv_unapply_subtree_drain(child, bs);
  802. }
  803. static int bdrv_child_cb_inactivate(BdrvChild *child)
  804. {
  805. BlockDriverState *bs = child->opaque;
  806. assert(bs->open_flags & BDRV_O_INACTIVE);
  807. return 0;
  808. }
  809. static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
  810. GSList **ignore, Error **errp)
  811. {
  812. BlockDriverState *bs = child->opaque;
  813. return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
  814. }
  815. static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
  816. GSList **ignore)
  817. {
  818. BlockDriverState *bs = child->opaque;
  819. return bdrv_set_aio_context_ignore(bs, ctx, ignore);
  820. }
  821. /*
  822. * Returns the options and flags that a temporary snapshot should get, based on
  823. * the originally requested flags (the originally requested image will have
  824. * flags like a backing file)
  825. */
  826. static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
  827. int parent_flags, QDict *parent_options)
  828. {
  829. *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
  830. /* For temporary files, unconditional cache=unsafe is fine */
  831. qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
  832. qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
  833. /* Copy the read-only and discard options from the parent */
  834. qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
  835. qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
  836. /* aio=native doesn't work for cache.direct=off, so disable it for the
  837. * temporary snapshot */
  838. *child_flags &= ~BDRV_O_NATIVE_AIO;
  839. }
  840. /*
  841. * Returns the options and flags that bs->file should get if a protocol driver
  842. * is expected, based on the given options and flags for the parent BDS
  843. */
  844. static void bdrv_inherited_options(int *child_flags, QDict *child_options,
  845. int parent_flags, QDict *parent_options)
  846. {
  847. int flags = parent_flags;
  848. /* Enable protocol handling, disable format probing for bs->file */
  849. flags |= BDRV_O_PROTOCOL;
  850. /* If the cache mode isn't explicitly set, inherit direct and no-flush from
  851. * the parent. */
  852. qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
  853. qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
  854. qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
  855. /* Inherit the read-only option from the parent if it's not set */
  856. qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
  857. qdict_copy_default(child_options, parent_options, BDRV_OPT_AUTO_READ_ONLY);
  858. /* Our block drivers take care to send flushes and respect unmap policy,
  859. * so we can default to enable both on lower layers regardless of the
  860. * corresponding parent options. */
  861. qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
  862. /* Clear flags that only apply to the top layer */
  863. flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
  864. BDRV_O_NO_IO);
  865. *child_flags = flags;
  866. }
  867. const BdrvChildRole child_file = {
  868. .parent_is_bds = true,
  869. .get_parent_desc = bdrv_child_get_parent_desc,
  870. .inherit_options = bdrv_inherited_options,
  871. .drained_begin = bdrv_child_cb_drained_begin,
  872. .drained_poll = bdrv_child_cb_drained_poll,
  873. .drained_end = bdrv_child_cb_drained_end,
  874. .attach = bdrv_child_cb_attach,
  875. .detach = bdrv_child_cb_detach,
  876. .inactivate = bdrv_child_cb_inactivate,
  877. .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
  878. .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
  879. };
  880. /*
  881. * Returns the options and flags that bs->file should get if the use of formats
  882. * (and not only protocols) is permitted for it, based on the given options and
  883. * flags for the parent BDS
  884. */
  885. static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
  886. int parent_flags, QDict *parent_options)
  887. {
  888. child_file.inherit_options(child_flags, child_options,
  889. parent_flags, parent_options);
  890. *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
  891. }
  892. const BdrvChildRole child_format = {
  893. .parent_is_bds = true,
  894. .get_parent_desc = bdrv_child_get_parent_desc,
  895. .inherit_options = bdrv_inherited_fmt_options,
  896. .drained_begin = bdrv_child_cb_drained_begin,
  897. .drained_poll = bdrv_child_cb_drained_poll,
  898. .drained_end = bdrv_child_cb_drained_end,
  899. .attach = bdrv_child_cb_attach,
  900. .detach = bdrv_child_cb_detach,
  901. .inactivate = bdrv_child_cb_inactivate,
  902. .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
  903. .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
  904. };
  905. static void bdrv_backing_attach(BdrvChild *c)
  906. {
  907. BlockDriverState *parent = c->opaque;
  908. BlockDriverState *backing_hd = c->bs;
  909. assert(!parent->backing_blocker);
  910. error_setg(&parent->backing_blocker,
  911. "node is used as backing hd of '%s'",
  912. bdrv_get_device_or_node_name(parent));
  913. bdrv_refresh_filename(backing_hd);
  914. parent->open_flags &= ~BDRV_O_NO_BACKING;
  915. pstrcpy(parent->backing_file, sizeof(parent->backing_file),
  916. backing_hd->filename);
  917. pstrcpy(parent->backing_format, sizeof(parent->backing_format),
  918. backing_hd->drv ? backing_hd->drv->format_name : "");
  919. bdrv_op_block_all(backing_hd, parent->backing_blocker);
  920. /* Otherwise we won't be able to commit or stream */
  921. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
  922. parent->backing_blocker);
  923. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
  924. parent->backing_blocker);
  925. /*
  926. * We do backup in 3 ways:
  927. * 1. drive backup
  928. * The target bs is new opened, and the source is top BDS
  929. * 2. blockdev backup
  930. * Both the source and the target are top BDSes.
  931. * 3. internal backup(used for block replication)
  932. * Both the source and the target are backing file
  933. *
  934. * In case 1 and 2, neither the source nor the target is the backing file.
  935. * In case 3, we will block the top BDS, so there is only one block job
  936. * for the top BDS and its backing chain.
  937. */
  938. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
  939. parent->backing_blocker);
  940. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
  941. parent->backing_blocker);
  942. bdrv_child_cb_attach(c);
  943. }
  944. static void bdrv_backing_detach(BdrvChild *c)
  945. {
  946. BlockDriverState *parent = c->opaque;
  947. assert(parent->backing_blocker);
  948. bdrv_op_unblock_all(c->bs, parent->backing_blocker);
  949. error_free(parent->backing_blocker);
  950. parent->backing_blocker = NULL;
  951. bdrv_child_cb_detach(c);
  952. }
  953. /*
  954. * Returns the options and flags that bs->backing should get, based on the
  955. * given options and flags for the parent BDS
  956. */
  957. static void bdrv_backing_options(int *child_flags, QDict *child_options,
  958. int parent_flags, QDict *parent_options)
  959. {
  960. int flags = parent_flags;
  961. /* The cache mode is inherited unmodified for backing files; except WCE,
  962. * which is only applied on the top level (BlockBackend) */
  963. qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
  964. qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
  965. qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
  966. /* backing files always opened read-only */
  967. qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
  968. qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
  969. flags &= ~BDRV_O_COPY_ON_READ;
  970. /* snapshot=on is handled on the top layer */
  971. flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
  972. *child_flags = flags;
  973. }
  974. static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
  975. const char *filename, Error **errp)
  976. {
  977. BlockDriverState *parent = c->opaque;
  978. bool read_only = bdrv_is_read_only(parent);
  979. int ret;
  980. if (read_only) {
  981. ret = bdrv_reopen_set_read_only(parent, false, errp);
  982. if (ret < 0) {
  983. return ret;
  984. }
  985. }
  986. ret = bdrv_change_backing_file(parent, filename,
  987. base->drv ? base->drv->format_name : "");
  988. if (ret < 0) {
  989. error_setg_errno(errp, -ret, "Could not update backing file link");
  990. }
  991. if (read_only) {
  992. bdrv_reopen_set_read_only(parent, true, NULL);
  993. }
  994. return ret;
  995. }
  996. const BdrvChildRole child_backing = {
  997. .parent_is_bds = true,
  998. .get_parent_desc = bdrv_child_get_parent_desc,
  999. .attach = bdrv_backing_attach,
  1000. .detach = bdrv_backing_detach,
  1001. .inherit_options = bdrv_backing_options,
  1002. .drained_begin = bdrv_child_cb_drained_begin,
  1003. .drained_poll = bdrv_child_cb_drained_poll,
  1004. .drained_end = bdrv_child_cb_drained_end,
  1005. .inactivate = bdrv_child_cb_inactivate,
  1006. .update_filename = bdrv_backing_update_filename,
  1007. .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
  1008. .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
  1009. };
  1010. static int bdrv_open_flags(BlockDriverState *bs, int flags)
  1011. {
  1012. int open_flags = flags;
  1013. /*
  1014. * Clear flags that are internal to the block layer before opening the
  1015. * image.
  1016. */
  1017. open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
  1018. return open_flags;
  1019. }
  1020. static void update_flags_from_options(int *flags, QemuOpts *opts)
  1021. {
  1022. *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
  1023. if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
  1024. *flags |= BDRV_O_NO_FLUSH;
  1025. }
  1026. if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
  1027. *flags |= BDRV_O_NOCACHE;
  1028. }
  1029. if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
  1030. *flags |= BDRV_O_RDWR;
  1031. }
  1032. if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
  1033. *flags |= BDRV_O_AUTO_RDONLY;
  1034. }
  1035. }
  1036. static void update_options_from_flags(QDict *options, int flags)
  1037. {
  1038. if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
  1039. qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
  1040. }
  1041. if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
  1042. qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
  1043. flags & BDRV_O_NO_FLUSH);
  1044. }
  1045. if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
  1046. qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
  1047. }
  1048. if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
  1049. qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
  1050. flags & BDRV_O_AUTO_RDONLY);
  1051. }
  1052. }
  1053. static void bdrv_assign_node_name(BlockDriverState *bs,
  1054. const char *node_name,
  1055. Error **errp)
  1056. {
  1057. char *gen_node_name = NULL;
  1058. if (!node_name) {
  1059. node_name = gen_node_name = id_generate(ID_BLOCK);
  1060. } else if (!id_wellformed(node_name)) {
  1061. /*
  1062. * Check for empty string or invalid characters, but not if it is
  1063. * generated (generated names use characters not available to the user)
  1064. */
  1065. error_setg(errp, "Invalid node name");
  1066. return;
  1067. }
  1068. /* takes care of avoiding namespaces collisions */
  1069. if (blk_by_name(node_name)) {
  1070. error_setg(errp, "node-name=%s is conflicting with a device id",
  1071. node_name);
  1072. goto out;
  1073. }
  1074. /* takes care of avoiding duplicates node names */
  1075. if (bdrv_find_node(node_name)) {
  1076. error_setg(errp, "Duplicate node name");
  1077. goto out;
  1078. }
  1079. /* Make sure that the node name isn't truncated */
  1080. if (strlen(node_name) >= sizeof(bs->node_name)) {
  1081. error_setg(errp, "Node name too long");
  1082. goto out;
  1083. }
  1084. /* copy node name into the bs and insert it into the graph list */
  1085. pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
  1086. QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
  1087. out:
  1088. g_free(gen_node_name);
  1089. }
  1090. static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
  1091. const char *node_name, QDict *options,
  1092. int open_flags, Error **errp)
  1093. {
  1094. Error *local_err = NULL;
  1095. int i, ret;
  1096. bdrv_assign_node_name(bs, node_name, &local_err);
  1097. if (local_err) {
  1098. error_propagate(errp, local_err);
  1099. return -EINVAL;
  1100. }
  1101. bs->drv = drv;
  1102. bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
  1103. bs->opaque = g_malloc0(drv->instance_size);
  1104. if (drv->bdrv_file_open) {
  1105. assert(!drv->bdrv_needs_filename || bs->filename[0]);
  1106. ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
  1107. } else if (drv->bdrv_open) {
  1108. ret = drv->bdrv_open(bs, options, open_flags, &local_err);
  1109. } else {
  1110. ret = 0;
  1111. }
  1112. if (ret < 0) {
  1113. if (local_err) {
  1114. error_propagate(errp, local_err);
  1115. } else if (bs->filename[0]) {
  1116. error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
  1117. } else {
  1118. error_setg_errno(errp, -ret, "Could not open image");
  1119. }
  1120. goto open_failed;
  1121. }
  1122. ret = refresh_total_sectors(bs, bs->total_sectors);
  1123. if (ret < 0) {
  1124. error_setg_errno(errp, -ret, "Could not refresh total sector count");
  1125. return ret;
  1126. }
  1127. bdrv_refresh_limits(bs, &local_err);
  1128. if (local_err) {
  1129. error_propagate(errp, local_err);
  1130. return -EINVAL;
  1131. }
  1132. assert(bdrv_opt_mem_align(bs) != 0);
  1133. assert(bdrv_min_mem_align(bs) != 0);
  1134. assert(is_power_of_2(bs->bl.request_alignment));
  1135. for (i = 0; i < bs->quiesce_counter; i++) {
  1136. if (drv->bdrv_co_drain_begin) {
  1137. drv->bdrv_co_drain_begin(bs);
  1138. }
  1139. }
  1140. return 0;
  1141. open_failed:
  1142. bs->drv = NULL;
  1143. if (bs->file != NULL) {
  1144. bdrv_unref_child(bs, bs->file);
  1145. bs->file = NULL;
  1146. }
  1147. g_free(bs->opaque);
  1148. bs->opaque = NULL;
  1149. return ret;
  1150. }
  1151. BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
  1152. int flags, Error **errp)
  1153. {
  1154. BlockDriverState *bs;
  1155. int ret;
  1156. bs = bdrv_new();
  1157. bs->open_flags = flags;
  1158. bs->explicit_options = qdict_new();
  1159. bs->options = qdict_new();
  1160. bs->opaque = NULL;
  1161. update_options_from_flags(bs->options, flags);
  1162. ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
  1163. if (ret < 0) {
  1164. qobject_unref(bs->explicit_options);
  1165. bs->explicit_options = NULL;
  1166. qobject_unref(bs->options);
  1167. bs->options = NULL;
  1168. bdrv_unref(bs);
  1169. return NULL;
  1170. }
  1171. return bs;
  1172. }
  1173. QemuOptsList bdrv_runtime_opts = {
  1174. .name = "bdrv_common",
  1175. .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
  1176. .desc = {
  1177. {
  1178. .name = "node-name",
  1179. .type = QEMU_OPT_STRING,
  1180. .help = "Node name of the block device node",
  1181. },
  1182. {
  1183. .name = "driver",
  1184. .type = QEMU_OPT_STRING,
  1185. .help = "Block driver to use for the node",
  1186. },
  1187. {
  1188. .name = BDRV_OPT_CACHE_DIRECT,
  1189. .type = QEMU_OPT_BOOL,
  1190. .help = "Bypass software writeback cache on the host",
  1191. },
  1192. {
  1193. .name = BDRV_OPT_CACHE_NO_FLUSH,
  1194. .type = QEMU_OPT_BOOL,
  1195. .help = "Ignore flush requests",
  1196. },
  1197. {
  1198. .name = BDRV_OPT_READ_ONLY,
  1199. .type = QEMU_OPT_BOOL,
  1200. .help = "Node is opened in read-only mode",
  1201. },
  1202. {
  1203. .name = BDRV_OPT_AUTO_READ_ONLY,
  1204. .type = QEMU_OPT_BOOL,
  1205. .help = "Node can become read-only if opening read-write fails",
  1206. },
  1207. {
  1208. .name = "detect-zeroes",
  1209. .type = QEMU_OPT_STRING,
  1210. .help = "try to optimize zero writes (off, on, unmap)",
  1211. },
  1212. {
  1213. .name = BDRV_OPT_DISCARD,
  1214. .type = QEMU_OPT_STRING,
  1215. .help = "discard operation (ignore/off, unmap/on)",
  1216. },
  1217. {
  1218. .name = BDRV_OPT_FORCE_SHARE,
  1219. .type = QEMU_OPT_BOOL,
  1220. .help = "always accept other writers (default: off)",
  1221. },
  1222. { /* end of list */ }
  1223. },
  1224. };
  1225. /*
  1226. * Common part for opening disk images and files
  1227. *
  1228. * Removes all processed options from *options.
  1229. */
  1230. static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
  1231. QDict *options, Error **errp)
  1232. {
  1233. int ret, open_flags;
  1234. const char *filename;
  1235. const char *driver_name = NULL;
  1236. const char *node_name = NULL;
  1237. const char *discard;
  1238. QemuOpts *opts;
  1239. BlockDriver *drv;
  1240. Error *local_err = NULL;
  1241. assert(bs->file == NULL);
  1242. assert(options != NULL && bs->options != options);
  1243. opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
  1244. qemu_opts_absorb_qdict(opts, options, &local_err);
  1245. if (local_err) {
  1246. error_propagate(errp, local_err);
  1247. ret = -EINVAL;
  1248. goto fail_opts;
  1249. }
  1250. update_flags_from_options(&bs->open_flags, opts);
  1251. driver_name = qemu_opt_get(opts, "driver");
  1252. drv = bdrv_find_format(driver_name);
  1253. assert(drv != NULL);
  1254. bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
  1255. if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
  1256. error_setg(errp,
  1257. BDRV_OPT_FORCE_SHARE
  1258. "=on can only be used with read-only images");
  1259. ret = -EINVAL;
  1260. goto fail_opts;
  1261. }
  1262. if (file != NULL) {
  1263. bdrv_refresh_filename(blk_bs(file));
  1264. filename = blk_bs(file)->filename;
  1265. } else {
  1266. /*
  1267. * Caution: while qdict_get_try_str() is fine, getting
  1268. * non-string types would require more care. When @options
  1269. * come from -blockdev or blockdev_add, its members are typed
  1270. * according to the QAPI schema, but when they come from
  1271. * -drive, they're all QString.
  1272. */
  1273. filename = qdict_get_try_str(options, "filename");
  1274. }
  1275. if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
  1276. error_setg(errp, "The '%s' block driver requires a file name",
  1277. drv->format_name);
  1278. ret = -EINVAL;
  1279. goto fail_opts;
  1280. }
  1281. trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
  1282. drv->format_name);
  1283. bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
  1284. if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
  1285. if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
  1286. ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
  1287. } else {
  1288. ret = -ENOTSUP;
  1289. }
  1290. if (ret < 0) {
  1291. error_setg(errp,
  1292. !bs->read_only && bdrv_is_whitelisted(drv, true)
  1293. ? "Driver '%s' can only be used for read-only devices"
  1294. : "Driver '%s' is not whitelisted",
  1295. drv->format_name);
  1296. goto fail_opts;
  1297. }
  1298. }
  1299. /* bdrv_new() and bdrv_close() make it so */
  1300. assert(atomic_read(&bs->copy_on_read) == 0);
  1301. if (bs->open_flags & BDRV_O_COPY_ON_READ) {
  1302. if (!bs->read_only) {
  1303. bdrv_enable_copy_on_read(bs);
  1304. } else {
  1305. error_setg(errp, "Can't use copy-on-read on read-only device");
  1306. ret = -EINVAL;
  1307. goto fail_opts;
  1308. }
  1309. }
  1310. discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
  1311. if (discard != NULL) {
  1312. if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
  1313. error_setg(errp, "Invalid discard option");
  1314. ret = -EINVAL;
  1315. goto fail_opts;
  1316. }
  1317. }
  1318. bs->detect_zeroes =
  1319. bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
  1320. if (local_err) {
  1321. error_propagate(errp, local_err);
  1322. ret = -EINVAL;
  1323. goto fail_opts;
  1324. }
  1325. if (filename != NULL) {
  1326. pstrcpy(bs->filename, sizeof(bs->filename), filename);
  1327. } else {
  1328. bs->filename[0] = '\0';
  1329. }
  1330. pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
  1331. /* Open the image, either directly or using a protocol */
  1332. open_flags = bdrv_open_flags(bs, bs->open_flags);
  1333. node_name = qemu_opt_get(opts, "node-name");
  1334. assert(!drv->bdrv_file_open || file == NULL);
  1335. ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
  1336. if (ret < 0) {
  1337. goto fail_opts;
  1338. }
  1339. qemu_opts_del(opts);
  1340. return 0;
  1341. fail_opts:
  1342. qemu_opts_del(opts);
  1343. return ret;
  1344. }
  1345. static QDict *parse_json_filename(const char *filename, Error **errp)
  1346. {
  1347. QObject *options_obj;
  1348. QDict *options;
  1349. int ret;
  1350. ret = strstart(filename, "json:", &filename);
  1351. assert(ret);
  1352. options_obj = qobject_from_json(filename, errp);
  1353. if (!options_obj) {
  1354. error_prepend(errp, "Could not parse the JSON options: ");
  1355. return NULL;
  1356. }
  1357. options = qobject_to(QDict, options_obj);
  1358. if (!options) {
  1359. qobject_unref(options_obj);
  1360. error_setg(errp, "Invalid JSON object given");
  1361. return NULL;
  1362. }
  1363. qdict_flatten(options);
  1364. return options;
  1365. }
  1366. static void parse_json_protocol(QDict *options, const char **pfilename,
  1367. Error **errp)
  1368. {
  1369. QDict *json_options;
  1370. Error *local_err = NULL;
  1371. /* Parse json: pseudo-protocol */
  1372. if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
  1373. return;
  1374. }
  1375. json_options = parse_json_filename(*pfilename, &local_err);
  1376. if (local_err) {
  1377. error_propagate(errp, local_err);
  1378. return;
  1379. }
  1380. /* Options given in the filename have lower priority than options
  1381. * specified directly */
  1382. qdict_join(options, json_options, false);
  1383. qobject_unref(json_options);
  1384. *pfilename = NULL;
  1385. }
  1386. /*
  1387. * Fills in default options for opening images and converts the legacy
  1388. * filename/flags pair to option QDict entries.
  1389. * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
  1390. * block driver has been specified explicitly.
  1391. */
  1392. static int bdrv_fill_options(QDict **options, const char *filename,
  1393. int *flags, Error **errp)
  1394. {
  1395. const char *drvname;
  1396. bool protocol = *flags & BDRV_O_PROTOCOL;
  1397. bool parse_filename = false;
  1398. BlockDriver *drv = NULL;
  1399. Error *local_err = NULL;
  1400. /*
  1401. * Caution: while qdict_get_try_str() is fine, getting non-string
  1402. * types would require more care. When @options come from
  1403. * -blockdev or blockdev_add, its members are typed according to
  1404. * the QAPI schema, but when they come from -drive, they're all
  1405. * QString.
  1406. */
  1407. drvname = qdict_get_try_str(*options, "driver");
  1408. if (drvname) {
  1409. drv = bdrv_find_format(drvname);
  1410. if (!drv) {
  1411. error_setg(errp, "Unknown driver '%s'", drvname);
  1412. return -ENOENT;
  1413. }
  1414. /* If the user has explicitly specified the driver, this choice should
  1415. * override the BDRV_O_PROTOCOL flag */
  1416. protocol = drv->bdrv_file_open;
  1417. }
  1418. if (protocol) {
  1419. *flags |= BDRV_O_PROTOCOL;
  1420. } else {
  1421. *flags &= ~BDRV_O_PROTOCOL;
  1422. }
  1423. /* Translate cache options from flags into options */
  1424. update_options_from_flags(*options, *flags);
  1425. /* Fetch the file name from the options QDict if necessary */
  1426. if (protocol && filename) {
  1427. if (!qdict_haskey(*options, "filename")) {
  1428. qdict_put_str(*options, "filename", filename);
  1429. parse_filename = true;
  1430. } else {
  1431. error_setg(errp, "Can't specify 'file' and 'filename' options at "
  1432. "the same time");
  1433. return -EINVAL;
  1434. }
  1435. }
  1436. /* Find the right block driver */
  1437. /* See cautionary note on accessing @options above */
  1438. filename = qdict_get_try_str(*options, "filename");
  1439. if (!drvname && protocol) {
  1440. if (filename) {
  1441. drv = bdrv_find_protocol(filename, parse_filename, errp);
  1442. if (!drv) {
  1443. return -EINVAL;
  1444. }
  1445. drvname = drv->format_name;
  1446. qdict_put_str(*options, "driver", drvname);
  1447. } else {
  1448. error_setg(errp, "Must specify either driver or file");
  1449. return -EINVAL;
  1450. }
  1451. }
  1452. assert(drv || !protocol);
  1453. /* Driver-specific filename parsing */
  1454. if (drv && drv->bdrv_parse_filename && parse_filename) {
  1455. drv->bdrv_parse_filename(filename, *options, &local_err);
  1456. if (local_err) {
  1457. error_propagate(errp, local_err);
  1458. return -EINVAL;
  1459. }
  1460. if (!drv->bdrv_needs_filename) {
  1461. qdict_del(*options, "filename");
  1462. }
  1463. }
  1464. return 0;
  1465. }
  1466. static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
  1467. uint64_t perm, uint64_t shared,
  1468. GSList *ignore_children, Error **errp);
  1469. static void bdrv_child_abort_perm_update(BdrvChild *c);
  1470. static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
  1471. static void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
  1472. uint64_t *shared_perm);
  1473. typedef struct BlockReopenQueueEntry {
  1474. bool prepared;
  1475. bool perms_checked;
  1476. BDRVReopenState state;
  1477. QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
  1478. } BlockReopenQueueEntry;
  1479. /*
  1480. * Return the flags that @bs will have after the reopens in @q have
  1481. * successfully completed. If @q is NULL (or @bs is not contained in @q),
  1482. * return the current flags.
  1483. */
  1484. static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
  1485. {
  1486. BlockReopenQueueEntry *entry;
  1487. if (q != NULL) {
  1488. QSIMPLEQ_FOREACH(entry, q, entry) {
  1489. if (entry->state.bs == bs) {
  1490. return entry->state.flags;
  1491. }
  1492. }
  1493. }
  1494. return bs->open_flags;
  1495. }
  1496. /* Returns whether the image file can be written to after the reopen queue @q
  1497. * has been successfully applied, or right now if @q is NULL. */
  1498. static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
  1499. BlockReopenQueue *q)
  1500. {
  1501. int flags = bdrv_reopen_get_flags(q, bs);
  1502. return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
  1503. }
  1504. /*
  1505. * Return whether the BDS can be written to. This is not necessarily
  1506. * the same as !bdrv_is_read_only(bs), as inactivated images may not
  1507. * be written to but do not count as read-only images.
  1508. */
  1509. bool bdrv_is_writable(BlockDriverState *bs)
  1510. {
  1511. return bdrv_is_writable_after_reopen(bs, NULL);
  1512. }
  1513. static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
  1514. BdrvChild *c, const BdrvChildRole *role,
  1515. BlockReopenQueue *reopen_queue,
  1516. uint64_t parent_perm, uint64_t parent_shared,
  1517. uint64_t *nperm, uint64_t *nshared)
  1518. {
  1519. assert(bs->drv && bs->drv->bdrv_child_perm);
  1520. bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
  1521. parent_perm, parent_shared,
  1522. nperm, nshared);
  1523. /* TODO Take force_share from reopen_queue */
  1524. if (child_bs && child_bs->force_share) {
  1525. *nshared = BLK_PERM_ALL;
  1526. }
  1527. }
  1528. /*
  1529. * Check whether permissions on this node can be changed in a way that
  1530. * @cumulative_perms and @cumulative_shared_perms are the new cumulative
  1531. * permissions of all its parents. This involves checking whether all necessary
  1532. * permission changes to child nodes can be performed.
  1533. *
  1534. * A call to this function must always be followed by a call to bdrv_set_perm()
  1535. * or bdrv_abort_perm_update().
  1536. */
  1537. static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
  1538. uint64_t cumulative_perms,
  1539. uint64_t cumulative_shared_perms,
  1540. GSList *ignore_children, Error **errp)
  1541. {
  1542. BlockDriver *drv = bs->drv;
  1543. BdrvChild *c;
  1544. int ret;
  1545. /* Write permissions never work with read-only images */
  1546. if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
  1547. !bdrv_is_writable_after_reopen(bs, q))
  1548. {
  1549. if (!bdrv_is_writable_after_reopen(bs, NULL)) {
  1550. error_setg(errp, "Block node is read-only");
  1551. } else {
  1552. uint64_t current_perms, current_shared;
  1553. bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
  1554. if (current_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
  1555. error_setg(errp, "Cannot make block node read-only, there is "
  1556. "a writer on it");
  1557. } else {
  1558. error_setg(errp, "Cannot make block node read-only and create "
  1559. "a writer on it");
  1560. }
  1561. }
  1562. return -EPERM;
  1563. }
  1564. /* Check this node */
  1565. if (!drv) {
  1566. return 0;
  1567. }
  1568. if (drv->bdrv_check_perm) {
  1569. return drv->bdrv_check_perm(bs, cumulative_perms,
  1570. cumulative_shared_perms, errp);
  1571. }
  1572. /* Drivers that never have children can omit .bdrv_child_perm() */
  1573. if (!drv->bdrv_child_perm) {
  1574. assert(QLIST_EMPTY(&bs->children));
  1575. return 0;
  1576. }
  1577. /* Check all children */
  1578. QLIST_FOREACH(c, &bs->children, next) {
  1579. uint64_t cur_perm, cur_shared;
  1580. bdrv_child_perm(bs, c->bs, c, c->role, q,
  1581. cumulative_perms, cumulative_shared_perms,
  1582. &cur_perm, &cur_shared);
  1583. ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared,
  1584. ignore_children, errp);
  1585. if (ret < 0) {
  1586. return ret;
  1587. }
  1588. }
  1589. return 0;
  1590. }
  1591. /*
  1592. * Notifies drivers that after a previous bdrv_check_perm() call, the
  1593. * permission update is not performed and any preparations made for it (e.g.
  1594. * taken file locks) need to be undone.
  1595. *
  1596. * This function recursively notifies all child nodes.
  1597. */
  1598. static void bdrv_abort_perm_update(BlockDriverState *bs)
  1599. {
  1600. BlockDriver *drv = bs->drv;
  1601. BdrvChild *c;
  1602. if (!drv) {
  1603. return;
  1604. }
  1605. if (drv->bdrv_abort_perm_update) {
  1606. drv->bdrv_abort_perm_update(bs);
  1607. }
  1608. QLIST_FOREACH(c, &bs->children, next) {
  1609. bdrv_child_abort_perm_update(c);
  1610. }
  1611. }
  1612. static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
  1613. uint64_t cumulative_shared_perms)
  1614. {
  1615. BlockDriver *drv = bs->drv;
  1616. BdrvChild *c;
  1617. if (!drv) {
  1618. return;
  1619. }
  1620. /* Update this node */
  1621. if (drv->bdrv_set_perm) {
  1622. drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
  1623. }
  1624. /* Drivers that never have children can omit .bdrv_child_perm() */
  1625. if (!drv->bdrv_child_perm) {
  1626. assert(QLIST_EMPTY(&bs->children));
  1627. return;
  1628. }
  1629. /* Update all children */
  1630. QLIST_FOREACH(c, &bs->children, next) {
  1631. uint64_t cur_perm, cur_shared;
  1632. bdrv_child_perm(bs, c->bs, c, c->role, NULL,
  1633. cumulative_perms, cumulative_shared_perms,
  1634. &cur_perm, &cur_shared);
  1635. bdrv_child_set_perm(c, cur_perm, cur_shared);
  1636. }
  1637. }
  1638. static void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
  1639. uint64_t *shared_perm)
  1640. {
  1641. BdrvChild *c;
  1642. uint64_t cumulative_perms = 0;
  1643. uint64_t cumulative_shared_perms = BLK_PERM_ALL;
  1644. QLIST_FOREACH(c, &bs->parents, next_parent) {
  1645. cumulative_perms |= c->perm;
  1646. cumulative_shared_perms &= c->shared_perm;
  1647. }
  1648. *perm = cumulative_perms;
  1649. *shared_perm = cumulative_shared_perms;
  1650. }
  1651. static char *bdrv_child_user_desc(BdrvChild *c)
  1652. {
  1653. if (c->role->get_parent_desc) {
  1654. return c->role->get_parent_desc(c);
  1655. }
  1656. return g_strdup("another user");
  1657. }
  1658. char *bdrv_perm_names(uint64_t perm)
  1659. {
  1660. struct perm_name {
  1661. uint64_t perm;
  1662. const char *name;
  1663. } permissions[] = {
  1664. { BLK_PERM_CONSISTENT_READ, "consistent read" },
  1665. { BLK_PERM_WRITE, "write" },
  1666. { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
  1667. { BLK_PERM_RESIZE, "resize" },
  1668. { BLK_PERM_GRAPH_MOD, "change children" },
  1669. { 0, NULL }
  1670. };
  1671. char *result = g_strdup("");
  1672. struct perm_name *p;
  1673. for (p = permissions; p->name; p++) {
  1674. if (perm & p->perm) {
  1675. char *old = result;
  1676. result = g_strdup_printf("%s%s%s", old, *old ? ", " : "", p->name);
  1677. g_free(old);
  1678. }
  1679. }
  1680. return result;
  1681. }
  1682. /*
  1683. * Checks whether a new reference to @bs can be added if the new user requires
  1684. * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
  1685. * set, the BdrvChild objects in this list are ignored in the calculations;
  1686. * this allows checking permission updates for an existing reference.
  1687. *
  1688. * Needs to be followed by a call to either bdrv_set_perm() or
  1689. * bdrv_abort_perm_update(). */
  1690. static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
  1691. uint64_t new_used_perm,
  1692. uint64_t new_shared_perm,
  1693. GSList *ignore_children, Error **errp)
  1694. {
  1695. BdrvChild *c;
  1696. uint64_t cumulative_perms = new_used_perm;
  1697. uint64_t cumulative_shared_perms = new_shared_perm;
  1698. /* There is no reason why anyone couldn't tolerate write_unchanged */
  1699. assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
  1700. QLIST_FOREACH(c, &bs->parents, next_parent) {
  1701. if (g_slist_find(ignore_children, c)) {
  1702. continue;
  1703. }
  1704. if ((new_used_perm & c->shared_perm) != new_used_perm) {
  1705. char *user = bdrv_child_user_desc(c);
  1706. char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
  1707. error_setg(errp, "Conflicts with use by %s as '%s', which does not "
  1708. "allow '%s' on %s",
  1709. user, c->name, perm_names, bdrv_get_node_name(c->bs));
  1710. g_free(user);
  1711. g_free(perm_names);
  1712. return -EPERM;
  1713. }
  1714. if ((c->perm & new_shared_perm) != c->perm) {
  1715. char *user = bdrv_child_user_desc(c);
  1716. char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
  1717. error_setg(errp, "Conflicts with use by %s as '%s', which uses "
  1718. "'%s' on %s",
  1719. user, c->name, perm_names, bdrv_get_node_name(c->bs));
  1720. g_free(user);
  1721. g_free(perm_names);
  1722. return -EPERM;
  1723. }
  1724. cumulative_perms |= c->perm;
  1725. cumulative_shared_perms &= c->shared_perm;
  1726. }
  1727. return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
  1728. ignore_children, errp);
  1729. }
  1730. /* Needs to be followed by a call to either bdrv_child_set_perm() or
  1731. * bdrv_child_abort_perm_update(). */
  1732. static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
  1733. uint64_t perm, uint64_t shared,
  1734. GSList *ignore_children, Error **errp)
  1735. {
  1736. int ret;
  1737. ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
  1738. ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children, errp);
  1739. g_slist_free(ignore_children);
  1740. if (ret < 0) {
  1741. return ret;
  1742. }
  1743. if (!c->has_backup_perm) {
  1744. c->has_backup_perm = true;
  1745. c->backup_perm = c->perm;
  1746. c->backup_shared_perm = c->shared_perm;
  1747. }
  1748. /*
  1749. * Note: it's OK if c->has_backup_perm was already set, as we can find the
  1750. * same child twice during check_perm procedure
  1751. */
  1752. c->perm = perm;
  1753. c->shared_perm = shared;
  1754. return 0;
  1755. }
  1756. static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
  1757. {
  1758. uint64_t cumulative_perms, cumulative_shared_perms;
  1759. c->has_backup_perm = false;
  1760. c->perm = perm;
  1761. c->shared_perm = shared;
  1762. bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
  1763. &cumulative_shared_perms);
  1764. bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
  1765. }
  1766. static void bdrv_child_abort_perm_update(BdrvChild *c)
  1767. {
  1768. if (c->has_backup_perm) {
  1769. c->perm = c->backup_perm;
  1770. c->shared_perm = c->backup_shared_perm;
  1771. c->has_backup_perm = false;
  1772. }
  1773. bdrv_abort_perm_update(c->bs);
  1774. }
  1775. int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
  1776. Error **errp)
  1777. {
  1778. int ret;
  1779. ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL, errp);
  1780. if (ret < 0) {
  1781. bdrv_child_abort_perm_update(c);
  1782. return ret;
  1783. }
  1784. bdrv_child_set_perm(c, perm, shared);
  1785. return 0;
  1786. }
  1787. void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
  1788. const BdrvChildRole *role,
  1789. BlockReopenQueue *reopen_queue,
  1790. uint64_t perm, uint64_t shared,
  1791. uint64_t *nperm, uint64_t *nshared)
  1792. {
  1793. if (c == NULL) {
  1794. *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
  1795. *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
  1796. return;
  1797. }
  1798. *nperm = (perm & DEFAULT_PERM_PASSTHROUGH) |
  1799. (c->perm & DEFAULT_PERM_UNCHANGED);
  1800. *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) |
  1801. (c->shared_perm & DEFAULT_PERM_UNCHANGED);
  1802. }
  1803. void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
  1804. const BdrvChildRole *role,
  1805. BlockReopenQueue *reopen_queue,
  1806. uint64_t perm, uint64_t shared,
  1807. uint64_t *nperm, uint64_t *nshared)
  1808. {
  1809. bool backing = (role == &child_backing);
  1810. assert(role == &child_backing || role == &child_file);
  1811. if (!backing) {
  1812. int flags = bdrv_reopen_get_flags(reopen_queue, bs);
  1813. /* Apart from the modifications below, the same permissions are
  1814. * forwarded and left alone as for filters */
  1815. bdrv_filter_default_perms(bs, c, role, reopen_queue, perm, shared,
  1816. &perm, &shared);
  1817. /* Format drivers may touch metadata even if the guest doesn't write */
  1818. if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
  1819. perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
  1820. }
  1821. /* bs->file always needs to be consistent because of the metadata. We
  1822. * can never allow other users to resize or write to it. */
  1823. if (!(flags & BDRV_O_NO_IO)) {
  1824. perm |= BLK_PERM_CONSISTENT_READ;
  1825. }
  1826. shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
  1827. } else {
  1828. /* We want consistent read from backing files if the parent needs it.
  1829. * No other operations are performed on backing files. */
  1830. perm &= BLK_PERM_CONSISTENT_READ;
  1831. /* If the parent can deal with changing data, we're okay with a
  1832. * writable and resizable backing file. */
  1833. /* TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too? */
  1834. if (shared & BLK_PERM_WRITE) {
  1835. shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
  1836. } else {
  1837. shared = 0;
  1838. }
  1839. shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
  1840. BLK_PERM_WRITE_UNCHANGED;
  1841. }
  1842. if (bs->open_flags & BDRV_O_INACTIVE) {
  1843. shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
  1844. }
  1845. *nperm = perm;
  1846. *nshared = shared;
  1847. }
  1848. static void bdrv_replace_child_noperm(BdrvChild *child,
  1849. BlockDriverState *new_bs)
  1850. {
  1851. BlockDriverState *old_bs = child->bs;
  1852. int i;
  1853. assert(!child->frozen);
  1854. if (old_bs && new_bs) {
  1855. assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
  1856. }
  1857. if (old_bs) {
  1858. /* Detach first so that the recursive drain sections coming from @child
  1859. * are already gone and we only end the drain sections that came from
  1860. * elsewhere. */
  1861. if (child->role->detach) {
  1862. child->role->detach(child);
  1863. }
  1864. if (old_bs->quiesce_counter && child->role->drained_end) {
  1865. int num = old_bs->quiesce_counter;
  1866. if (child->role->parent_is_bds) {
  1867. num -= bdrv_drain_all_count;
  1868. }
  1869. assert(num >= 0);
  1870. for (i = 0; i < num; i++) {
  1871. child->role->drained_end(child);
  1872. }
  1873. }
  1874. QLIST_REMOVE(child, next_parent);
  1875. }
  1876. child->bs = new_bs;
  1877. if (new_bs) {
  1878. QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
  1879. if (new_bs->quiesce_counter && child->role->drained_begin) {
  1880. int num = new_bs->quiesce_counter;
  1881. if (child->role->parent_is_bds) {
  1882. num -= bdrv_drain_all_count;
  1883. }
  1884. assert(num >= 0);
  1885. for (i = 0; i < num; i++) {
  1886. bdrv_parent_drained_begin_single(child, true);
  1887. }
  1888. }
  1889. /* Attach only after starting new drained sections, so that recursive
  1890. * drain sections coming from @child don't get an extra .drained_begin
  1891. * callback. */
  1892. if (child->role->attach) {
  1893. child->role->attach(child);
  1894. }
  1895. }
  1896. }
  1897. /*
  1898. * Updates @child to change its reference to point to @new_bs, including
  1899. * checking and applying the necessary permisson updates both to the old node
  1900. * and to @new_bs.
  1901. *
  1902. * NULL is passed as @new_bs for removing the reference before freeing @child.
  1903. *
  1904. * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
  1905. * function uses bdrv_set_perm() to update the permissions according to the new
  1906. * reference that @new_bs gets.
  1907. */
  1908. static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
  1909. {
  1910. BlockDriverState *old_bs = child->bs;
  1911. uint64_t perm, shared_perm;
  1912. bdrv_replace_child_noperm(child, new_bs);
  1913. if (old_bs) {
  1914. /* Update permissions for old node. This is guaranteed to succeed
  1915. * because we're just taking a parent away, so we're loosening
  1916. * restrictions. */
  1917. bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
  1918. bdrv_check_perm(old_bs, NULL, perm, shared_perm, NULL, &error_abort);
  1919. bdrv_set_perm(old_bs, perm, shared_perm);
  1920. /* When the parent requiring a non-default AioContext is removed, the
  1921. * node moves back to the main AioContext */
  1922. bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
  1923. }
  1924. if (new_bs) {
  1925. bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
  1926. bdrv_set_perm(new_bs, perm, shared_perm);
  1927. }
  1928. }
  1929. /*
  1930. * This function steals the reference to child_bs from the caller.
  1931. * That reference is later dropped by bdrv_root_unref_child().
  1932. *
  1933. * On failure NULL is returned, errp is set and the reference to
  1934. * child_bs is also dropped.
  1935. *
  1936. * The caller must hold the AioContext lock @child_bs, but not that of @ctx
  1937. * (unless @child_bs is already in @ctx).
  1938. */
  1939. BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
  1940. const char *child_name,
  1941. const BdrvChildRole *child_role,
  1942. AioContext *ctx,
  1943. uint64_t perm, uint64_t shared_perm,
  1944. void *opaque, Error **errp)
  1945. {
  1946. BdrvChild *child;
  1947. Error *local_err = NULL;
  1948. int ret;
  1949. ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, errp);
  1950. if (ret < 0) {
  1951. bdrv_abort_perm_update(child_bs);
  1952. bdrv_unref(child_bs);
  1953. return NULL;
  1954. }
  1955. child = g_new(BdrvChild, 1);
  1956. *child = (BdrvChild) {
  1957. .bs = NULL,
  1958. .name = g_strdup(child_name),
  1959. .role = child_role,
  1960. .perm = perm,
  1961. .shared_perm = shared_perm,
  1962. .opaque = opaque,
  1963. };
  1964. /* If the AioContexts don't match, first try to move the subtree of
  1965. * child_bs into the AioContext of the new parent. If this doesn't work,
  1966. * try moving the parent into the AioContext of child_bs instead. */
  1967. if (bdrv_get_aio_context(child_bs) != ctx) {
  1968. ret = bdrv_try_set_aio_context(child_bs, ctx, &local_err);
  1969. if (ret < 0 && child_role->can_set_aio_ctx) {
  1970. GSList *ignore = g_slist_prepend(NULL, child);;
  1971. ctx = bdrv_get_aio_context(child_bs);
  1972. if (child_role->can_set_aio_ctx(child, ctx, &ignore, NULL)) {
  1973. error_free(local_err);
  1974. ret = 0;
  1975. g_slist_free(ignore);
  1976. ignore = g_slist_prepend(NULL, child);;
  1977. child_role->set_aio_ctx(child, ctx, &ignore);
  1978. }
  1979. g_slist_free(ignore);
  1980. }
  1981. if (ret < 0) {
  1982. error_propagate(errp, local_err);
  1983. g_free(child);
  1984. bdrv_abort_perm_update(child_bs);
  1985. return NULL;
  1986. }
  1987. }
  1988. /* This performs the matching bdrv_set_perm() for the above check. */
  1989. bdrv_replace_child(child, child_bs);
  1990. return child;
  1991. }
  1992. /*
  1993. * This function transfers the reference to child_bs from the caller
  1994. * to parent_bs. That reference is later dropped by parent_bs on
  1995. * bdrv_close() or if someone calls bdrv_unref_child().
  1996. *
  1997. * On failure NULL is returned, errp is set and the reference to
  1998. * child_bs is also dropped.
  1999. *
  2000. * If @parent_bs and @child_bs are in different AioContexts, the caller must
  2001. * hold the AioContext lock for @child_bs, but not for @parent_bs.
  2002. */
  2003. BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
  2004. BlockDriverState *child_bs,
  2005. const char *child_name,
  2006. const BdrvChildRole *child_role,
  2007. Error **errp)
  2008. {
  2009. BdrvChild *child;
  2010. uint64_t perm, shared_perm;
  2011. bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
  2012. assert(parent_bs->drv);
  2013. bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
  2014. perm, shared_perm, &perm, &shared_perm);
  2015. child = bdrv_root_attach_child(child_bs, child_name, child_role,
  2016. bdrv_get_aio_context(parent_bs),
  2017. perm, shared_perm, parent_bs, errp);
  2018. if (child == NULL) {
  2019. return NULL;
  2020. }
  2021. QLIST_INSERT_HEAD(&parent_bs->children, child, next);
  2022. return child;
  2023. }
  2024. static void bdrv_detach_child(BdrvChild *child)
  2025. {
  2026. if (child->next.le_prev) {
  2027. QLIST_REMOVE(child, next);
  2028. child->next.le_prev = NULL;
  2029. }
  2030. bdrv_replace_child(child, NULL);
  2031. g_free(child->name);
  2032. g_free(child);
  2033. }
  2034. void bdrv_root_unref_child(BdrvChild *child)
  2035. {
  2036. BlockDriverState *child_bs;
  2037. child_bs = child->bs;
  2038. bdrv_detach_child(child);
  2039. bdrv_unref(child_bs);
  2040. }
  2041. void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
  2042. {
  2043. if (child == NULL) {
  2044. return;
  2045. }
  2046. if (child->bs->inherits_from == parent) {
  2047. BdrvChild *c;
  2048. /* Remove inherits_from only when the last reference between parent and
  2049. * child->bs goes away. */
  2050. QLIST_FOREACH(c, &parent->children, next) {
  2051. if (c != child && c->bs == child->bs) {
  2052. break;
  2053. }
  2054. }
  2055. if (c == NULL) {
  2056. child->bs->inherits_from = NULL;
  2057. }
  2058. }
  2059. bdrv_root_unref_child(child);
  2060. }
  2061. static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
  2062. {
  2063. BdrvChild *c;
  2064. QLIST_FOREACH(c, &bs->parents, next_parent) {
  2065. if (c->role->change_media) {
  2066. c->role->change_media(c, load);
  2067. }
  2068. }
  2069. }
  2070. /* Return true if you can reach parent going through child->inherits_from
  2071. * recursively. If parent or child are NULL, return false */
  2072. static bool bdrv_inherits_from_recursive(BlockDriverState *child,
  2073. BlockDriverState *parent)
  2074. {
  2075. while (child && child != parent) {
  2076. child = child->inherits_from;
  2077. }
  2078. return child != NULL;
  2079. }
  2080. /*
  2081. * Sets the backing file link of a BDS. A new reference is created; callers
  2082. * which don't need their own reference any more must call bdrv_unref().
  2083. */
  2084. void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
  2085. Error **errp)
  2086. {
  2087. bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
  2088. bdrv_inherits_from_recursive(backing_hd, bs);
  2089. if (bdrv_is_backing_chain_frozen(bs, backing_bs(bs), errp)) {
  2090. return;
  2091. }
  2092. if (backing_hd) {
  2093. bdrv_ref(backing_hd);
  2094. }
  2095. if (bs->backing) {
  2096. bdrv_unref_child(bs, bs->backing);
  2097. }
  2098. if (!backing_hd) {
  2099. bs->backing = NULL;
  2100. goto out;
  2101. }
  2102. bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing,
  2103. errp);
  2104. /* If backing_hd was already part of bs's backing chain, and
  2105. * inherits_from pointed recursively to bs then let's update it to
  2106. * point directly to bs (else it will become NULL). */
  2107. if (bs->backing && update_inherits_from) {
  2108. backing_hd->inherits_from = bs;
  2109. }
  2110. out:
  2111. bdrv_refresh_limits(bs, NULL);
  2112. }
  2113. /*
  2114. * Opens the backing file for a BlockDriverState if not yet open
  2115. *
  2116. * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
  2117. * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
  2118. * itself, all options starting with "${bdref_key}." are considered part of the
  2119. * BlockdevRef.
  2120. *
  2121. * TODO Can this be unified with bdrv_open_image()?
  2122. */
  2123. int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
  2124. const char *bdref_key, Error **errp)
  2125. {
  2126. char *backing_filename = NULL;
  2127. char *bdref_key_dot;
  2128. const char *reference = NULL;
  2129. int ret = 0;
  2130. bool implicit_backing = false;
  2131. BlockDriverState *backing_hd;
  2132. QDict *options;
  2133. QDict *tmp_parent_options = NULL;
  2134. Error *local_err = NULL;
  2135. if (bs->backing != NULL) {
  2136. goto free_exit;
  2137. }
  2138. /* NULL means an empty set of options */
  2139. if (parent_options == NULL) {
  2140. tmp_parent_options = qdict_new();
  2141. parent_options = tmp_parent_options;
  2142. }
  2143. bs->open_flags &= ~BDRV_O_NO_BACKING;
  2144. bdref_key_dot = g_strdup_printf("%s.", bdref_key);
  2145. qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
  2146. g_free(bdref_key_dot);
  2147. /*
  2148. * Caution: while qdict_get_try_str() is fine, getting non-string
  2149. * types would require more care. When @parent_options come from
  2150. * -blockdev or blockdev_add, its members are typed according to
  2151. * the QAPI schema, but when they come from -drive, they're all
  2152. * QString.
  2153. */
  2154. reference = qdict_get_try_str(parent_options, bdref_key);
  2155. if (reference || qdict_haskey(options, "file.filename")) {
  2156. /* keep backing_filename NULL */
  2157. } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
  2158. qobject_unref(options);
  2159. goto free_exit;
  2160. } else {
  2161. if (qdict_size(options) == 0) {
  2162. /* If the user specifies options that do not modify the
  2163. * backing file's behavior, we might still consider it the
  2164. * implicit backing file. But it's easier this way, and
  2165. * just specifying some of the backing BDS's options is
  2166. * only possible with -drive anyway (otherwise the QAPI
  2167. * schema forces the user to specify everything). */
  2168. implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
  2169. }
  2170. backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
  2171. if (local_err) {
  2172. ret = -EINVAL;
  2173. error_propagate(errp, local_err);
  2174. qobject_unref(options);
  2175. goto free_exit;
  2176. }
  2177. }
  2178. if (!bs->drv || !bs->drv->supports_backing) {
  2179. ret = -EINVAL;
  2180. error_setg(errp, "Driver doesn't support backing files");
  2181. qobject_unref(options);
  2182. goto free_exit;
  2183. }
  2184. if (!reference &&
  2185. bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
  2186. qdict_put_str(options, "driver", bs->backing_format);
  2187. }
  2188. backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
  2189. &child_backing, errp);
  2190. if (!backing_hd) {
  2191. bs->open_flags |= BDRV_O_NO_BACKING;
  2192. error_prepend(errp, "Could not open backing file: ");
  2193. ret = -EINVAL;
  2194. goto free_exit;
  2195. }
  2196. if (implicit_backing) {
  2197. bdrv_refresh_filename(backing_hd);
  2198. pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
  2199. backing_hd->filename);
  2200. }
  2201. /* Hook up the backing file link; drop our reference, bs owns the
  2202. * backing_hd reference now */
  2203. bdrv_set_backing_hd(bs, backing_hd, &local_err);
  2204. bdrv_unref(backing_hd);
  2205. if (local_err) {
  2206. error_propagate(errp, local_err);
  2207. ret = -EINVAL;
  2208. goto free_exit;
  2209. }
  2210. qdict_del(parent_options, bdref_key);
  2211. free_exit:
  2212. g_free(backing_filename);
  2213. qobject_unref(tmp_parent_options);
  2214. return ret;
  2215. }
  2216. static BlockDriverState *
  2217. bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
  2218. BlockDriverState *parent, const BdrvChildRole *child_role,
  2219. bool allow_none, Error **errp)
  2220. {
  2221. BlockDriverState *bs = NULL;
  2222. QDict *image_options;
  2223. char *bdref_key_dot;
  2224. const char *reference;
  2225. assert(child_role != NULL);
  2226. bdref_key_dot = g_strdup_printf("%s.", bdref_key);
  2227. qdict_extract_subqdict(options, &image_options, bdref_key_dot);
  2228. g_free(bdref_key_dot);
  2229. /*
  2230. * Caution: while qdict_get_try_str() is fine, getting non-string
  2231. * types would require more care. When @options come from
  2232. * -blockdev or blockdev_add, its members are typed according to
  2233. * the QAPI schema, but when they come from -drive, they're all
  2234. * QString.
  2235. */
  2236. reference = qdict_get_try_str(options, bdref_key);
  2237. if (!filename && !reference && !qdict_size(image_options)) {
  2238. if (!allow_none) {
  2239. error_setg(errp, "A block device must be specified for \"%s\"",
  2240. bdref_key);
  2241. }
  2242. qobject_unref(image_options);
  2243. goto done;
  2244. }
  2245. bs = bdrv_open_inherit(filename, reference, image_options, 0,
  2246. parent, child_role, errp);
  2247. if (!bs) {
  2248. goto done;
  2249. }
  2250. done:
  2251. qdict_del(options, bdref_key);
  2252. return bs;
  2253. }
  2254. /*
  2255. * Opens a disk image whose options are given as BlockdevRef in another block
  2256. * device's options.
  2257. *
  2258. * If allow_none is true, no image will be opened if filename is false and no
  2259. * BlockdevRef is given. NULL will be returned, but errp remains unset.
  2260. *
  2261. * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
  2262. * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
  2263. * itself, all options starting with "${bdref_key}." are considered part of the
  2264. * BlockdevRef.
  2265. *
  2266. * The BlockdevRef will be removed from the options QDict.
  2267. */
  2268. BdrvChild *bdrv_open_child(const char *filename,
  2269. QDict *options, const char *bdref_key,
  2270. BlockDriverState *parent,
  2271. const BdrvChildRole *child_role,
  2272. bool allow_none, Error **errp)
  2273. {
  2274. BlockDriverState *bs;
  2275. bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_role,
  2276. allow_none, errp);
  2277. if (bs == NULL) {
  2278. return NULL;
  2279. }
  2280. return bdrv_attach_child(parent, bs, bdref_key, child_role, errp);
  2281. }
  2282. /* TODO Future callers may need to specify parent/child_role in order for
  2283. * option inheritance to work. Existing callers use it for the root node. */
  2284. BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
  2285. {
  2286. BlockDriverState *bs = NULL;
  2287. Error *local_err = NULL;
  2288. QObject *obj = NULL;
  2289. QDict *qdict = NULL;
  2290. const char *reference = NULL;
  2291. Visitor *v = NULL;
  2292. if (ref->type == QTYPE_QSTRING) {
  2293. reference = ref->u.reference;
  2294. } else {
  2295. BlockdevOptions *options = &ref->u.definition;
  2296. assert(ref->type == QTYPE_QDICT);
  2297. v = qobject_output_visitor_new(&obj);
  2298. visit_type_BlockdevOptions(v, NULL, &options, &local_err);
  2299. if (local_err) {
  2300. error_propagate(errp, local_err);
  2301. goto fail;
  2302. }
  2303. visit_complete(v, &obj);
  2304. qdict = qobject_to(QDict, obj);
  2305. qdict_flatten(qdict);
  2306. /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
  2307. * compatibility with other callers) rather than what we want as the
  2308. * real defaults. Apply the defaults here instead. */
  2309. qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
  2310. qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
  2311. qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
  2312. qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
  2313. }
  2314. bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, errp);
  2315. obj = NULL;
  2316. fail:
  2317. qobject_unref(obj);
  2318. visit_free(v);
  2319. return bs;
  2320. }
  2321. static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
  2322. int flags,
  2323. QDict *snapshot_options,
  2324. Error **errp)
  2325. {
  2326. /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
  2327. char *tmp_filename = g_malloc0(PATH_MAX + 1);
  2328. int64_t total_size;
  2329. QemuOpts *opts = NULL;
  2330. BlockDriverState *bs_snapshot = NULL;
  2331. Error *local_err = NULL;
  2332. int ret;
  2333. /* if snapshot, we create a temporary backing file and open it
  2334. instead of opening 'filename' directly */
  2335. /* Get the required size from the image */
  2336. total_size = bdrv_getlength(bs);
  2337. if (total_size < 0) {
  2338. error_setg_errno(errp, -total_size, "Could not get image size");
  2339. goto out;
  2340. }
  2341. /* Create the temporary image */
  2342. ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
  2343. if (ret < 0) {
  2344. error_setg_errno(errp, -ret, "Could not get temporary filename");
  2345. goto out;
  2346. }
  2347. opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
  2348. &error_abort);
  2349. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
  2350. ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
  2351. qemu_opts_del(opts);
  2352. if (ret < 0) {
  2353. error_prepend(errp, "Could not create temporary overlay '%s': ",
  2354. tmp_filename);
  2355. goto out;
  2356. }
  2357. /* Prepare options QDict for the temporary file */
  2358. qdict_put_str(snapshot_options, "file.driver", "file");
  2359. qdict_put_str(snapshot_options, "file.filename", tmp_filename);
  2360. qdict_put_str(snapshot_options, "driver", "qcow2");
  2361. bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
  2362. snapshot_options = NULL;
  2363. if (!bs_snapshot) {
  2364. goto out;
  2365. }
  2366. /* bdrv_append() consumes a strong reference to bs_snapshot
  2367. * (i.e. it will call bdrv_unref() on it) even on error, so in
  2368. * order to be able to return one, we have to increase
  2369. * bs_snapshot's refcount here */
  2370. bdrv_ref(bs_snapshot);
  2371. bdrv_append(bs_snapshot, bs, &local_err);
  2372. if (local_err) {
  2373. error_propagate(errp, local_err);
  2374. bs_snapshot = NULL;
  2375. goto out;
  2376. }
  2377. out:
  2378. qobject_unref(snapshot_options);
  2379. g_free(tmp_filename);
  2380. return bs_snapshot;
  2381. }
  2382. /*
  2383. * Opens a disk image (raw, qcow2, vmdk, ...)
  2384. *
  2385. * options is a QDict of options to pass to the block drivers, or NULL for an
  2386. * empty set of options. The reference to the QDict belongs to the block layer
  2387. * after the call (even on failure), so if the caller intends to reuse the
  2388. * dictionary, it needs to use qobject_ref() before calling bdrv_open.
  2389. *
  2390. * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
  2391. * If it is not NULL, the referenced BDS will be reused.
  2392. *
  2393. * The reference parameter may be used to specify an existing block device which
  2394. * should be opened. If specified, neither options nor a filename may be given,
  2395. * nor can an existing BDS be reused (that is, *pbs has to be NULL).
  2396. */
  2397. static BlockDriverState *bdrv_open_inherit(const char *filename,
  2398. const char *reference,
  2399. QDict *options, int flags,
  2400. BlockDriverState *parent,
  2401. const BdrvChildRole *child_role,
  2402. Error **errp)
  2403. {
  2404. int ret;
  2405. BlockBackend *file = NULL;
  2406. BlockDriverState *bs;
  2407. BlockDriver *drv = NULL;
  2408. BdrvChild *child;
  2409. const char *drvname;
  2410. const char *backing;
  2411. Error *local_err = NULL;
  2412. QDict *snapshot_options = NULL;
  2413. int snapshot_flags = 0;
  2414. assert(!child_role || !flags);
  2415. assert(!child_role == !parent);
  2416. if (reference) {
  2417. bool options_non_empty = options ? qdict_size(options) : false;
  2418. qobject_unref(options);
  2419. if (filename || options_non_empty) {
  2420. error_setg(errp, "Cannot reference an existing block device with "
  2421. "additional options or a new filename");
  2422. return NULL;
  2423. }
  2424. bs = bdrv_lookup_bs(reference, reference, errp);
  2425. if (!bs) {
  2426. return NULL;
  2427. }
  2428. bdrv_ref(bs);
  2429. return bs;
  2430. }
  2431. bs = bdrv_new();
  2432. /* NULL means an empty set of options */
  2433. if (options == NULL) {
  2434. options = qdict_new();
  2435. }
  2436. /* json: syntax counts as explicit options, as if in the QDict */
  2437. parse_json_protocol(options, &filename, &local_err);
  2438. if (local_err) {
  2439. goto fail;
  2440. }
  2441. bs->explicit_options = qdict_clone_shallow(options);
  2442. if (child_role) {
  2443. bs->inherits_from = parent;
  2444. child_role->inherit_options(&flags, options,
  2445. parent->open_flags, parent->options);
  2446. }
  2447. ret = bdrv_fill_options(&options, filename, &flags, &local_err);
  2448. if (local_err) {
  2449. goto fail;
  2450. }
  2451. /*
  2452. * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
  2453. * Caution: getting a boolean member of @options requires care.
  2454. * When @options come from -blockdev or blockdev_add, members are
  2455. * typed according to the QAPI schema, but when they come from
  2456. * -drive, they're all QString.
  2457. */
  2458. if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
  2459. !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
  2460. flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
  2461. } else {
  2462. flags &= ~BDRV_O_RDWR;
  2463. }
  2464. if (flags & BDRV_O_SNAPSHOT) {
  2465. snapshot_options = qdict_new();
  2466. bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
  2467. flags, options);
  2468. /* Let bdrv_backing_options() override "read-only" */
  2469. qdict_del(options, BDRV_OPT_READ_ONLY);
  2470. bdrv_backing_options(&flags, options, flags, options);
  2471. }
  2472. bs->open_flags = flags;
  2473. bs->options = options;
  2474. options = qdict_clone_shallow(options);
  2475. /* Find the right image format driver */
  2476. /* See cautionary note on accessing @options above */
  2477. drvname = qdict_get_try_str(options, "driver");
  2478. if (drvname) {
  2479. drv = bdrv_find_format(drvname);
  2480. if (!drv) {
  2481. error_setg(errp, "Unknown driver: '%s'", drvname);
  2482. goto fail;
  2483. }
  2484. }
  2485. assert(drvname || !(flags & BDRV_O_PROTOCOL));
  2486. /* See cautionary note on accessing @options above */
  2487. backing = qdict_get_try_str(options, "backing");
  2488. if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
  2489. (backing && *backing == '\0'))
  2490. {
  2491. if (backing) {
  2492. warn_report("Use of \"backing\": \"\" is deprecated; "
  2493. "use \"backing\": null instead");
  2494. }
  2495. flags |= BDRV_O_NO_BACKING;
  2496. qdict_del(options, "backing");
  2497. }
  2498. /* Open image file without format layer. This BlockBackend is only used for
  2499. * probing, the block drivers will do their own bdrv_open_child() for the
  2500. * same BDS, which is why we put the node name back into options. */
  2501. if ((flags & BDRV_O_PROTOCOL) == 0) {
  2502. BlockDriverState *file_bs;
  2503. file_bs = bdrv_open_child_bs(filename, options, "file", bs,
  2504. &child_file, true, &local_err);
  2505. if (local_err) {
  2506. goto fail;
  2507. }
  2508. if (file_bs != NULL) {
  2509. /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
  2510. * looking at the header to guess the image format. This works even
  2511. * in cases where a guest would not see a consistent state. */
  2512. file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
  2513. blk_insert_bs(file, file_bs, &local_err);
  2514. bdrv_unref(file_bs);
  2515. if (local_err) {
  2516. goto fail;
  2517. }
  2518. qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
  2519. }
  2520. }
  2521. /* Image format probing */
  2522. bs->probed = !drv;
  2523. if (!drv && file) {
  2524. ret = find_image_format(file, filename, &drv, &local_err);
  2525. if (ret < 0) {
  2526. goto fail;
  2527. }
  2528. /*
  2529. * This option update would logically belong in bdrv_fill_options(),
  2530. * but we first need to open bs->file for the probing to work, while
  2531. * opening bs->file already requires the (mostly) final set of options
  2532. * so that cache mode etc. can be inherited.
  2533. *
  2534. * Adding the driver later is somewhat ugly, but it's not an option
  2535. * that would ever be inherited, so it's correct. We just need to make
  2536. * sure to update both bs->options (which has the full effective
  2537. * options for bs) and options (which has file.* already removed).
  2538. */
  2539. qdict_put_str(bs->options, "driver", drv->format_name);
  2540. qdict_put_str(options, "driver", drv->format_name);
  2541. } else if (!drv) {
  2542. error_setg(errp, "Must specify either driver or file");
  2543. goto fail;
  2544. }
  2545. /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
  2546. assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
  2547. /* file must be NULL if a protocol BDS is about to be created
  2548. * (the inverse results in an error message from bdrv_open_common()) */
  2549. assert(!(flags & BDRV_O_PROTOCOL) || !file);
  2550. /* Open the image */
  2551. ret = bdrv_open_common(bs, file, options, &local_err);
  2552. if (ret < 0) {
  2553. goto fail;
  2554. }
  2555. if (file) {
  2556. blk_unref(file);
  2557. file = NULL;
  2558. }
  2559. /* If there is a backing file, use it */
  2560. if ((flags & BDRV_O_NO_BACKING) == 0) {
  2561. ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
  2562. if (ret < 0) {
  2563. goto close_and_fail;
  2564. }
  2565. }
  2566. /* Remove all children options and references
  2567. * from bs->options and bs->explicit_options */
  2568. QLIST_FOREACH(child, &bs->children, next) {
  2569. char *child_key_dot;
  2570. child_key_dot = g_strdup_printf("%s.", child->name);
  2571. qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
  2572. qdict_extract_subqdict(bs->options, NULL, child_key_dot);
  2573. qdict_del(bs->explicit_options, child->name);
  2574. qdict_del(bs->options, child->name);
  2575. g_free(child_key_dot);
  2576. }
  2577. /* Check if any unknown options were used */
  2578. if (qdict_size(options) != 0) {
  2579. const QDictEntry *entry = qdict_first(options);
  2580. if (flags & BDRV_O_PROTOCOL) {
  2581. error_setg(errp, "Block protocol '%s' doesn't support the option "
  2582. "'%s'", drv->format_name, entry->key);
  2583. } else {
  2584. error_setg(errp,
  2585. "Block format '%s' does not support the option '%s'",
  2586. drv->format_name, entry->key);
  2587. }
  2588. goto close_and_fail;
  2589. }
  2590. bdrv_parent_cb_change_media(bs, true);
  2591. qobject_unref(options);
  2592. options = NULL;
  2593. /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
  2594. * temporary snapshot afterwards. */
  2595. if (snapshot_flags) {
  2596. BlockDriverState *snapshot_bs;
  2597. snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
  2598. snapshot_options, &local_err);
  2599. snapshot_options = NULL;
  2600. if (local_err) {
  2601. goto close_and_fail;
  2602. }
  2603. /* We are not going to return bs but the overlay on top of it
  2604. * (snapshot_bs); thus, we have to drop the strong reference to bs
  2605. * (which we obtained by calling bdrv_new()). bs will not be deleted,
  2606. * though, because the overlay still has a reference to it. */
  2607. bdrv_unref(bs);
  2608. bs = snapshot_bs;
  2609. }
  2610. return bs;
  2611. fail:
  2612. blk_unref(file);
  2613. qobject_unref(snapshot_options);
  2614. qobject_unref(bs->explicit_options);
  2615. qobject_unref(bs->options);
  2616. qobject_unref(options);
  2617. bs->options = NULL;
  2618. bs->explicit_options = NULL;
  2619. bdrv_unref(bs);
  2620. error_propagate(errp, local_err);
  2621. return NULL;
  2622. close_and_fail:
  2623. bdrv_unref(bs);
  2624. qobject_unref(snapshot_options);
  2625. qobject_unref(options);
  2626. error_propagate(errp, local_err);
  2627. return NULL;
  2628. }
  2629. BlockDriverState *bdrv_open(const char *filename, const char *reference,
  2630. QDict *options, int flags, Error **errp)
  2631. {
  2632. return bdrv_open_inherit(filename, reference, options, flags, NULL,
  2633. NULL, errp);
  2634. }
  2635. /* Return true if the NULL-terminated @list contains @str */
  2636. static bool is_str_in_list(const char *str, const char *const *list)
  2637. {
  2638. if (str && list) {
  2639. int i;
  2640. for (i = 0; list[i] != NULL; i++) {
  2641. if (!strcmp(str, list[i])) {
  2642. return true;
  2643. }
  2644. }
  2645. }
  2646. return false;
  2647. }
  2648. /*
  2649. * Check that every option set in @bs->options is also set in
  2650. * @new_opts.
  2651. *
  2652. * Options listed in the common_options list and in
  2653. * @bs->drv->mutable_opts are skipped.
  2654. *
  2655. * Return 0 on success, otherwise return -EINVAL and set @errp.
  2656. */
  2657. static int bdrv_reset_options_allowed(BlockDriverState *bs,
  2658. const QDict *new_opts, Error **errp)
  2659. {
  2660. const QDictEntry *e;
  2661. /* These options are common to all block drivers and are handled
  2662. * in bdrv_reopen_prepare() so they can be left out of @new_opts */
  2663. const char *const common_options[] = {
  2664. "node-name", "discard", "cache.direct", "cache.no-flush",
  2665. "read-only", "auto-read-only", "detect-zeroes", NULL
  2666. };
  2667. for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
  2668. if (!qdict_haskey(new_opts, e->key) &&
  2669. !is_str_in_list(e->key, common_options) &&
  2670. !is_str_in_list(e->key, bs->drv->mutable_opts)) {
  2671. error_setg(errp, "Option '%s' cannot be reset "
  2672. "to its default value", e->key);
  2673. return -EINVAL;
  2674. }
  2675. }
  2676. return 0;
  2677. }
  2678. /*
  2679. * Returns true if @child can be reached recursively from @bs
  2680. */
  2681. static bool bdrv_recurse_has_child(BlockDriverState *bs,
  2682. BlockDriverState *child)
  2683. {
  2684. BdrvChild *c;
  2685. if (bs == child) {
  2686. return true;
  2687. }
  2688. QLIST_FOREACH(c, &bs->children, next) {
  2689. if (bdrv_recurse_has_child(c->bs, child)) {
  2690. return true;
  2691. }
  2692. }
  2693. return false;
  2694. }
  2695. /*
  2696. * Adds a BlockDriverState to a simple queue for an atomic, transactional
  2697. * reopen of multiple devices.
  2698. *
  2699. * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
  2700. * already performed, or alternatively may be NULL a new BlockReopenQueue will
  2701. * be created and initialized. This newly created BlockReopenQueue should be
  2702. * passed back in for subsequent calls that are intended to be of the same
  2703. * atomic 'set'.
  2704. *
  2705. * bs is the BlockDriverState to add to the reopen queue.
  2706. *
  2707. * options contains the changed options for the associated bs
  2708. * (the BlockReopenQueue takes ownership)
  2709. *
  2710. * flags contains the open flags for the associated bs
  2711. *
  2712. * returns a pointer to bs_queue, which is either the newly allocated
  2713. * bs_queue, or the existing bs_queue being used.
  2714. *
  2715. * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
  2716. */
  2717. static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
  2718. BlockDriverState *bs,
  2719. QDict *options,
  2720. const BdrvChildRole *role,
  2721. QDict *parent_options,
  2722. int parent_flags,
  2723. bool keep_old_opts)
  2724. {
  2725. assert(bs != NULL);
  2726. BlockReopenQueueEntry *bs_entry;
  2727. BdrvChild *child;
  2728. QDict *old_options, *explicit_options, *options_copy;
  2729. int flags;
  2730. QemuOpts *opts;
  2731. /* Make sure that the caller remembered to use a drained section. This is
  2732. * important to avoid graph changes between the recursive queuing here and
  2733. * bdrv_reopen_multiple(). */
  2734. assert(bs->quiesce_counter > 0);
  2735. if (bs_queue == NULL) {
  2736. bs_queue = g_new0(BlockReopenQueue, 1);
  2737. QSIMPLEQ_INIT(bs_queue);
  2738. }
  2739. if (!options) {
  2740. options = qdict_new();
  2741. }
  2742. /* Check if this BlockDriverState is already in the queue */
  2743. QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
  2744. if (bs == bs_entry->state.bs) {
  2745. break;
  2746. }
  2747. }
  2748. /*
  2749. * Precedence of options:
  2750. * 1. Explicitly passed in options (highest)
  2751. * 2. Retained from explicitly set options of bs
  2752. * 3. Inherited from parent node
  2753. * 4. Retained from effective options of bs
  2754. */
  2755. /* Old explicitly set values (don't overwrite by inherited value) */
  2756. if (bs_entry || keep_old_opts) {
  2757. old_options = qdict_clone_shallow(bs_entry ?
  2758. bs_entry->state.explicit_options :
  2759. bs->explicit_options);
  2760. bdrv_join_options(bs, options, old_options);
  2761. qobject_unref(old_options);
  2762. }
  2763. explicit_options = qdict_clone_shallow(options);
  2764. /* Inherit from parent node */
  2765. if (parent_options) {
  2766. flags = 0;
  2767. role->inherit_options(&flags, options, parent_flags, parent_options);
  2768. } else {
  2769. flags = bdrv_get_flags(bs);
  2770. }
  2771. if (keep_old_opts) {
  2772. /* Old values are used for options that aren't set yet */
  2773. old_options = qdict_clone_shallow(bs->options);
  2774. bdrv_join_options(bs, options, old_options);
  2775. qobject_unref(old_options);
  2776. }
  2777. /* We have the final set of options so let's update the flags */
  2778. options_copy = qdict_clone_shallow(options);
  2779. opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
  2780. qemu_opts_absorb_qdict(opts, options_copy, NULL);
  2781. update_flags_from_options(&flags, opts);
  2782. qemu_opts_del(opts);
  2783. qobject_unref(options_copy);
  2784. /* bdrv_open_inherit() sets and clears some additional flags internally */
  2785. flags &= ~BDRV_O_PROTOCOL;
  2786. if (flags & BDRV_O_RDWR) {
  2787. flags |= BDRV_O_ALLOW_RDWR;
  2788. }
  2789. if (!bs_entry) {
  2790. bs_entry = g_new0(BlockReopenQueueEntry, 1);
  2791. QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
  2792. } else {
  2793. qobject_unref(bs_entry->state.options);
  2794. qobject_unref(bs_entry->state.explicit_options);
  2795. }
  2796. bs_entry->state.bs = bs;
  2797. bs_entry->state.options = options;
  2798. bs_entry->state.explicit_options = explicit_options;
  2799. bs_entry->state.flags = flags;
  2800. /* This needs to be overwritten in bdrv_reopen_prepare() */
  2801. bs_entry->state.perm = UINT64_MAX;
  2802. bs_entry->state.shared_perm = 0;
  2803. /*
  2804. * If keep_old_opts is false then it means that unspecified
  2805. * options must be reset to their original value. We don't allow
  2806. * resetting 'backing' but we need to know if the option is
  2807. * missing in order to decide if we have to return an error.
  2808. */
  2809. if (!keep_old_opts) {
  2810. bs_entry->state.backing_missing =
  2811. !qdict_haskey(options, "backing") &&
  2812. !qdict_haskey(options, "backing.driver");
  2813. }
  2814. QLIST_FOREACH(child, &bs->children, next) {
  2815. QDict *new_child_options = NULL;
  2816. bool child_keep_old = keep_old_opts;
  2817. /* reopen can only change the options of block devices that were
  2818. * implicitly created and inherited options. For other (referenced)
  2819. * block devices, a syntax like "backing.foo" results in an error. */
  2820. if (child->bs->inherits_from != bs) {
  2821. continue;
  2822. }
  2823. /* Check if the options contain a child reference */
  2824. if (qdict_haskey(options, child->name)) {
  2825. const char *childref = qdict_get_try_str(options, child->name);
  2826. /*
  2827. * The current child must not be reopened if the child
  2828. * reference is null or points to a different node.
  2829. */
  2830. if (g_strcmp0(childref, child->bs->node_name)) {
  2831. continue;
  2832. }
  2833. /*
  2834. * If the child reference points to the current child then
  2835. * reopen it with its existing set of options (note that
  2836. * it can still inherit new options from the parent).
  2837. */
  2838. child_keep_old = true;
  2839. } else {
  2840. /* Extract child options ("child-name.*") */
  2841. char *child_key_dot = g_strdup_printf("%s.", child->name);
  2842. qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
  2843. qdict_extract_subqdict(options, &new_child_options, child_key_dot);
  2844. g_free(child_key_dot);
  2845. }
  2846. bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
  2847. child->role, options, flags, child_keep_old);
  2848. }
  2849. return bs_queue;
  2850. }
  2851. BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
  2852. BlockDriverState *bs,
  2853. QDict *options, bool keep_old_opts)
  2854. {
  2855. return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, NULL, 0,
  2856. keep_old_opts);
  2857. }
  2858. /*
  2859. * Reopen multiple BlockDriverStates atomically & transactionally.
  2860. *
  2861. * The queue passed in (bs_queue) must have been built up previous
  2862. * via bdrv_reopen_queue().
  2863. *
  2864. * Reopens all BDS specified in the queue, with the appropriate
  2865. * flags. All devices are prepared for reopen, and failure of any
  2866. * device will cause all device changes to be abandoned, and intermediate
  2867. * data cleaned up.
  2868. *
  2869. * If all devices prepare successfully, then the changes are committed
  2870. * to all devices.
  2871. *
  2872. * All affected nodes must be drained between bdrv_reopen_queue() and
  2873. * bdrv_reopen_multiple().
  2874. */
  2875. int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
  2876. {
  2877. int ret = -1;
  2878. BlockReopenQueueEntry *bs_entry, *next;
  2879. assert(bs_queue != NULL);
  2880. QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
  2881. assert(bs_entry->state.bs->quiesce_counter > 0);
  2882. if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, errp)) {
  2883. goto cleanup;
  2884. }
  2885. bs_entry->prepared = true;
  2886. }
  2887. QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
  2888. BDRVReopenState *state = &bs_entry->state;
  2889. ret = bdrv_check_perm(state->bs, bs_queue, state->perm,
  2890. state->shared_perm, NULL, errp);
  2891. if (ret < 0) {
  2892. goto cleanup_perm;
  2893. }
  2894. /* Check if new_backing_bs would accept the new permissions */
  2895. if (state->replace_backing_bs && state->new_backing_bs) {
  2896. uint64_t nperm, nshared;
  2897. bdrv_child_perm(state->bs, state->new_backing_bs,
  2898. NULL, &child_backing, bs_queue,
  2899. state->perm, state->shared_perm,
  2900. &nperm, &nshared);
  2901. ret = bdrv_check_update_perm(state->new_backing_bs, NULL,
  2902. nperm, nshared, NULL, errp);
  2903. if (ret < 0) {
  2904. goto cleanup_perm;
  2905. }
  2906. }
  2907. bs_entry->perms_checked = true;
  2908. }
  2909. /* If we reach this point, we have success and just need to apply the
  2910. * changes
  2911. */
  2912. QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
  2913. bdrv_reopen_commit(&bs_entry->state);
  2914. }
  2915. ret = 0;
  2916. cleanup_perm:
  2917. QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
  2918. BDRVReopenState *state = &bs_entry->state;
  2919. if (!bs_entry->perms_checked) {
  2920. continue;
  2921. }
  2922. if (ret == 0) {
  2923. bdrv_set_perm(state->bs, state->perm, state->shared_perm);
  2924. } else {
  2925. bdrv_abort_perm_update(state->bs);
  2926. if (state->replace_backing_bs && state->new_backing_bs) {
  2927. bdrv_abort_perm_update(state->new_backing_bs);
  2928. }
  2929. }
  2930. }
  2931. cleanup:
  2932. QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
  2933. if (ret) {
  2934. if (bs_entry->prepared) {
  2935. bdrv_reopen_abort(&bs_entry->state);
  2936. }
  2937. qobject_unref(bs_entry->state.explicit_options);
  2938. qobject_unref(bs_entry->state.options);
  2939. }
  2940. if (bs_entry->state.new_backing_bs) {
  2941. bdrv_unref(bs_entry->state.new_backing_bs);
  2942. }
  2943. g_free(bs_entry);
  2944. }
  2945. g_free(bs_queue);
  2946. return ret;
  2947. }
  2948. int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
  2949. Error **errp)
  2950. {
  2951. int ret;
  2952. BlockReopenQueue *queue;
  2953. QDict *opts = qdict_new();
  2954. qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
  2955. bdrv_subtree_drained_begin(bs);
  2956. queue = bdrv_reopen_queue(NULL, bs, opts, true);
  2957. ret = bdrv_reopen_multiple(queue, errp);
  2958. bdrv_subtree_drained_end(bs);
  2959. return ret;
  2960. }
  2961. static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
  2962. BdrvChild *c)
  2963. {
  2964. BlockReopenQueueEntry *entry;
  2965. QSIMPLEQ_FOREACH(entry, q, entry) {
  2966. BlockDriverState *bs = entry->state.bs;
  2967. BdrvChild *child;
  2968. QLIST_FOREACH(child, &bs->children, next) {
  2969. if (child == c) {
  2970. return entry;
  2971. }
  2972. }
  2973. }
  2974. return NULL;
  2975. }
  2976. static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
  2977. uint64_t *perm, uint64_t *shared)
  2978. {
  2979. BdrvChild *c;
  2980. BlockReopenQueueEntry *parent;
  2981. uint64_t cumulative_perms = 0;
  2982. uint64_t cumulative_shared_perms = BLK_PERM_ALL;
  2983. QLIST_FOREACH(c, &bs->parents, next_parent) {
  2984. parent = find_parent_in_reopen_queue(q, c);
  2985. if (!parent) {
  2986. cumulative_perms |= c->perm;
  2987. cumulative_shared_perms &= c->shared_perm;
  2988. } else {
  2989. uint64_t nperm, nshared;
  2990. bdrv_child_perm(parent->state.bs, bs, c, c->role, q,
  2991. parent->state.perm, parent->state.shared_perm,
  2992. &nperm, &nshared);
  2993. cumulative_perms |= nperm;
  2994. cumulative_shared_perms &= nshared;
  2995. }
  2996. }
  2997. *perm = cumulative_perms;
  2998. *shared = cumulative_shared_perms;
  2999. }
  3000. /*
  3001. * Take a BDRVReopenState and check if the value of 'backing' in the
  3002. * reopen_state->options QDict is valid or not.
  3003. *
  3004. * If 'backing' is missing from the QDict then return 0.
  3005. *
  3006. * If 'backing' contains the node name of the backing file of
  3007. * reopen_state->bs then return 0.
  3008. *
  3009. * If 'backing' contains a different node name (or is null) then check
  3010. * whether the current backing file can be replaced with the new one.
  3011. * If that's the case then reopen_state->replace_backing_bs is set to
  3012. * true and reopen_state->new_backing_bs contains a pointer to the new
  3013. * backing BlockDriverState (or NULL).
  3014. *
  3015. * Return 0 on success, otherwise return < 0 and set @errp.
  3016. */
  3017. static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
  3018. Error **errp)
  3019. {
  3020. BlockDriverState *bs = reopen_state->bs;
  3021. BlockDriverState *overlay_bs, *new_backing_bs;
  3022. QObject *value;
  3023. const char *str;
  3024. value = qdict_get(reopen_state->options, "backing");
  3025. if (value == NULL) {
  3026. return 0;
  3027. }
  3028. switch (qobject_type(value)) {
  3029. case QTYPE_QNULL:
  3030. new_backing_bs = NULL;
  3031. break;
  3032. case QTYPE_QSTRING:
  3033. str = qobject_get_try_str(value);
  3034. new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
  3035. if (new_backing_bs == NULL) {
  3036. return -EINVAL;
  3037. } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
  3038. error_setg(errp, "Making '%s' a backing file of '%s' "
  3039. "would create a cycle", str, bs->node_name);
  3040. return -EINVAL;
  3041. }
  3042. break;
  3043. default:
  3044. /* 'backing' does not allow any other data type */
  3045. g_assert_not_reached();
  3046. }
  3047. /*
  3048. * TODO: before removing the x- prefix from x-blockdev-reopen we
  3049. * should move the new backing file into the right AioContext
  3050. * instead of returning an error.
  3051. */
  3052. if (new_backing_bs) {
  3053. if (bdrv_get_aio_context(new_backing_bs) != bdrv_get_aio_context(bs)) {
  3054. error_setg(errp, "Cannot use a new backing file "
  3055. "with a different AioContext");
  3056. return -EINVAL;
  3057. }
  3058. }
  3059. /*
  3060. * Find the "actual" backing file by skipping all links that point
  3061. * to an implicit node, if any (e.g. a commit filter node).
  3062. */
  3063. overlay_bs = bs;
  3064. while (backing_bs(overlay_bs) && backing_bs(overlay_bs)->implicit) {
  3065. overlay_bs = backing_bs(overlay_bs);
  3066. }
  3067. /* If we want to replace the backing file we need some extra checks */
  3068. if (new_backing_bs != backing_bs(overlay_bs)) {
  3069. /* Check for implicit nodes between bs and its backing file */
  3070. if (bs != overlay_bs) {
  3071. error_setg(errp, "Cannot change backing link if '%s' has "
  3072. "an implicit backing file", bs->node_name);
  3073. return -EPERM;
  3074. }
  3075. /* Check if the backing link that we want to replace is frozen */
  3076. if (bdrv_is_backing_chain_frozen(overlay_bs, backing_bs(overlay_bs),
  3077. errp)) {
  3078. return -EPERM;
  3079. }
  3080. reopen_state->replace_backing_bs = true;
  3081. if (new_backing_bs) {
  3082. bdrv_ref(new_backing_bs);
  3083. reopen_state->new_backing_bs = new_backing_bs;
  3084. }
  3085. }
  3086. return 0;
  3087. }
  3088. /*
  3089. * Prepares a BlockDriverState for reopen. All changes are staged in the
  3090. * 'opaque' field of the BDRVReopenState, which is used and allocated by
  3091. * the block driver layer .bdrv_reopen_prepare()
  3092. *
  3093. * bs is the BlockDriverState to reopen
  3094. * flags are the new open flags
  3095. * queue is the reopen queue
  3096. *
  3097. * Returns 0 on success, non-zero on error. On error errp will be set
  3098. * as well.
  3099. *
  3100. * On failure, bdrv_reopen_abort() will be called to clean up any data.
  3101. * It is the responsibility of the caller to then call the abort() or
  3102. * commit() for any other BDS that have been left in a prepare() state
  3103. *
  3104. */
  3105. int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
  3106. Error **errp)
  3107. {
  3108. int ret = -1;
  3109. int old_flags;
  3110. Error *local_err = NULL;
  3111. BlockDriver *drv;
  3112. QemuOpts *opts;
  3113. QDict *orig_reopen_opts;
  3114. char *discard = NULL;
  3115. bool read_only;
  3116. bool drv_prepared = false;
  3117. assert(reopen_state != NULL);
  3118. assert(reopen_state->bs->drv != NULL);
  3119. drv = reopen_state->bs->drv;
  3120. /* This function and each driver's bdrv_reopen_prepare() remove
  3121. * entries from reopen_state->options as they are processed, so
  3122. * we need to make a copy of the original QDict. */
  3123. orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
  3124. /* Process generic block layer options */
  3125. opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
  3126. qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
  3127. if (local_err) {
  3128. error_propagate(errp, local_err);
  3129. ret = -EINVAL;
  3130. goto error;
  3131. }
  3132. /* This was already called in bdrv_reopen_queue_child() so the flags
  3133. * are up-to-date. This time we simply want to remove the options from
  3134. * QemuOpts in order to indicate that they have been processed. */
  3135. old_flags = reopen_state->flags;
  3136. update_flags_from_options(&reopen_state->flags, opts);
  3137. assert(old_flags == reopen_state->flags);
  3138. discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
  3139. if (discard != NULL) {
  3140. if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
  3141. error_setg(errp, "Invalid discard option");
  3142. ret = -EINVAL;
  3143. goto error;
  3144. }
  3145. }
  3146. reopen_state->detect_zeroes =
  3147. bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
  3148. if (local_err) {
  3149. error_propagate(errp, local_err);
  3150. ret = -EINVAL;
  3151. goto error;
  3152. }
  3153. /* All other options (including node-name and driver) must be unchanged.
  3154. * Put them back into the QDict, so that they are checked at the end
  3155. * of this function. */
  3156. qemu_opts_to_qdict(opts, reopen_state->options);
  3157. /* If we are to stay read-only, do not allow permission change
  3158. * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
  3159. * not set, or if the BDS still has copy_on_read enabled */
  3160. read_only = !(reopen_state->flags & BDRV_O_RDWR);
  3161. ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
  3162. if (local_err) {
  3163. error_propagate(errp, local_err);
  3164. goto error;
  3165. }
  3166. /* Calculate required permissions after reopening */
  3167. bdrv_reopen_perm(queue, reopen_state->bs,
  3168. &reopen_state->perm, &reopen_state->shared_perm);
  3169. ret = bdrv_flush(reopen_state->bs);
  3170. if (ret) {
  3171. error_setg_errno(errp, -ret, "Error flushing drive");
  3172. goto error;
  3173. }
  3174. if (drv->bdrv_reopen_prepare) {
  3175. /*
  3176. * If a driver-specific option is missing, it means that we
  3177. * should reset it to its default value.
  3178. * But not all options allow that, so we need to check it first.
  3179. */
  3180. ret = bdrv_reset_options_allowed(reopen_state->bs,
  3181. reopen_state->options, errp);
  3182. if (ret) {
  3183. goto error;
  3184. }
  3185. ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
  3186. if (ret) {
  3187. if (local_err != NULL) {
  3188. error_propagate(errp, local_err);
  3189. } else {
  3190. bdrv_refresh_filename(reopen_state->bs);
  3191. error_setg(errp, "failed while preparing to reopen image '%s'",
  3192. reopen_state->bs->filename);
  3193. }
  3194. goto error;
  3195. }
  3196. } else {
  3197. /* It is currently mandatory to have a bdrv_reopen_prepare()
  3198. * handler for each supported drv. */
  3199. error_setg(errp, "Block format '%s' used by node '%s' "
  3200. "does not support reopening files", drv->format_name,
  3201. bdrv_get_device_or_node_name(reopen_state->bs));
  3202. ret = -1;
  3203. goto error;
  3204. }
  3205. drv_prepared = true;
  3206. /*
  3207. * We must provide the 'backing' option if the BDS has a backing
  3208. * file or if the image file has a backing file name as part of
  3209. * its metadata. Otherwise the 'backing' option can be omitted.
  3210. */
  3211. if (drv->supports_backing && reopen_state->backing_missing &&
  3212. (backing_bs(reopen_state->bs) || reopen_state->bs->backing_file[0])) {
  3213. error_setg(errp, "backing is missing for '%s'",
  3214. reopen_state->bs->node_name);
  3215. ret = -EINVAL;
  3216. goto error;
  3217. }
  3218. /*
  3219. * Allow changing the 'backing' option. The new value can be
  3220. * either a reference to an existing node (using its node name)
  3221. * or NULL to simply detach the current backing file.
  3222. */
  3223. ret = bdrv_reopen_parse_backing(reopen_state, errp);
  3224. if (ret < 0) {
  3225. goto error;
  3226. }
  3227. qdict_del(reopen_state->options, "backing");
  3228. /* Options that are not handled are only okay if they are unchanged
  3229. * compared to the old state. It is expected that some options are only
  3230. * used for the initial open, but not reopen (e.g. filename) */
  3231. if (qdict_size(reopen_state->options)) {
  3232. const QDictEntry *entry = qdict_first(reopen_state->options);
  3233. do {
  3234. QObject *new = entry->value;
  3235. QObject *old = qdict_get(reopen_state->bs->options, entry->key);
  3236. /* Allow child references (child_name=node_name) as long as they
  3237. * point to the current child (i.e. everything stays the same). */
  3238. if (qobject_type(new) == QTYPE_QSTRING) {
  3239. BdrvChild *child;
  3240. QLIST_FOREACH(child, &reopen_state->bs->children, next) {
  3241. if (!strcmp(child->name, entry->key)) {
  3242. break;
  3243. }
  3244. }
  3245. if (child) {
  3246. const char *str = qobject_get_try_str(new);
  3247. if (!strcmp(child->bs->node_name, str)) {
  3248. continue; /* Found child with this name, skip option */
  3249. }
  3250. }
  3251. }
  3252. /*
  3253. * TODO: When using -drive to specify blockdev options, all values
  3254. * will be strings; however, when using -blockdev, blockdev-add or
  3255. * filenames using the json:{} pseudo-protocol, they will be
  3256. * correctly typed.
  3257. * In contrast, reopening options are (currently) always strings
  3258. * (because you can only specify them through qemu-io; all other
  3259. * callers do not specify any options).
  3260. * Therefore, when using anything other than -drive to create a BDS,
  3261. * this cannot detect non-string options as unchanged, because
  3262. * qobject_is_equal() always returns false for objects of different
  3263. * type. In the future, this should be remedied by correctly typing
  3264. * all options. For now, this is not too big of an issue because
  3265. * the user can simply omit options which cannot be changed anyway,
  3266. * so they will stay unchanged.
  3267. */
  3268. if (!qobject_is_equal(new, old)) {
  3269. error_setg(errp, "Cannot change the option '%s'", entry->key);
  3270. ret = -EINVAL;
  3271. goto error;
  3272. }
  3273. } while ((entry = qdict_next(reopen_state->options, entry)));
  3274. }
  3275. ret = 0;
  3276. /* Restore the original reopen_state->options QDict */
  3277. qobject_unref(reopen_state->options);
  3278. reopen_state->options = qobject_ref(orig_reopen_opts);
  3279. error:
  3280. if (ret < 0 && drv_prepared) {
  3281. /* drv->bdrv_reopen_prepare() has succeeded, so we need to
  3282. * call drv->bdrv_reopen_abort() before signaling an error
  3283. * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
  3284. * when the respective bdrv_reopen_prepare() has failed) */
  3285. if (drv->bdrv_reopen_abort) {
  3286. drv->bdrv_reopen_abort(reopen_state);
  3287. }
  3288. }
  3289. qemu_opts_del(opts);
  3290. qobject_unref(orig_reopen_opts);
  3291. g_free(discard);
  3292. return ret;
  3293. }
  3294. /*
  3295. * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
  3296. * makes them final by swapping the staging BlockDriverState contents into
  3297. * the active BlockDriverState contents.
  3298. */
  3299. void bdrv_reopen_commit(BDRVReopenState *reopen_state)
  3300. {
  3301. BlockDriver *drv;
  3302. BlockDriverState *bs;
  3303. BdrvChild *child;
  3304. bool old_can_write, new_can_write;
  3305. assert(reopen_state != NULL);
  3306. bs = reopen_state->bs;
  3307. drv = bs->drv;
  3308. assert(drv != NULL);
  3309. old_can_write =
  3310. !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE);
  3311. /* If there are any driver level actions to take */
  3312. if (drv->bdrv_reopen_commit) {
  3313. drv->bdrv_reopen_commit(reopen_state);
  3314. }
  3315. /* set BDS specific flags now */
  3316. qobject_unref(bs->explicit_options);
  3317. qobject_unref(bs->options);
  3318. bs->explicit_options = reopen_state->explicit_options;
  3319. bs->options = reopen_state->options;
  3320. bs->open_flags = reopen_state->flags;
  3321. bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
  3322. bs->detect_zeroes = reopen_state->detect_zeroes;
  3323. if (reopen_state->replace_backing_bs) {
  3324. qdict_del(bs->explicit_options, "backing");
  3325. qdict_del(bs->options, "backing");
  3326. }
  3327. /* Remove child references from bs->options and bs->explicit_options.
  3328. * Child options were already removed in bdrv_reopen_queue_child() */
  3329. QLIST_FOREACH(child, &bs->children, next) {
  3330. qdict_del(bs->explicit_options, child->name);
  3331. qdict_del(bs->options, child->name);
  3332. }
  3333. /*
  3334. * Change the backing file if a new one was specified. We do this
  3335. * after updating bs->options, so bdrv_refresh_filename() (called
  3336. * from bdrv_set_backing_hd()) has the new values.
  3337. */
  3338. if (reopen_state->replace_backing_bs) {
  3339. BlockDriverState *old_backing_bs = backing_bs(bs);
  3340. assert(!old_backing_bs || !old_backing_bs->implicit);
  3341. /* Abort the permission update on the backing bs we're detaching */
  3342. if (old_backing_bs) {
  3343. bdrv_abort_perm_update(old_backing_bs);
  3344. }
  3345. bdrv_set_backing_hd(bs, reopen_state->new_backing_bs, &error_abort);
  3346. }
  3347. bdrv_refresh_limits(bs, NULL);
  3348. new_can_write =
  3349. !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE);
  3350. if (!old_can_write && new_can_write && drv->bdrv_reopen_bitmaps_rw) {
  3351. Error *local_err = NULL;
  3352. if (drv->bdrv_reopen_bitmaps_rw(bs, &local_err) < 0) {
  3353. /* This is not fatal, bitmaps just left read-only, so all following
  3354. * writes will fail. User can remove read-only bitmaps to unblock
  3355. * writes.
  3356. */
  3357. error_reportf_err(local_err,
  3358. "%s: Failed to make dirty bitmaps writable: ",
  3359. bdrv_get_node_name(bs));
  3360. }
  3361. }
  3362. }
  3363. /*
  3364. * Abort the reopen, and delete and free the staged changes in
  3365. * reopen_state
  3366. */
  3367. void bdrv_reopen_abort(BDRVReopenState *reopen_state)
  3368. {
  3369. BlockDriver *drv;
  3370. assert(reopen_state != NULL);
  3371. drv = reopen_state->bs->drv;
  3372. assert(drv != NULL);
  3373. if (drv->bdrv_reopen_abort) {
  3374. drv->bdrv_reopen_abort(reopen_state);
  3375. }
  3376. }
  3377. static void bdrv_close(BlockDriverState *bs)
  3378. {
  3379. BdrvAioNotifier *ban, *ban_next;
  3380. BdrvChild *child, *next;
  3381. assert(!bs->job);
  3382. assert(!bs->refcnt);
  3383. bdrv_drained_begin(bs); /* complete I/O */
  3384. bdrv_flush(bs);
  3385. bdrv_drain(bs); /* in case flush left pending I/O */
  3386. if (bs->drv) {
  3387. if (bs->drv->bdrv_close) {
  3388. bs->drv->bdrv_close(bs);
  3389. }
  3390. bs->drv = NULL;
  3391. }
  3392. QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
  3393. bdrv_unref_child(bs, child);
  3394. }
  3395. bs->backing = NULL;
  3396. bs->file = NULL;
  3397. g_free(bs->opaque);
  3398. bs->opaque = NULL;
  3399. atomic_set(&bs->copy_on_read, 0);
  3400. bs->backing_file[0] = '\0';
  3401. bs->backing_format[0] = '\0';
  3402. bs->total_sectors = 0;
  3403. bs->encrypted = false;
  3404. bs->sg = false;
  3405. qobject_unref(bs->options);
  3406. qobject_unref(bs->explicit_options);
  3407. bs->options = NULL;
  3408. bs->explicit_options = NULL;
  3409. qobject_unref(bs->full_open_options);
  3410. bs->full_open_options = NULL;
  3411. bdrv_release_named_dirty_bitmaps(bs);
  3412. assert(QLIST_EMPTY(&bs->dirty_bitmaps));
  3413. QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
  3414. g_free(ban);
  3415. }
  3416. QLIST_INIT(&bs->aio_notifiers);
  3417. bdrv_drained_end(bs);
  3418. }
  3419. void bdrv_close_all(void)
  3420. {
  3421. assert(job_next(NULL) == NULL);
  3422. nbd_export_close_all();
  3423. /* Drop references from requests still in flight, such as canceled block
  3424. * jobs whose AIO context has not been polled yet */
  3425. bdrv_drain_all();
  3426. blk_remove_all_bs();
  3427. blockdev_close_all_bdrv_states();
  3428. assert(QTAILQ_EMPTY(&all_bdrv_states));
  3429. }
  3430. static bool should_update_child(BdrvChild *c, BlockDriverState *to)
  3431. {
  3432. GQueue *queue;
  3433. GHashTable *found;
  3434. bool ret;
  3435. if (c->role->stay_at_node) {
  3436. return false;
  3437. }
  3438. /* If the child @c belongs to the BDS @to, replacing the current
  3439. * c->bs by @to would mean to create a loop.
  3440. *
  3441. * Such a case occurs when appending a BDS to a backing chain.
  3442. * For instance, imagine the following chain:
  3443. *
  3444. * guest device -> node A -> further backing chain...
  3445. *
  3446. * Now we create a new BDS B which we want to put on top of this
  3447. * chain, so we first attach A as its backing node:
  3448. *
  3449. * node B
  3450. * |
  3451. * v
  3452. * guest device -> node A -> further backing chain...
  3453. *
  3454. * Finally we want to replace A by B. When doing that, we want to
  3455. * replace all pointers to A by pointers to B -- except for the
  3456. * pointer from B because (1) that would create a loop, and (2)
  3457. * that pointer should simply stay intact:
  3458. *
  3459. * guest device -> node B
  3460. * |
  3461. * v
  3462. * node A -> further backing chain...
  3463. *
  3464. * In general, when replacing a node A (c->bs) by a node B (@to),
  3465. * if A is a child of B, that means we cannot replace A by B there
  3466. * because that would create a loop. Silently detaching A from B
  3467. * is also not really an option. So overall just leaving A in
  3468. * place there is the most sensible choice.
  3469. *
  3470. * We would also create a loop in any cases where @c is only
  3471. * indirectly referenced by @to. Prevent this by returning false
  3472. * if @c is found (by breadth-first search) anywhere in the whole
  3473. * subtree of @to.
  3474. */
  3475. ret = true;
  3476. found = g_hash_table_new(NULL, NULL);
  3477. g_hash_table_add(found, to);
  3478. queue = g_queue_new();
  3479. g_queue_push_tail(queue, to);
  3480. while (!g_queue_is_empty(queue)) {
  3481. BlockDriverState *v = g_queue_pop_head(queue);
  3482. BdrvChild *c2;
  3483. QLIST_FOREACH(c2, &v->children, next) {
  3484. if (c2 == c) {
  3485. ret = false;
  3486. break;
  3487. }
  3488. if (g_hash_table_contains(found, c2->bs)) {
  3489. continue;
  3490. }
  3491. g_queue_push_tail(queue, c2->bs);
  3492. g_hash_table_add(found, c2->bs);
  3493. }
  3494. }
  3495. g_queue_free(queue);
  3496. g_hash_table_destroy(found);
  3497. return ret;
  3498. }
  3499. void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
  3500. Error **errp)
  3501. {
  3502. BdrvChild *c, *next;
  3503. GSList *list = NULL, *p;
  3504. uint64_t old_perm, old_shared;
  3505. uint64_t perm = 0, shared = BLK_PERM_ALL;
  3506. int ret;
  3507. /* Make sure that @from doesn't go away until we have successfully attached
  3508. * all of its parents to @to. */
  3509. bdrv_ref(from);
  3510. assert(qemu_get_current_aio_context() == qemu_get_aio_context());
  3511. bdrv_drained_begin(from);
  3512. /* Put all parents into @list and calculate their cumulative permissions */
  3513. QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
  3514. assert(c->bs == from);
  3515. if (!should_update_child(c, to)) {
  3516. continue;
  3517. }
  3518. if (c->frozen) {
  3519. error_setg(errp, "Cannot change '%s' link to '%s'",
  3520. c->name, from->node_name);
  3521. goto out;
  3522. }
  3523. list = g_slist_prepend(list, c);
  3524. perm |= c->perm;
  3525. shared &= c->shared_perm;
  3526. }
  3527. /* Check whether the required permissions can be granted on @to, ignoring
  3528. * all BdrvChild in @list so that they can't block themselves. */
  3529. ret = bdrv_check_update_perm(to, NULL, perm, shared, list, errp);
  3530. if (ret < 0) {
  3531. bdrv_abort_perm_update(to);
  3532. goto out;
  3533. }
  3534. /* Now actually perform the change. We performed the permission check for
  3535. * all elements of @list at once, so set the permissions all at once at the
  3536. * very end. */
  3537. for (p = list; p != NULL; p = p->next) {
  3538. c = p->data;
  3539. bdrv_ref(to);
  3540. bdrv_replace_child_noperm(c, to);
  3541. bdrv_unref(from);
  3542. }
  3543. bdrv_get_cumulative_perm(to, &old_perm, &old_shared);
  3544. bdrv_set_perm(to, old_perm | perm, old_shared | shared);
  3545. out:
  3546. g_slist_free(list);
  3547. bdrv_drained_end(from);
  3548. bdrv_unref(from);
  3549. }
  3550. /*
  3551. * Add new bs contents at the top of an image chain while the chain is
  3552. * live, while keeping required fields on the top layer.
  3553. *
  3554. * This will modify the BlockDriverState fields, and swap contents
  3555. * between bs_new and bs_top. Both bs_new and bs_top are modified.
  3556. *
  3557. * bs_new must not be attached to a BlockBackend.
  3558. *
  3559. * This function does not create any image files.
  3560. *
  3561. * bdrv_append() takes ownership of a bs_new reference and unrefs it because
  3562. * that's what the callers commonly need. bs_new will be referenced by the old
  3563. * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
  3564. * reference of its own, it must call bdrv_ref().
  3565. */
  3566. void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
  3567. Error **errp)
  3568. {
  3569. Error *local_err = NULL;
  3570. bdrv_set_backing_hd(bs_new, bs_top, &local_err);
  3571. if (local_err) {
  3572. error_propagate(errp, local_err);
  3573. goto out;
  3574. }
  3575. bdrv_replace_node(bs_top, bs_new, &local_err);
  3576. if (local_err) {
  3577. error_propagate(errp, local_err);
  3578. bdrv_set_backing_hd(bs_new, NULL, &error_abort);
  3579. goto out;
  3580. }
  3581. /* bs_new is now referenced by its new parents, we don't need the
  3582. * additional reference any more. */
  3583. out:
  3584. bdrv_unref(bs_new);
  3585. }
  3586. static void bdrv_delete(BlockDriverState *bs)
  3587. {
  3588. assert(!bs->job);
  3589. assert(bdrv_op_blocker_is_empty(bs));
  3590. assert(!bs->refcnt);
  3591. /* remove from list, if necessary */
  3592. if (bs->node_name[0] != '\0') {
  3593. QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
  3594. }
  3595. QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
  3596. bdrv_close(bs);
  3597. g_free(bs);
  3598. }
  3599. /*
  3600. * Run consistency checks on an image
  3601. *
  3602. * Returns 0 if the check could be completed (it doesn't mean that the image is
  3603. * free of errors) or -errno when an internal error occurred. The results of the
  3604. * check are stored in res.
  3605. */
  3606. static int coroutine_fn bdrv_co_check(BlockDriverState *bs,
  3607. BdrvCheckResult *res, BdrvCheckMode fix)
  3608. {
  3609. if (bs->drv == NULL) {
  3610. return -ENOMEDIUM;
  3611. }
  3612. if (bs->drv->bdrv_co_check == NULL) {
  3613. return -ENOTSUP;
  3614. }
  3615. memset(res, 0, sizeof(*res));
  3616. return bs->drv->bdrv_co_check(bs, res, fix);
  3617. }
  3618. typedef struct CheckCo {
  3619. BlockDriverState *bs;
  3620. BdrvCheckResult *res;
  3621. BdrvCheckMode fix;
  3622. int ret;
  3623. } CheckCo;
  3624. static void coroutine_fn bdrv_check_co_entry(void *opaque)
  3625. {
  3626. CheckCo *cco = opaque;
  3627. cco->ret = bdrv_co_check(cco->bs, cco->res, cco->fix);
  3628. aio_wait_kick();
  3629. }
  3630. int bdrv_check(BlockDriverState *bs,
  3631. BdrvCheckResult *res, BdrvCheckMode fix)
  3632. {
  3633. Coroutine *co;
  3634. CheckCo cco = {
  3635. .bs = bs,
  3636. .res = res,
  3637. .ret = -EINPROGRESS,
  3638. .fix = fix,
  3639. };
  3640. if (qemu_in_coroutine()) {
  3641. /* Fast-path if already in coroutine context */
  3642. bdrv_check_co_entry(&cco);
  3643. } else {
  3644. co = qemu_coroutine_create(bdrv_check_co_entry, &cco);
  3645. bdrv_coroutine_enter(bs, co);
  3646. BDRV_POLL_WHILE(bs, cco.ret == -EINPROGRESS);
  3647. }
  3648. return cco.ret;
  3649. }
  3650. /*
  3651. * Return values:
  3652. * 0 - success
  3653. * -EINVAL - backing format specified, but no file
  3654. * -ENOSPC - can't update the backing file because no space is left in the
  3655. * image file header
  3656. * -ENOTSUP - format driver doesn't support changing the backing file
  3657. */
  3658. int bdrv_change_backing_file(BlockDriverState *bs,
  3659. const char *backing_file, const char *backing_fmt)
  3660. {
  3661. BlockDriver *drv = bs->drv;
  3662. int ret;
  3663. if (!drv) {
  3664. return -ENOMEDIUM;
  3665. }
  3666. /* Backing file format doesn't make sense without a backing file */
  3667. if (backing_fmt && !backing_file) {
  3668. return -EINVAL;
  3669. }
  3670. if (drv->bdrv_change_backing_file != NULL) {
  3671. ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
  3672. } else {
  3673. ret = -ENOTSUP;
  3674. }
  3675. if (ret == 0) {
  3676. pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
  3677. pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
  3678. pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
  3679. backing_file ?: "");
  3680. }
  3681. return ret;
  3682. }
  3683. /*
  3684. * Finds the image layer in the chain that has 'bs' as its backing file.
  3685. *
  3686. * active is the current topmost image.
  3687. *
  3688. * Returns NULL if bs is not found in active's image chain,
  3689. * or if active == bs.
  3690. *
  3691. * Returns the bottommost base image if bs == NULL.
  3692. */
  3693. BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
  3694. BlockDriverState *bs)
  3695. {
  3696. while (active && bs != backing_bs(active)) {
  3697. active = backing_bs(active);
  3698. }
  3699. return active;
  3700. }
  3701. /* Given a BDS, searches for the base layer. */
  3702. BlockDriverState *bdrv_find_base(BlockDriverState *bs)
  3703. {
  3704. return bdrv_find_overlay(bs, NULL);
  3705. }
  3706. /*
  3707. * Return true if at least one of the backing links between @bs and
  3708. * @base is frozen. @errp is set if that's the case.
  3709. * @base must be reachable from @bs, or NULL.
  3710. */
  3711. bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
  3712. Error **errp)
  3713. {
  3714. BlockDriverState *i;
  3715. for (i = bs; i != base; i = backing_bs(i)) {
  3716. if (i->backing && i->backing->frozen) {
  3717. error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
  3718. i->backing->name, i->node_name,
  3719. backing_bs(i)->node_name);
  3720. return true;
  3721. }
  3722. }
  3723. return false;
  3724. }
  3725. /*
  3726. * Freeze all backing links between @bs and @base.
  3727. * If any of the links is already frozen the operation is aborted and
  3728. * none of the links are modified.
  3729. * @base must be reachable from @bs, or NULL.
  3730. * Returns 0 on success. On failure returns < 0 and sets @errp.
  3731. */
  3732. int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
  3733. Error **errp)
  3734. {
  3735. BlockDriverState *i;
  3736. if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
  3737. return -EPERM;
  3738. }
  3739. for (i = bs; i != base; i = backing_bs(i)) {
  3740. if (i->backing) {
  3741. i->backing->frozen = true;
  3742. }
  3743. }
  3744. return 0;
  3745. }
  3746. /*
  3747. * Unfreeze all backing links between @bs and @base. The caller must
  3748. * ensure that all links are frozen before using this function.
  3749. * @base must be reachable from @bs, or NULL.
  3750. */
  3751. void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
  3752. {
  3753. BlockDriverState *i;
  3754. for (i = bs; i != base; i = backing_bs(i)) {
  3755. if (i->backing) {
  3756. assert(i->backing->frozen);
  3757. i->backing->frozen = false;
  3758. }
  3759. }
  3760. }
  3761. /*
  3762. * Drops images above 'base' up to and including 'top', and sets the image
  3763. * above 'top' to have base as its backing file.
  3764. *
  3765. * Requires that the overlay to 'top' is opened r/w, so that the backing file
  3766. * information in 'bs' can be properly updated.
  3767. *
  3768. * E.g., this will convert the following chain:
  3769. * bottom <- base <- intermediate <- top <- active
  3770. *
  3771. * to
  3772. *
  3773. * bottom <- base <- active
  3774. *
  3775. * It is allowed for bottom==base, in which case it converts:
  3776. *
  3777. * base <- intermediate <- top <- active
  3778. *
  3779. * to
  3780. *
  3781. * base <- active
  3782. *
  3783. * If backing_file_str is non-NULL, it will be used when modifying top's
  3784. * overlay image metadata.
  3785. *
  3786. * Error conditions:
  3787. * if active == top, that is considered an error
  3788. *
  3789. */
  3790. int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
  3791. const char *backing_file_str)
  3792. {
  3793. BlockDriverState *explicit_top = top;
  3794. bool update_inherits_from;
  3795. BdrvChild *c, *next;
  3796. Error *local_err = NULL;
  3797. int ret = -EIO;
  3798. bdrv_ref(top);
  3799. if (!top->drv || !base->drv) {
  3800. goto exit;
  3801. }
  3802. /* Make sure that base is in the backing chain of top */
  3803. if (!bdrv_chain_contains(top, base)) {
  3804. goto exit;
  3805. }
  3806. /* This function changes all links that point to top and makes
  3807. * them point to base. Check that none of them is frozen. */
  3808. QLIST_FOREACH(c, &top->parents, next_parent) {
  3809. if (c->frozen) {
  3810. goto exit;
  3811. }
  3812. }
  3813. /* If 'base' recursively inherits from 'top' then we should set
  3814. * base->inherits_from to top->inherits_from after 'top' and all
  3815. * other intermediate nodes have been dropped.
  3816. * If 'top' is an implicit node (e.g. "commit_top") we should skip
  3817. * it because no one inherits from it. We use explicit_top for that. */
  3818. while (explicit_top && explicit_top->implicit) {
  3819. explicit_top = backing_bs(explicit_top);
  3820. }
  3821. update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
  3822. /* success - we can delete the intermediate states, and link top->base */
  3823. /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
  3824. * we've figured out how they should work. */
  3825. if (!backing_file_str) {
  3826. bdrv_refresh_filename(base);
  3827. backing_file_str = base->filename;
  3828. }
  3829. QLIST_FOREACH_SAFE(c, &top->parents, next_parent, next) {
  3830. /* Check whether we are allowed to switch c from top to base */
  3831. GSList *ignore_children = g_slist_prepend(NULL, c);
  3832. ret = bdrv_check_update_perm(base, NULL, c->perm, c->shared_perm,
  3833. ignore_children, &local_err);
  3834. g_slist_free(ignore_children);
  3835. if (ret < 0) {
  3836. error_report_err(local_err);
  3837. goto exit;
  3838. }
  3839. /* If so, update the backing file path in the image file */
  3840. if (c->role->update_filename) {
  3841. ret = c->role->update_filename(c, base, backing_file_str,
  3842. &local_err);
  3843. if (ret < 0) {
  3844. bdrv_abort_perm_update(base);
  3845. error_report_err(local_err);
  3846. goto exit;
  3847. }
  3848. }
  3849. /* Do the actual switch in the in-memory graph.
  3850. * Completes bdrv_check_update_perm() transaction internally. */
  3851. bdrv_ref(base);
  3852. bdrv_replace_child(c, base);
  3853. bdrv_unref(top);
  3854. }
  3855. if (update_inherits_from) {
  3856. base->inherits_from = explicit_top->inherits_from;
  3857. }
  3858. ret = 0;
  3859. exit:
  3860. bdrv_unref(top);
  3861. return ret;
  3862. }
  3863. /**
  3864. * Length of a allocated file in bytes. Sparse files are counted by actual
  3865. * allocated space. Return < 0 if error or unknown.
  3866. */
  3867. int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
  3868. {
  3869. BlockDriver *drv = bs->drv;
  3870. if (!drv) {
  3871. return -ENOMEDIUM;
  3872. }
  3873. if (drv->bdrv_get_allocated_file_size) {
  3874. return drv->bdrv_get_allocated_file_size(bs);
  3875. }
  3876. if (bs->file) {
  3877. return bdrv_get_allocated_file_size(bs->file->bs);
  3878. }
  3879. return -ENOTSUP;
  3880. }
  3881. /*
  3882. * bdrv_measure:
  3883. * @drv: Format driver
  3884. * @opts: Creation options for new image
  3885. * @in_bs: Existing image containing data for new image (may be NULL)
  3886. * @errp: Error object
  3887. * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
  3888. * or NULL on error
  3889. *
  3890. * Calculate file size required to create a new image.
  3891. *
  3892. * If @in_bs is given then space for allocated clusters and zero clusters
  3893. * from that image are included in the calculation. If @opts contains a
  3894. * backing file that is shared by @in_bs then backing clusters may be omitted
  3895. * from the calculation.
  3896. *
  3897. * If @in_bs is NULL then the calculation includes no allocated clusters
  3898. * unless a preallocation option is given in @opts.
  3899. *
  3900. * Note that @in_bs may use a different BlockDriver from @drv.
  3901. *
  3902. * If an error occurs the @errp pointer is set.
  3903. */
  3904. BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
  3905. BlockDriverState *in_bs, Error **errp)
  3906. {
  3907. if (!drv->bdrv_measure) {
  3908. error_setg(errp, "Block driver '%s' does not support size measurement",
  3909. drv->format_name);
  3910. return NULL;
  3911. }
  3912. return drv->bdrv_measure(opts, in_bs, errp);
  3913. }
  3914. /**
  3915. * Return number of sectors on success, -errno on error.
  3916. */
  3917. int64_t bdrv_nb_sectors(BlockDriverState *bs)
  3918. {
  3919. BlockDriver *drv = bs->drv;
  3920. if (!drv)
  3921. return -ENOMEDIUM;
  3922. if (drv->has_variable_length) {
  3923. int ret = refresh_total_sectors(bs, bs->total_sectors);
  3924. if (ret < 0) {
  3925. return ret;
  3926. }
  3927. }
  3928. return bs->total_sectors;
  3929. }
  3930. /**
  3931. * Return length in bytes on success, -errno on error.
  3932. * The length is always a multiple of BDRV_SECTOR_SIZE.
  3933. */
  3934. int64_t bdrv_getlength(BlockDriverState *bs)
  3935. {
  3936. int64_t ret = bdrv_nb_sectors(bs);
  3937. ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
  3938. return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
  3939. }
  3940. /* return 0 as number of sectors if no device present or error */
  3941. void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
  3942. {
  3943. int64_t nb_sectors = bdrv_nb_sectors(bs);
  3944. *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
  3945. }
  3946. bool bdrv_is_sg(BlockDriverState *bs)
  3947. {
  3948. return bs->sg;
  3949. }
  3950. bool bdrv_is_encrypted(BlockDriverState *bs)
  3951. {
  3952. if (bs->backing && bs->backing->bs->encrypted) {
  3953. return true;
  3954. }
  3955. return bs->encrypted;
  3956. }
  3957. const char *bdrv_get_format_name(BlockDriverState *bs)
  3958. {
  3959. return bs->drv ? bs->drv->format_name : NULL;
  3960. }
  3961. static int qsort_strcmp(const void *a, const void *b)
  3962. {
  3963. return strcmp(*(char *const *)a, *(char *const *)b);
  3964. }
  3965. void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
  3966. void *opaque, bool read_only)
  3967. {
  3968. BlockDriver *drv;
  3969. int count = 0;
  3970. int i;
  3971. const char **formats = NULL;
  3972. QLIST_FOREACH(drv, &bdrv_drivers, list) {
  3973. if (drv->format_name) {
  3974. bool found = false;
  3975. int i = count;
  3976. if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
  3977. continue;
  3978. }
  3979. while (formats && i && !found) {
  3980. found = !strcmp(formats[--i], drv->format_name);
  3981. }
  3982. if (!found) {
  3983. formats = g_renew(const char *, formats, count + 1);
  3984. formats[count++] = drv->format_name;
  3985. }
  3986. }
  3987. }
  3988. for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
  3989. const char *format_name = block_driver_modules[i].format_name;
  3990. if (format_name) {
  3991. bool found = false;
  3992. int j = count;
  3993. if (use_bdrv_whitelist &&
  3994. !bdrv_format_is_whitelisted(format_name, read_only)) {
  3995. continue;
  3996. }
  3997. while (formats && j && !found) {
  3998. found = !strcmp(formats[--j], format_name);
  3999. }
  4000. if (!found) {
  4001. formats = g_renew(const char *, formats, count + 1);
  4002. formats[count++] = format_name;
  4003. }
  4004. }
  4005. }
  4006. qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
  4007. for (i = 0; i < count; i++) {
  4008. it(opaque, formats[i]);
  4009. }
  4010. g_free(formats);
  4011. }
  4012. /* This function is to find a node in the bs graph */
  4013. BlockDriverState *bdrv_find_node(const char *node_name)
  4014. {
  4015. BlockDriverState *bs;
  4016. assert(node_name);
  4017. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  4018. if (!strcmp(node_name, bs->node_name)) {
  4019. return bs;
  4020. }
  4021. }
  4022. return NULL;
  4023. }
  4024. /* Put this QMP function here so it can access the static graph_bdrv_states. */
  4025. BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
  4026. {
  4027. BlockDeviceInfoList *list, *entry;
  4028. BlockDriverState *bs;
  4029. list = NULL;
  4030. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  4031. BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
  4032. if (!info) {
  4033. qapi_free_BlockDeviceInfoList(list);
  4034. return NULL;
  4035. }
  4036. entry = g_malloc0(sizeof(*entry));
  4037. entry->value = info;
  4038. entry->next = list;
  4039. list = entry;
  4040. }
  4041. return list;
  4042. }
  4043. #define QAPI_LIST_ADD(list, element) do { \
  4044. typeof(list) _tmp = g_new(typeof(*(list)), 1); \
  4045. _tmp->value = (element); \
  4046. _tmp->next = (list); \
  4047. (list) = _tmp; \
  4048. } while (0)
  4049. typedef struct XDbgBlockGraphConstructor {
  4050. XDbgBlockGraph *graph;
  4051. GHashTable *graph_nodes;
  4052. } XDbgBlockGraphConstructor;
  4053. static XDbgBlockGraphConstructor *xdbg_graph_new(void)
  4054. {
  4055. XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
  4056. gr->graph = g_new0(XDbgBlockGraph, 1);
  4057. gr->graph_nodes = g_hash_table_new(NULL, NULL);
  4058. return gr;
  4059. }
  4060. static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
  4061. {
  4062. XDbgBlockGraph *graph = gr->graph;
  4063. g_hash_table_destroy(gr->graph_nodes);
  4064. g_free(gr);
  4065. return graph;
  4066. }
  4067. static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
  4068. {
  4069. uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
  4070. if (ret != 0) {
  4071. return ret;
  4072. }
  4073. /*
  4074. * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
  4075. * answer of g_hash_table_lookup.
  4076. */
  4077. ret = g_hash_table_size(gr->graph_nodes) + 1;
  4078. g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
  4079. return ret;
  4080. }
  4081. static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
  4082. XDbgBlockGraphNodeType type, const char *name)
  4083. {
  4084. XDbgBlockGraphNode *n;
  4085. n = g_new0(XDbgBlockGraphNode, 1);
  4086. n->id = xdbg_graph_node_num(gr, node);
  4087. n->type = type;
  4088. n->name = g_strdup(name);
  4089. QAPI_LIST_ADD(gr->graph->nodes, n);
  4090. }
  4091. static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
  4092. const BdrvChild *child)
  4093. {
  4094. typedef struct {
  4095. unsigned int flag;
  4096. BlockPermission num;
  4097. } PermissionMap;
  4098. static const PermissionMap permissions[] = {
  4099. { BLK_PERM_CONSISTENT_READ, BLOCK_PERMISSION_CONSISTENT_READ },
  4100. { BLK_PERM_WRITE, BLOCK_PERMISSION_WRITE },
  4101. { BLK_PERM_WRITE_UNCHANGED, BLOCK_PERMISSION_WRITE_UNCHANGED },
  4102. { BLK_PERM_RESIZE, BLOCK_PERMISSION_RESIZE },
  4103. { BLK_PERM_GRAPH_MOD, BLOCK_PERMISSION_GRAPH_MOD },
  4104. { 0, 0 }
  4105. };
  4106. const PermissionMap *p;
  4107. XDbgBlockGraphEdge *edge;
  4108. QEMU_BUILD_BUG_ON(1UL << (ARRAY_SIZE(permissions) - 1) != BLK_PERM_ALL + 1);
  4109. edge = g_new0(XDbgBlockGraphEdge, 1);
  4110. edge->parent = xdbg_graph_node_num(gr, parent);
  4111. edge->child = xdbg_graph_node_num(gr, child->bs);
  4112. edge->name = g_strdup(child->name);
  4113. for (p = permissions; p->flag; p++) {
  4114. if (p->flag & child->perm) {
  4115. QAPI_LIST_ADD(edge->perm, p->num);
  4116. }
  4117. if (p->flag & child->shared_perm) {
  4118. QAPI_LIST_ADD(edge->shared_perm, p->num);
  4119. }
  4120. }
  4121. QAPI_LIST_ADD(gr->graph->edges, edge);
  4122. }
  4123. XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
  4124. {
  4125. BlockBackend *blk;
  4126. BlockJob *job;
  4127. BlockDriverState *bs;
  4128. BdrvChild *child;
  4129. XDbgBlockGraphConstructor *gr = xdbg_graph_new();
  4130. for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
  4131. char *allocated_name = NULL;
  4132. const char *name = blk_name(blk);
  4133. if (!*name) {
  4134. name = allocated_name = blk_get_attached_dev_id(blk);
  4135. }
  4136. xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
  4137. name);
  4138. g_free(allocated_name);
  4139. if (blk_root(blk)) {
  4140. xdbg_graph_add_edge(gr, blk, blk_root(blk));
  4141. }
  4142. }
  4143. for (job = block_job_next(NULL); job; job = block_job_next(job)) {
  4144. GSList *el;
  4145. xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
  4146. job->job.id);
  4147. for (el = job->nodes; el; el = el->next) {
  4148. xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
  4149. }
  4150. }
  4151. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  4152. xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
  4153. bs->node_name);
  4154. QLIST_FOREACH(child, &bs->children, next) {
  4155. xdbg_graph_add_edge(gr, bs, child);
  4156. }
  4157. }
  4158. return xdbg_graph_finalize(gr);
  4159. }
  4160. BlockDriverState *bdrv_lookup_bs(const char *device,
  4161. const char *node_name,
  4162. Error **errp)
  4163. {
  4164. BlockBackend *blk;
  4165. BlockDriverState *bs;
  4166. if (device) {
  4167. blk = blk_by_name(device);
  4168. if (blk) {
  4169. bs = blk_bs(blk);
  4170. if (!bs) {
  4171. error_setg(errp, "Device '%s' has no medium", device);
  4172. }
  4173. return bs;
  4174. }
  4175. }
  4176. if (node_name) {
  4177. bs = bdrv_find_node(node_name);
  4178. if (bs) {
  4179. return bs;
  4180. }
  4181. }
  4182. error_setg(errp, "Cannot find device=%s nor node_name=%s",
  4183. device ? device : "",
  4184. node_name ? node_name : "");
  4185. return NULL;
  4186. }
  4187. /* If 'base' is in the same chain as 'top', return true. Otherwise,
  4188. * return false. If either argument is NULL, return false. */
  4189. bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
  4190. {
  4191. while (top && top != base) {
  4192. top = backing_bs(top);
  4193. }
  4194. return top != NULL;
  4195. }
  4196. BlockDriverState *bdrv_next_node(BlockDriverState *bs)
  4197. {
  4198. if (!bs) {
  4199. return QTAILQ_FIRST(&graph_bdrv_states);
  4200. }
  4201. return QTAILQ_NEXT(bs, node_list);
  4202. }
  4203. BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
  4204. {
  4205. if (!bs) {
  4206. return QTAILQ_FIRST(&all_bdrv_states);
  4207. }
  4208. return QTAILQ_NEXT(bs, bs_list);
  4209. }
  4210. const char *bdrv_get_node_name(const BlockDriverState *bs)
  4211. {
  4212. return bs->node_name;
  4213. }
  4214. const char *bdrv_get_parent_name(const BlockDriverState *bs)
  4215. {
  4216. BdrvChild *c;
  4217. const char *name;
  4218. /* If multiple parents have a name, just pick the first one. */
  4219. QLIST_FOREACH(c, &bs->parents, next_parent) {
  4220. if (c->role->get_name) {
  4221. name = c->role->get_name(c);
  4222. if (name && *name) {
  4223. return name;
  4224. }
  4225. }
  4226. }
  4227. return NULL;
  4228. }
  4229. /* TODO check what callers really want: bs->node_name or blk_name() */
  4230. const char *bdrv_get_device_name(const BlockDriverState *bs)
  4231. {
  4232. return bdrv_get_parent_name(bs) ?: "";
  4233. }
  4234. /* This can be used to identify nodes that might not have a device
  4235. * name associated. Since node and device names live in the same
  4236. * namespace, the result is unambiguous. The exception is if both are
  4237. * absent, then this returns an empty (non-null) string. */
  4238. const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
  4239. {
  4240. return bdrv_get_parent_name(bs) ?: bs->node_name;
  4241. }
  4242. int bdrv_get_flags(BlockDriverState *bs)
  4243. {
  4244. return bs->open_flags;
  4245. }
  4246. int bdrv_has_zero_init_1(BlockDriverState *bs)
  4247. {
  4248. return 1;
  4249. }
  4250. int bdrv_has_zero_init(BlockDriverState *bs)
  4251. {
  4252. if (!bs->drv) {
  4253. return 0;
  4254. }
  4255. /* If BS is a copy on write image, it is initialized to
  4256. the contents of the base image, which may not be zeroes. */
  4257. if (bs->backing) {
  4258. return 0;
  4259. }
  4260. if (bs->drv->bdrv_has_zero_init) {
  4261. return bs->drv->bdrv_has_zero_init(bs);
  4262. }
  4263. if (bs->file && bs->drv->is_filter) {
  4264. return bdrv_has_zero_init(bs->file->bs);
  4265. }
  4266. /* safe default */
  4267. return 0;
  4268. }
  4269. bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
  4270. {
  4271. BlockDriverInfo bdi;
  4272. if (bs->backing) {
  4273. return false;
  4274. }
  4275. if (bdrv_get_info(bs, &bdi) == 0) {
  4276. return bdi.unallocated_blocks_are_zero;
  4277. }
  4278. return false;
  4279. }
  4280. bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
  4281. {
  4282. if (!(bs->open_flags & BDRV_O_UNMAP)) {
  4283. return false;
  4284. }
  4285. return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
  4286. }
  4287. void bdrv_get_backing_filename(BlockDriverState *bs,
  4288. char *filename, int filename_size)
  4289. {
  4290. pstrcpy(filename, filename_size, bs->backing_file);
  4291. }
  4292. int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
  4293. {
  4294. BlockDriver *drv = bs->drv;
  4295. /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
  4296. if (!drv) {
  4297. return -ENOMEDIUM;
  4298. }
  4299. if (!drv->bdrv_get_info) {
  4300. if (bs->file && drv->is_filter) {
  4301. return bdrv_get_info(bs->file->bs, bdi);
  4302. }
  4303. return -ENOTSUP;
  4304. }
  4305. memset(bdi, 0, sizeof(*bdi));
  4306. return drv->bdrv_get_info(bs, bdi);
  4307. }
  4308. ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
  4309. Error **errp)
  4310. {
  4311. BlockDriver *drv = bs->drv;
  4312. if (drv && drv->bdrv_get_specific_info) {
  4313. return drv->bdrv_get_specific_info(bs, errp);
  4314. }
  4315. return NULL;
  4316. }
  4317. void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
  4318. {
  4319. if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
  4320. return;
  4321. }
  4322. bs->drv->bdrv_debug_event(bs, event);
  4323. }
  4324. int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
  4325. const char *tag)
  4326. {
  4327. while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
  4328. bs = bs->file ? bs->file->bs : NULL;
  4329. }
  4330. if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
  4331. return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
  4332. }
  4333. return -ENOTSUP;
  4334. }
  4335. int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
  4336. {
  4337. while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
  4338. bs = bs->file ? bs->file->bs : NULL;
  4339. }
  4340. if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
  4341. return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
  4342. }
  4343. return -ENOTSUP;
  4344. }
  4345. int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
  4346. {
  4347. while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
  4348. bs = bs->file ? bs->file->bs : NULL;
  4349. }
  4350. if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
  4351. return bs->drv->bdrv_debug_resume(bs, tag);
  4352. }
  4353. return -ENOTSUP;
  4354. }
  4355. bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
  4356. {
  4357. while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
  4358. bs = bs->file ? bs->file->bs : NULL;
  4359. }
  4360. if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
  4361. return bs->drv->bdrv_debug_is_suspended(bs, tag);
  4362. }
  4363. return false;
  4364. }
  4365. /* backing_file can either be relative, or absolute, or a protocol. If it is
  4366. * relative, it must be relative to the chain. So, passing in bs->filename
  4367. * from a BDS as backing_file should not be done, as that may be relative to
  4368. * the CWD rather than the chain. */
  4369. BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
  4370. const char *backing_file)
  4371. {
  4372. char *filename_full = NULL;
  4373. char *backing_file_full = NULL;
  4374. char *filename_tmp = NULL;
  4375. int is_protocol = 0;
  4376. BlockDriverState *curr_bs = NULL;
  4377. BlockDriverState *retval = NULL;
  4378. if (!bs || !bs->drv || !backing_file) {
  4379. return NULL;
  4380. }
  4381. filename_full = g_malloc(PATH_MAX);
  4382. backing_file_full = g_malloc(PATH_MAX);
  4383. is_protocol = path_has_protocol(backing_file);
  4384. for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
  4385. /* If either of the filename paths is actually a protocol, then
  4386. * compare unmodified paths; otherwise make paths relative */
  4387. if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
  4388. char *backing_file_full_ret;
  4389. if (strcmp(backing_file, curr_bs->backing_file) == 0) {
  4390. retval = curr_bs->backing->bs;
  4391. break;
  4392. }
  4393. /* Also check against the full backing filename for the image */
  4394. backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
  4395. NULL);
  4396. if (backing_file_full_ret) {
  4397. bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
  4398. g_free(backing_file_full_ret);
  4399. if (equal) {
  4400. retval = curr_bs->backing->bs;
  4401. break;
  4402. }
  4403. }
  4404. } else {
  4405. /* If not an absolute filename path, make it relative to the current
  4406. * image's filename path */
  4407. filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
  4408. NULL);
  4409. /* We are going to compare canonicalized absolute pathnames */
  4410. if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
  4411. g_free(filename_tmp);
  4412. continue;
  4413. }
  4414. g_free(filename_tmp);
  4415. /* We need to make sure the backing filename we are comparing against
  4416. * is relative to the current image filename (or absolute) */
  4417. filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
  4418. if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
  4419. g_free(filename_tmp);
  4420. continue;
  4421. }
  4422. g_free(filename_tmp);
  4423. if (strcmp(backing_file_full, filename_full) == 0) {
  4424. retval = curr_bs->backing->bs;
  4425. break;
  4426. }
  4427. }
  4428. }
  4429. g_free(filename_full);
  4430. g_free(backing_file_full);
  4431. return retval;
  4432. }
  4433. void bdrv_init(void)
  4434. {
  4435. module_call_init(MODULE_INIT_BLOCK);
  4436. }
  4437. void bdrv_init_with_whitelist(void)
  4438. {
  4439. use_bdrv_whitelist = 1;
  4440. bdrv_init();
  4441. }
  4442. static void coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs,
  4443. Error **errp)
  4444. {
  4445. BdrvChild *child, *parent;
  4446. uint64_t perm, shared_perm;
  4447. Error *local_err = NULL;
  4448. int ret;
  4449. BdrvDirtyBitmap *bm;
  4450. if (!bs->drv) {
  4451. return;
  4452. }
  4453. if (!(bs->open_flags & BDRV_O_INACTIVE)) {
  4454. return;
  4455. }
  4456. QLIST_FOREACH(child, &bs->children, next) {
  4457. bdrv_co_invalidate_cache(child->bs, &local_err);
  4458. if (local_err) {
  4459. error_propagate(errp, local_err);
  4460. return;
  4461. }
  4462. }
  4463. /*
  4464. * Update permissions, they may differ for inactive nodes.
  4465. *
  4466. * Note that the required permissions of inactive images are always a
  4467. * subset of the permissions required after activating the image. This
  4468. * allows us to just get the permissions upfront without restricting
  4469. * drv->bdrv_invalidate_cache().
  4470. *
  4471. * It also means that in error cases, we don't have to try and revert to
  4472. * the old permissions (which is an operation that could fail, too). We can
  4473. * just keep the extended permissions for the next time that an activation
  4474. * of the image is tried.
  4475. */
  4476. bs->open_flags &= ~BDRV_O_INACTIVE;
  4477. bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
  4478. ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, &local_err);
  4479. if (ret < 0) {
  4480. bs->open_flags |= BDRV_O_INACTIVE;
  4481. error_propagate(errp, local_err);
  4482. return;
  4483. }
  4484. bdrv_set_perm(bs, perm, shared_perm);
  4485. if (bs->drv->bdrv_co_invalidate_cache) {
  4486. bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
  4487. if (local_err) {
  4488. bs->open_flags |= BDRV_O_INACTIVE;
  4489. error_propagate(errp, local_err);
  4490. return;
  4491. }
  4492. }
  4493. for (bm = bdrv_dirty_bitmap_next(bs, NULL); bm;
  4494. bm = bdrv_dirty_bitmap_next(bs, bm))
  4495. {
  4496. bdrv_dirty_bitmap_set_migration(bm, false);
  4497. }
  4498. ret = refresh_total_sectors(bs, bs->total_sectors);
  4499. if (ret < 0) {
  4500. bs->open_flags |= BDRV_O_INACTIVE;
  4501. error_setg_errno(errp, -ret, "Could not refresh total sector count");
  4502. return;
  4503. }
  4504. QLIST_FOREACH(parent, &bs->parents, next_parent) {
  4505. if (parent->role->activate) {
  4506. parent->role->activate(parent, &local_err);
  4507. if (local_err) {
  4508. bs->open_flags |= BDRV_O_INACTIVE;
  4509. error_propagate(errp, local_err);
  4510. return;
  4511. }
  4512. }
  4513. }
  4514. }
  4515. typedef struct InvalidateCacheCo {
  4516. BlockDriverState *bs;
  4517. Error **errp;
  4518. bool done;
  4519. } InvalidateCacheCo;
  4520. static void coroutine_fn bdrv_invalidate_cache_co_entry(void *opaque)
  4521. {
  4522. InvalidateCacheCo *ico = opaque;
  4523. bdrv_co_invalidate_cache(ico->bs, ico->errp);
  4524. ico->done = true;
  4525. aio_wait_kick();
  4526. }
  4527. void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
  4528. {
  4529. Coroutine *co;
  4530. InvalidateCacheCo ico = {
  4531. .bs = bs,
  4532. .done = false,
  4533. .errp = errp
  4534. };
  4535. if (qemu_in_coroutine()) {
  4536. /* Fast-path if already in coroutine context */
  4537. bdrv_invalidate_cache_co_entry(&ico);
  4538. } else {
  4539. co = qemu_coroutine_create(bdrv_invalidate_cache_co_entry, &ico);
  4540. bdrv_coroutine_enter(bs, co);
  4541. BDRV_POLL_WHILE(bs, !ico.done);
  4542. }
  4543. }
  4544. void bdrv_invalidate_cache_all(Error **errp)
  4545. {
  4546. BlockDriverState *bs;
  4547. Error *local_err = NULL;
  4548. BdrvNextIterator it;
  4549. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  4550. AioContext *aio_context = bdrv_get_aio_context(bs);
  4551. aio_context_acquire(aio_context);
  4552. bdrv_invalidate_cache(bs, &local_err);
  4553. aio_context_release(aio_context);
  4554. if (local_err) {
  4555. error_propagate(errp, local_err);
  4556. bdrv_next_cleanup(&it);
  4557. return;
  4558. }
  4559. }
  4560. }
  4561. static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
  4562. {
  4563. BdrvChild *parent;
  4564. QLIST_FOREACH(parent, &bs->parents, next_parent) {
  4565. if (parent->role->parent_is_bds) {
  4566. BlockDriverState *parent_bs = parent->opaque;
  4567. if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
  4568. return true;
  4569. }
  4570. }
  4571. }
  4572. return false;
  4573. }
  4574. static int bdrv_inactivate_recurse(BlockDriverState *bs)
  4575. {
  4576. BdrvChild *child, *parent;
  4577. uint64_t perm, shared_perm;
  4578. int ret;
  4579. if (!bs->drv) {
  4580. return -ENOMEDIUM;
  4581. }
  4582. /* Make sure that we don't inactivate a child before its parent.
  4583. * It will be covered by recursion from the yet active parent. */
  4584. if (bdrv_has_bds_parent(bs, true)) {
  4585. return 0;
  4586. }
  4587. assert(!(bs->open_flags & BDRV_O_INACTIVE));
  4588. /* Inactivate this node */
  4589. if (bs->drv->bdrv_inactivate) {
  4590. ret = bs->drv->bdrv_inactivate(bs);
  4591. if (ret < 0) {
  4592. return ret;
  4593. }
  4594. }
  4595. QLIST_FOREACH(parent, &bs->parents, next_parent) {
  4596. if (parent->role->inactivate) {
  4597. ret = parent->role->inactivate(parent);
  4598. if (ret < 0) {
  4599. return ret;
  4600. }
  4601. }
  4602. }
  4603. bs->open_flags |= BDRV_O_INACTIVE;
  4604. /* Update permissions, they may differ for inactive nodes */
  4605. bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
  4606. bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, &error_abort);
  4607. bdrv_set_perm(bs, perm, shared_perm);
  4608. /* Recursively inactivate children */
  4609. QLIST_FOREACH(child, &bs->children, next) {
  4610. ret = bdrv_inactivate_recurse(child->bs);
  4611. if (ret < 0) {
  4612. return ret;
  4613. }
  4614. }
  4615. return 0;
  4616. }
  4617. int bdrv_inactivate_all(void)
  4618. {
  4619. BlockDriverState *bs = NULL;
  4620. BdrvNextIterator it;
  4621. int ret = 0;
  4622. GSList *aio_ctxs = NULL, *ctx;
  4623. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  4624. AioContext *aio_context = bdrv_get_aio_context(bs);
  4625. if (!g_slist_find(aio_ctxs, aio_context)) {
  4626. aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
  4627. aio_context_acquire(aio_context);
  4628. }
  4629. }
  4630. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  4631. /* Nodes with BDS parents are covered by recursion from the last
  4632. * parent that gets inactivated. Don't inactivate them a second
  4633. * time if that has already happened. */
  4634. if (bdrv_has_bds_parent(bs, false)) {
  4635. continue;
  4636. }
  4637. ret = bdrv_inactivate_recurse(bs);
  4638. if (ret < 0) {
  4639. bdrv_next_cleanup(&it);
  4640. goto out;
  4641. }
  4642. }
  4643. out:
  4644. for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
  4645. AioContext *aio_context = ctx->data;
  4646. aio_context_release(aio_context);
  4647. }
  4648. g_slist_free(aio_ctxs);
  4649. return ret;
  4650. }
  4651. /**************************************************************/
  4652. /* removable device support */
  4653. /**
  4654. * Return TRUE if the media is present
  4655. */
  4656. bool bdrv_is_inserted(BlockDriverState *bs)
  4657. {
  4658. BlockDriver *drv = bs->drv;
  4659. BdrvChild *child;
  4660. if (!drv) {
  4661. return false;
  4662. }
  4663. if (drv->bdrv_is_inserted) {
  4664. return drv->bdrv_is_inserted(bs);
  4665. }
  4666. QLIST_FOREACH(child, &bs->children, next) {
  4667. if (!bdrv_is_inserted(child->bs)) {
  4668. return false;
  4669. }
  4670. }
  4671. return true;
  4672. }
  4673. /**
  4674. * If eject_flag is TRUE, eject the media. Otherwise, close the tray
  4675. */
  4676. void bdrv_eject(BlockDriverState *bs, bool eject_flag)
  4677. {
  4678. BlockDriver *drv = bs->drv;
  4679. if (drv && drv->bdrv_eject) {
  4680. drv->bdrv_eject(bs, eject_flag);
  4681. }
  4682. }
  4683. /**
  4684. * Lock or unlock the media (if it is locked, the user won't be able
  4685. * to eject it manually).
  4686. */
  4687. void bdrv_lock_medium(BlockDriverState *bs, bool locked)
  4688. {
  4689. BlockDriver *drv = bs->drv;
  4690. trace_bdrv_lock_medium(bs, locked);
  4691. if (drv && drv->bdrv_lock_medium) {
  4692. drv->bdrv_lock_medium(bs, locked);
  4693. }
  4694. }
  4695. /* Get a reference to bs */
  4696. void bdrv_ref(BlockDriverState *bs)
  4697. {
  4698. bs->refcnt++;
  4699. }
  4700. /* Release a previously grabbed reference to bs.
  4701. * If after releasing, reference count is zero, the BlockDriverState is
  4702. * deleted. */
  4703. void bdrv_unref(BlockDriverState *bs)
  4704. {
  4705. if (!bs) {
  4706. return;
  4707. }
  4708. assert(bs->refcnt > 0);
  4709. if (--bs->refcnt == 0) {
  4710. bdrv_delete(bs);
  4711. }
  4712. }
  4713. struct BdrvOpBlocker {
  4714. Error *reason;
  4715. QLIST_ENTRY(BdrvOpBlocker) list;
  4716. };
  4717. bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
  4718. {
  4719. BdrvOpBlocker *blocker;
  4720. assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
  4721. if (!QLIST_EMPTY(&bs->op_blockers[op])) {
  4722. blocker = QLIST_FIRST(&bs->op_blockers[op]);
  4723. error_propagate_prepend(errp, error_copy(blocker->reason),
  4724. "Node '%s' is busy: ",
  4725. bdrv_get_device_or_node_name(bs));
  4726. return true;
  4727. }
  4728. return false;
  4729. }
  4730. void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
  4731. {
  4732. BdrvOpBlocker *blocker;
  4733. assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
  4734. blocker = g_new0(BdrvOpBlocker, 1);
  4735. blocker->reason = reason;
  4736. QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
  4737. }
  4738. void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
  4739. {
  4740. BdrvOpBlocker *blocker, *next;
  4741. assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
  4742. QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
  4743. if (blocker->reason == reason) {
  4744. QLIST_REMOVE(blocker, list);
  4745. g_free(blocker);
  4746. }
  4747. }
  4748. }
  4749. void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
  4750. {
  4751. int i;
  4752. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  4753. bdrv_op_block(bs, i, reason);
  4754. }
  4755. }
  4756. void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
  4757. {
  4758. int i;
  4759. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  4760. bdrv_op_unblock(bs, i, reason);
  4761. }
  4762. }
  4763. bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
  4764. {
  4765. int i;
  4766. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  4767. if (!QLIST_EMPTY(&bs->op_blockers[i])) {
  4768. return false;
  4769. }
  4770. }
  4771. return true;
  4772. }
  4773. void bdrv_img_create(const char *filename, const char *fmt,
  4774. const char *base_filename, const char *base_fmt,
  4775. char *options, uint64_t img_size, int flags, bool quiet,
  4776. Error **errp)
  4777. {
  4778. QemuOptsList *create_opts = NULL;
  4779. QemuOpts *opts = NULL;
  4780. const char *backing_fmt, *backing_file;
  4781. int64_t size;
  4782. BlockDriver *drv, *proto_drv;
  4783. Error *local_err = NULL;
  4784. int ret = 0;
  4785. /* Find driver and parse its options */
  4786. drv = bdrv_find_format(fmt);
  4787. if (!drv) {
  4788. error_setg(errp, "Unknown file format '%s'", fmt);
  4789. return;
  4790. }
  4791. proto_drv = bdrv_find_protocol(filename, true, errp);
  4792. if (!proto_drv) {
  4793. return;
  4794. }
  4795. if (!drv->create_opts) {
  4796. error_setg(errp, "Format driver '%s' does not support image creation",
  4797. drv->format_name);
  4798. return;
  4799. }
  4800. if (!proto_drv->create_opts) {
  4801. error_setg(errp, "Protocol driver '%s' does not support image creation",
  4802. proto_drv->format_name);
  4803. return;
  4804. }
  4805. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  4806. create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
  4807. /* Create parameter list with default values */
  4808. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  4809. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
  4810. /* Parse -o options */
  4811. if (options) {
  4812. qemu_opts_do_parse(opts, options, NULL, &local_err);
  4813. if (local_err) {
  4814. goto out;
  4815. }
  4816. }
  4817. if (base_filename) {
  4818. qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
  4819. if (local_err) {
  4820. error_setg(errp, "Backing file not supported for file format '%s'",
  4821. fmt);
  4822. goto out;
  4823. }
  4824. }
  4825. if (base_fmt) {
  4826. qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
  4827. if (local_err) {
  4828. error_setg(errp, "Backing file format not supported for file "
  4829. "format '%s'", fmt);
  4830. goto out;
  4831. }
  4832. }
  4833. backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
  4834. if (backing_file) {
  4835. if (!strcmp(filename, backing_file)) {
  4836. error_setg(errp, "Error: Trying to create an image with the "
  4837. "same filename as the backing file");
  4838. goto out;
  4839. }
  4840. }
  4841. backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
  4842. /* The size for the image must always be specified, unless we have a backing
  4843. * file and we have not been forbidden from opening it. */
  4844. size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
  4845. if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
  4846. BlockDriverState *bs;
  4847. char *full_backing;
  4848. int back_flags;
  4849. QDict *backing_options = NULL;
  4850. full_backing =
  4851. bdrv_get_full_backing_filename_from_filename(filename, backing_file,
  4852. &local_err);
  4853. if (local_err) {
  4854. goto out;
  4855. }
  4856. assert(full_backing);
  4857. /* backing files always opened read-only */
  4858. back_flags = flags;
  4859. back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
  4860. backing_options = qdict_new();
  4861. if (backing_fmt) {
  4862. qdict_put_str(backing_options, "driver", backing_fmt);
  4863. }
  4864. qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
  4865. bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
  4866. &local_err);
  4867. g_free(full_backing);
  4868. if (!bs && size != -1) {
  4869. /* Couldn't open BS, but we have a size, so it's nonfatal */
  4870. warn_reportf_err(local_err,
  4871. "Could not verify backing image. "
  4872. "This may become an error in future versions.\n");
  4873. local_err = NULL;
  4874. } else if (!bs) {
  4875. /* Couldn't open bs, do not have size */
  4876. error_append_hint(&local_err,
  4877. "Could not open backing image to determine size.\n");
  4878. goto out;
  4879. } else {
  4880. if (size == -1) {
  4881. /* Opened BS, have no size */
  4882. size = bdrv_getlength(bs);
  4883. if (size < 0) {
  4884. error_setg_errno(errp, -size, "Could not get size of '%s'",
  4885. backing_file);
  4886. bdrv_unref(bs);
  4887. goto out;
  4888. }
  4889. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
  4890. }
  4891. bdrv_unref(bs);
  4892. }
  4893. } /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
  4894. if (size == -1) {
  4895. error_setg(errp, "Image creation needs a size parameter");
  4896. goto out;
  4897. }
  4898. if (!quiet) {
  4899. printf("Formatting '%s', fmt=%s ", filename, fmt);
  4900. qemu_opts_print(opts, " ");
  4901. puts("");
  4902. }
  4903. ret = bdrv_create(drv, filename, opts, &local_err);
  4904. if (ret == -EFBIG) {
  4905. /* This is generally a better message than whatever the driver would
  4906. * deliver (especially because of the cluster_size_hint), since that
  4907. * is most probably not much different from "image too large". */
  4908. const char *cluster_size_hint = "";
  4909. if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
  4910. cluster_size_hint = " (try using a larger cluster size)";
  4911. }
  4912. error_setg(errp, "The image size is too large for file format '%s'"
  4913. "%s", fmt, cluster_size_hint);
  4914. error_free(local_err);
  4915. local_err = NULL;
  4916. }
  4917. out:
  4918. qemu_opts_del(opts);
  4919. qemu_opts_free(create_opts);
  4920. error_propagate(errp, local_err);
  4921. }
  4922. AioContext *bdrv_get_aio_context(BlockDriverState *bs)
  4923. {
  4924. return bs ? bs->aio_context : qemu_get_aio_context();
  4925. }
  4926. void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
  4927. {
  4928. aio_co_enter(bdrv_get_aio_context(bs), co);
  4929. }
  4930. static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
  4931. {
  4932. QLIST_REMOVE(ban, list);
  4933. g_free(ban);
  4934. }
  4935. static void bdrv_detach_aio_context(BlockDriverState *bs)
  4936. {
  4937. BdrvAioNotifier *baf, *baf_tmp;
  4938. assert(!bs->walking_aio_notifiers);
  4939. bs->walking_aio_notifiers = true;
  4940. QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
  4941. if (baf->deleted) {
  4942. bdrv_do_remove_aio_context_notifier(baf);
  4943. } else {
  4944. baf->detach_aio_context(baf->opaque);
  4945. }
  4946. }
  4947. /* Never mind iterating again to check for ->deleted. bdrv_close() will
  4948. * remove remaining aio notifiers if we aren't called again.
  4949. */
  4950. bs->walking_aio_notifiers = false;
  4951. if (bs->drv && bs->drv->bdrv_detach_aio_context) {
  4952. bs->drv->bdrv_detach_aio_context(bs);
  4953. }
  4954. if (bs->quiesce_counter) {
  4955. aio_enable_external(bs->aio_context);
  4956. }
  4957. bs->aio_context = NULL;
  4958. }
  4959. static void bdrv_attach_aio_context(BlockDriverState *bs,
  4960. AioContext *new_context)
  4961. {
  4962. BdrvAioNotifier *ban, *ban_tmp;
  4963. if (bs->quiesce_counter) {
  4964. aio_disable_external(new_context);
  4965. }
  4966. bs->aio_context = new_context;
  4967. if (bs->drv && bs->drv->bdrv_attach_aio_context) {
  4968. bs->drv->bdrv_attach_aio_context(bs, new_context);
  4969. }
  4970. assert(!bs->walking_aio_notifiers);
  4971. bs->walking_aio_notifiers = true;
  4972. QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
  4973. if (ban->deleted) {
  4974. bdrv_do_remove_aio_context_notifier(ban);
  4975. } else {
  4976. ban->attached_aio_context(new_context, ban->opaque);
  4977. }
  4978. }
  4979. bs->walking_aio_notifiers = false;
  4980. }
  4981. /*
  4982. * Changes the AioContext used for fd handlers, timers, and BHs by this
  4983. * BlockDriverState and all its children and parents.
  4984. *
  4985. * The caller must own the AioContext lock for the old AioContext of bs, but it
  4986. * must not own the AioContext lock for new_context (unless new_context is the
  4987. * same as the current context of bs).
  4988. *
  4989. * @ignore will accumulate all visited BdrvChild object. The caller is
  4990. * responsible for freeing the list afterwards.
  4991. */
  4992. void bdrv_set_aio_context_ignore(BlockDriverState *bs,
  4993. AioContext *new_context, GSList **ignore)
  4994. {
  4995. BdrvChild *child;
  4996. if (bdrv_get_aio_context(bs) == new_context) {
  4997. return;
  4998. }
  4999. bdrv_drained_begin(bs);
  5000. QLIST_FOREACH(child, &bs->children, next) {
  5001. if (g_slist_find(*ignore, child)) {
  5002. continue;
  5003. }
  5004. *ignore = g_slist_prepend(*ignore, child);
  5005. bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
  5006. }
  5007. QLIST_FOREACH(child, &bs->parents, next_parent) {
  5008. if (g_slist_find(*ignore, child)) {
  5009. continue;
  5010. }
  5011. assert(child->role->set_aio_ctx);
  5012. *ignore = g_slist_prepend(*ignore, child);
  5013. child->role->set_aio_ctx(child, new_context, ignore);
  5014. }
  5015. bdrv_detach_aio_context(bs);
  5016. /* This function executes in the old AioContext so acquire the new one in
  5017. * case it runs in a different thread.
  5018. */
  5019. aio_context_acquire(new_context);
  5020. bdrv_attach_aio_context(bs, new_context);
  5021. bdrv_drained_end(bs);
  5022. aio_context_release(new_context);
  5023. }
  5024. static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
  5025. GSList **ignore, Error **errp)
  5026. {
  5027. if (g_slist_find(*ignore, c)) {
  5028. return true;
  5029. }
  5030. *ignore = g_slist_prepend(*ignore, c);
  5031. /* A BdrvChildRole that doesn't handle AioContext changes cannot
  5032. * tolerate any AioContext changes */
  5033. if (!c->role->can_set_aio_ctx) {
  5034. char *user = bdrv_child_user_desc(c);
  5035. error_setg(errp, "Changing iothreads is not supported by %s", user);
  5036. g_free(user);
  5037. return false;
  5038. }
  5039. if (!c->role->can_set_aio_ctx(c, ctx, ignore, errp)) {
  5040. assert(!errp || *errp);
  5041. return false;
  5042. }
  5043. return true;
  5044. }
  5045. bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
  5046. GSList **ignore, Error **errp)
  5047. {
  5048. if (g_slist_find(*ignore, c)) {
  5049. return true;
  5050. }
  5051. *ignore = g_slist_prepend(*ignore, c);
  5052. return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
  5053. }
  5054. /* @ignore will accumulate all visited BdrvChild object. The caller is
  5055. * responsible for freeing the list afterwards. */
  5056. bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
  5057. GSList **ignore, Error **errp)
  5058. {
  5059. BdrvChild *c;
  5060. if (bdrv_get_aio_context(bs) == ctx) {
  5061. return true;
  5062. }
  5063. QLIST_FOREACH(c, &bs->parents, next_parent) {
  5064. if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
  5065. return false;
  5066. }
  5067. }
  5068. QLIST_FOREACH(c, &bs->children, next) {
  5069. if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
  5070. return false;
  5071. }
  5072. }
  5073. return true;
  5074. }
  5075. int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
  5076. BdrvChild *ignore_child, Error **errp)
  5077. {
  5078. GSList *ignore;
  5079. bool ret;
  5080. ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
  5081. ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
  5082. g_slist_free(ignore);
  5083. if (!ret) {
  5084. return -EPERM;
  5085. }
  5086. ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
  5087. bdrv_set_aio_context_ignore(bs, ctx, &ignore);
  5088. g_slist_free(ignore);
  5089. return 0;
  5090. }
  5091. int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
  5092. Error **errp)
  5093. {
  5094. return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
  5095. }
  5096. void bdrv_add_aio_context_notifier(BlockDriverState *bs,
  5097. void (*attached_aio_context)(AioContext *new_context, void *opaque),
  5098. void (*detach_aio_context)(void *opaque), void *opaque)
  5099. {
  5100. BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
  5101. *ban = (BdrvAioNotifier){
  5102. .attached_aio_context = attached_aio_context,
  5103. .detach_aio_context = detach_aio_context,
  5104. .opaque = opaque
  5105. };
  5106. QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
  5107. }
  5108. void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
  5109. void (*attached_aio_context)(AioContext *,
  5110. void *),
  5111. void (*detach_aio_context)(void *),
  5112. void *opaque)
  5113. {
  5114. BdrvAioNotifier *ban, *ban_next;
  5115. QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
  5116. if (ban->attached_aio_context == attached_aio_context &&
  5117. ban->detach_aio_context == detach_aio_context &&
  5118. ban->opaque == opaque &&
  5119. ban->deleted == false)
  5120. {
  5121. if (bs->walking_aio_notifiers) {
  5122. ban->deleted = true;
  5123. } else {
  5124. bdrv_do_remove_aio_context_notifier(ban);
  5125. }
  5126. return;
  5127. }
  5128. }
  5129. abort();
  5130. }
  5131. int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
  5132. BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
  5133. Error **errp)
  5134. {
  5135. if (!bs->drv) {
  5136. error_setg(errp, "Node is ejected");
  5137. return -ENOMEDIUM;
  5138. }
  5139. if (!bs->drv->bdrv_amend_options) {
  5140. error_setg(errp, "Block driver '%s' does not support option amendment",
  5141. bs->drv->format_name);
  5142. return -ENOTSUP;
  5143. }
  5144. return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque, errp);
  5145. }
  5146. /* This function will be called by the bdrv_recurse_is_first_non_filter method
  5147. * of block filter and by bdrv_is_first_non_filter.
  5148. * It is used to test if the given bs is the candidate or recurse more in the
  5149. * node graph.
  5150. */
  5151. bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
  5152. BlockDriverState *candidate)
  5153. {
  5154. /* return false if basic checks fails */
  5155. if (!bs || !bs->drv) {
  5156. return false;
  5157. }
  5158. /* the code reached a non block filter driver -> check if the bs is
  5159. * the same as the candidate. It's the recursion termination condition.
  5160. */
  5161. if (!bs->drv->is_filter) {
  5162. return bs == candidate;
  5163. }
  5164. /* Down this path the driver is a block filter driver */
  5165. /* If the block filter recursion method is defined use it to recurse down
  5166. * the node graph.
  5167. */
  5168. if (bs->drv->bdrv_recurse_is_first_non_filter) {
  5169. return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
  5170. }
  5171. /* the driver is a block filter but don't allow to recurse -> return false
  5172. */
  5173. return false;
  5174. }
  5175. /* This function checks if the candidate is the first non filter bs down it's
  5176. * bs chain. Since we don't have pointers to parents it explore all bs chains
  5177. * from the top. Some filters can choose not to pass down the recursion.
  5178. */
  5179. bool bdrv_is_first_non_filter(BlockDriverState *candidate)
  5180. {
  5181. BlockDriverState *bs;
  5182. BdrvNextIterator it;
  5183. /* walk down the bs forest recursively */
  5184. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  5185. bool perm;
  5186. /* try to recurse in this top level bs */
  5187. perm = bdrv_recurse_is_first_non_filter(bs, candidate);
  5188. /* candidate is the first non filter */
  5189. if (perm) {
  5190. bdrv_next_cleanup(&it);
  5191. return true;
  5192. }
  5193. }
  5194. return false;
  5195. }
  5196. BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
  5197. const char *node_name, Error **errp)
  5198. {
  5199. BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
  5200. AioContext *aio_context;
  5201. if (!to_replace_bs) {
  5202. error_setg(errp, "Node name '%s' not found", node_name);
  5203. return NULL;
  5204. }
  5205. aio_context = bdrv_get_aio_context(to_replace_bs);
  5206. aio_context_acquire(aio_context);
  5207. if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
  5208. to_replace_bs = NULL;
  5209. goto out;
  5210. }
  5211. /* We don't want arbitrary node of the BDS chain to be replaced only the top
  5212. * most non filter in order to prevent data corruption.
  5213. * Another benefit is that this tests exclude backing files which are
  5214. * blocked by the backing blockers.
  5215. */
  5216. if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
  5217. error_setg(errp, "Only top most non filter can be replaced");
  5218. to_replace_bs = NULL;
  5219. goto out;
  5220. }
  5221. out:
  5222. aio_context_release(aio_context);
  5223. return to_replace_bs;
  5224. }
  5225. /**
  5226. * Iterates through the list of runtime option keys that are said to
  5227. * be "strong" for a BDS. An option is called "strong" if it changes
  5228. * a BDS's data. For example, the null block driver's "size" and
  5229. * "read-zeroes" options are strong, but its "latency-ns" option is
  5230. * not.
  5231. *
  5232. * If a key returned by this function ends with a dot, all options
  5233. * starting with that prefix are strong.
  5234. */
  5235. static const char *const *strong_options(BlockDriverState *bs,
  5236. const char *const *curopt)
  5237. {
  5238. static const char *const global_options[] = {
  5239. "driver", "filename", NULL
  5240. };
  5241. if (!curopt) {
  5242. return &global_options[0];
  5243. }
  5244. curopt++;
  5245. if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
  5246. curopt = bs->drv->strong_runtime_opts;
  5247. }
  5248. return (curopt && *curopt) ? curopt : NULL;
  5249. }
  5250. /**
  5251. * Copies all strong runtime options from bs->options to the given
  5252. * QDict. The set of strong option keys is determined by invoking
  5253. * strong_options().
  5254. *
  5255. * Returns true iff any strong option was present in bs->options (and
  5256. * thus copied to the target QDict) with the exception of "filename"
  5257. * and "driver". The caller is expected to use this value to decide
  5258. * whether the existence of strong options prevents the generation of
  5259. * a plain filename.
  5260. */
  5261. static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
  5262. {
  5263. bool found_any = false;
  5264. const char *const *option_name = NULL;
  5265. if (!bs->drv) {
  5266. return false;
  5267. }
  5268. while ((option_name = strong_options(bs, option_name))) {
  5269. bool option_given = false;
  5270. assert(strlen(*option_name) > 0);
  5271. if ((*option_name)[strlen(*option_name) - 1] != '.') {
  5272. QObject *entry = qdict_get(bs->options, *option_name);
  5273. if (!entry) {
  5274. continue;
  5275. }
  5276. qdict_put_obj(d, *option_name, qobject_ref(entry));
  5277. option_given = true;
  5278. } else {
  5279. const QDictEntry *entry;
  5280. for (entry = qdict_first(bs->options); entry;
  5281. entry = qdict_next(bs->options, entry))
  5282. {
  5283. if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
  5284. qdict_put_obj(d, qdict_entry_key(entry),
  5285. qobject_ref(qdict_entry_value(entry)));
  5286. option_given = true;
  5287. }
  5288. }
  5289. }
  5290. /* While "driver" and "filename" need to be included in a JSON filename,
  5291. * their existence does not prohibit generation of a plain filename. */
  5292. if (!found_any && option_given &&
  5293. strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
  5294. {
  5295. found_any = true;
  5296. }
  5297. }
  5298. if (!qdict_haskey(d, "driver")) {
  5299. /* Drivers created with bdrv_new_open_driver() may not have a
  5300. * @driver option. Add it here. */
  5301. qdict_put_str(d, "driver", bs->drv->format_name);
  5302. }
  5303. return found_any;
  5304. }
  5305. /* Note: This function may return false positives; it may return true
  5306. * even if opening the backing file specified by bs's image header
  5307. * would result in exactly bs->backing. */
  5308. static bool bdrv_backing_overridden(BlockDriverState *bs)
  5309. {
  5310. if (bs->backing) {
  5311. return strcmp(bs->auto_backing_file,
  5312. bs->backing->bs->filename);
  5313. } else {
  5314. /* No backing BDS, so if the image header reports any backing
  5315. * file, it must have been suppressed */
  5316. return bs->auto_backing_file[0] != '\0';
  5317. }
  5318. }
  5319. /* Updates the following BDS fields:
  5320. * - exact_filename: A filename which may be used for opening a block device
  5321. * which (mostly) equals the given BDS (even without any
  5322. * other options; so reading and writing must return the same
  5323. * results, but caching etc. may be different)
  5324. * - full_open_options: Options which, when given when opening a block device
  5325. * (without a filename), result in a BDS (mostly)
  5326. * equalling the given one
  5327. * - filename: If exact_filename is set, it is copied here. Otherwise,
  5328. * full_open_options is converted to a JSON object, prefixed with
  5329. * "json:" (for use through the JSON pseudo protocol) and put here.
  5330. */
  5331. void bdrv_refresh_filename(BlockDriverState *bs)
  5332. {
  5333. BlockDriver *drv = bs->drv;
  5334. BdrvChild *child;
  5335. QDict *opts;
  5336. bool backing_overridden;
  5337. bool generate_json_filename; /* Whether our default implementation should
  5338. fill exact_filename (false) or not (true) */
  5339. if (!drv) {
  5340. return;
  5341. }
  5342. /* This BDS's file name may depend on any of its children's file names, so
  5343. * refresh those first */
  5344. QLIST_FOREACH(child, &bs->children, next) {
  5345. bdrv_refresh_filename(child->bs);
  5346. }
  5347. if (bs->implicit) {
  5348. /* For implicit nodes, just copy everything from the single child */
  5349. child = QLIST_FIRST(&bs->children);
  5350. assert(QLIST_NEXT(child, next) == NULL);
  5351. pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
  5352. child->bs->exact_filename);
  5353. pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
  5354. bs->full_open_options = qobject_ref(child->bs->full_open_options);
  5355. return;
  5356. }
  5357. backing_overridden = bdrv_backing_overridden(bs);
  5358. if (bs->open_flags & BDRV_O_NO_IO) {
  5359. /* Without I/O, the backing file does not change anything.
  5360. * Therefore, in such a case (primarily qemu-img), we can
  5361. * pretend the backing file has not been overridden even if
  5362. * it technically has been. */
  5363. backing_overridden = false;
  5364. }
  5365. /* Gather the options QDict */
  5366. opts = qdict_new();
  5367. generate_json_filename = append_strong_runtime_options(opts, bs);
  5368. generate_json_filename |= backing_overridden;
  5369. if (drv->bdrv_gather_child_options) {
  5370. /* Some block drivers may not want to present all of their children's
  5371. * options, or name them differently from BdrvChild.name */
  5372. drv->bdrv_gather_child_options(bs, opts, backing_overridden);
  5373. } else {
  5374. QLIST_FOREACH(child, &bs->children, next) {
  5375. if (child->role == &child_backing && !backing_overridden) {
  5376. /* We can skip the backing BDS if it has not been overridden */
  5377. continue;
  5378. }
  5379. qdict_put(opts, child->name,
  5380. qobject_ref(child->bs->full_open_options));
  5381. }
  5382. if (backing_overridden && !bs->backing) {
  5383. /* Force no backing file */
  5384. qdict_put_null(opts, "backing");
  5385. }
  5386. }
  5387. qobject_unref(bs->full_open_options);
  5388. bs->full_open_options = opts;
  5389. if (drv->bdrv_refresh_filename) {
  5390. /* Obsolete information is of no use here, so drop the old file name
  5391. * information before refreshing it */
  5392. bs->exact_filename[0] = '\0';
  5393. drv->bdrv_refresh_filename(bs);
  5394. } else if (bs->file) {
  5395. /* Try to reconstruct valid information from the underlying file */
  5396. bs->exact_filename[0] = '\0';
  5397. /*
  5398. * We can use the underlying file's filename if:
  5399. * - it has a filename,
  5400. * - the file is a protocol BDS, and
  5401. * - opening that file (as this BDS's format) will automatically create
  5402. * the BDS tree we have right now, that is:
  5403. * - the user did not significantly change this BDS's behavior with
  5404. * some explicit (strong) options
  5405. * - no non-file child of this BDS has been overridden by the user
  5406. * Both of these conditions are represented by generate_json_filename.
  5407. */
  5408. if (bs->file->bs->exact_filename[0] &&
  5409. bs->file->bs->drv->bdrv_file_open &&
  5410. !generate_json_filename)
  5411. {
  5412. strcpy(bs->exact_filename, bs->file->bs->exact_filename);
  5413. }
  5414. }
  5415. if (bs->exact_filename[0]) {
  5416. pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
  5417. } else {
  5418. QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
  5419. snprintf(bs->filename, sizeof(bs->filename), "json:%s",
  5420. qstring_get_str(json));
  5421. qobject_unref(json);
  5422. }
  5423. }
  5424. char *bdrv_dirname(BlockDriverState *bs, Error **errp)
  5425. {
  5426. BlockDriver *drv = bs->drv;
  5427. if (!drv) {
  5428. error_setg(errp, "Node '%s' is ejected", bs->node_name);
  5429. return NULL;
  5430. }
  5431. if (drv->bdrv_dirname) {
  5432. return drv->bdrv_dirname(bs, errp);
  5433. }
  5434. if (bs->file) {
  5435. return bdrv_dirname(bs->file->bs, errp);
  5436. }
  5437. bdrv_refresh_filename(bs);
  5438. if (bs->exact_filename[0] != '\0') {
  5439. return path_combine(bs->exact_filename, "");
  5440. }
  5441. error_setg(errp, "Cannot generate a base directory for %s nodes",
  5442. drv->format_name);
  5443. return NULL;
  5444. }
  5445. /*
  5446. * Hot add/remove a BDS's child. So the user can take a child offline when
  5447. * it is broken and take a new child online
  5448. */
  5449. void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
  5450. Error **errp)
  5451. {
  5452. if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
  5453. error_setg(errp, "The node %s does not support adding a child",
  5454. bdrv_get_device_or_node_name(parent_bs));
  5455. return;
  5456. }
  5457. if (!QLIST_EMPTY(&child_bs->parents)) {
  5458. error_setg(errp, "The node %s already has a parent",
  5459. child_bs->node_name);
  5460. return;
  5461. }
  5462. parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
  5463. }
  5464. void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
  5465. {
  5466. BdrvChild *tmp;
  5467. if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
  5468. error_setg(errp, "The node %s does not support removing a child",
  5469. bdrv_get_device_or_node_name(parent_bs));
  5470. return;
  5471. }
  5472. QLIST_FOREACH(tmp, &parent_bs->children, next) {
  5473. if (tmp == child) {
  5474. break;
  5475. }
  5476. }
  5477. if (!tmp) {
  5478. error_setg(errp, "The node %s does not have a child named %s",
  5479. bdrv_get_device_or_node_name(parent_bs),
  5480. bdrv_get_device_or_node_name(child->bs));
  5481. return;
  5482. }
  5483. parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
  5484. }
  5485. bool bdrv_can_store_new_dirty_bitmap(BlockDriverState *bs, const char *name,
  5486. uint32_t granularity, Error **errp)
  5487. {
  5488. BlockDriver *drv = bs->drv;
  5489. if (!drv) {
  5490. error_setg_errno(errp, ENOMEDIUM,
  5491. "Can't store persistent bitmaps to %s",
  5492. bdrv_get_device_or_node_name(bs));
  5493. return false;
  5494. }
  5495. if (!drv->bdrv_can_store_new_dirty_bitmap) {
  5496. error_setg_errno(errp, ENOTSUP,
  5497. "Can't store persistent bitmaps to %s",
  5498. bdrv_get_device_or_node_name(bs));
  5499. return false;
  5500. }
  5501. return drv->bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp);
  5502. }