2
0

block.c 210 KB

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