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 199KB

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