2
0

blockdev.c 119 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089
  1. /*
  2. * QEMU host block devices
  3. *
  4. * Copyright (c) 2003-2008 Fabrice Bellard
  5. *
  6. * This work is licensed under the terms of the GNU GPL, version 2 or
  7. * later. See the COPYING file in the top-level directory.
  8. *
  9. * This file incorporates work covered by the following copyright and
  10. * permission notice:
  11. *
  12. * Copyright (c) 2003-2008 Fabrice Bellard
  13. *
  14. * Permission is hereby granted, free of charge, to any person obtaining a copy
  15. * of this software and associated documentation files (the "Software"), to deal
  16. * in the Software without restriction, including without limitation the rights
  17. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18. * copies of the Software, and to permit persons to whom the Software is
  19. * furnished to do so, subject to the following conditions:
  20. *
  21. * The above copyright notice and this permission notice shall be included in
  22. * all copies or substantial portions of the Software.
  23. *
  24. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  25. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  26. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  27. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  28. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  29. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  30. * THE SOFTWARE.
  31. */
  32. #include "qemu/osdep.h"
  33. #include "sysemu/block-backend.h"
  34. #include "sysemu/blockdev.h"
  35. #include "hw/block/block.h"
  36. #include "block/blockjob.h"
  37. #include "block/throttle-groups.h"
  38. #include "monitor/monitor.h"
  39. #include "qemu/error-report.h"
  40. #include "qemu/option.h"
  41. #include "qemu/config-file.h"
  42. #include "qapi/qmp/types.h"
  43. #include "qapi-visit.h"
  44. #include "qapi/qmp/qerror.h"
  45. #include "qapi/qobject-output-visitor.h"
  46. #include "qapi/util.h"
  47. #include "sysemu/sysemu.h"
  48. #include "block/block_int.h"
  49. #include "qmp-commands.h"
  50. #include "block/trace.h"
  51. #include "sysemu/arch_init.h"
  52. #include "qemu/cutils.h"
  53. #include "qemu/help_option.h"
  54. #include "qemu/throttle-options.h"
  55. static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
  56. QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
  57. static int do_open_tray(const char *blk_name, const char *qdev_id,
  58. bool force, Error **errp);
  59. static const char *const if_name[IF_COUNT] = {
  60. [IF_NONE] = "none",
  61. [IF_IDE] = "ide",
  62. [IF_SCSI] = "scsi",
  63. [IF_FLOPPY] = "floppy",
  64. [IF_PFLASH] = "pflash",
  65. [IF_MTD] = "mtd",
  66. [IF_SD] = "sd",
  67. [IF_VIRTIO] = "virtio",
  68. [IF_XEN] = "xen",
  69. };
  70. static int if_max_devs[IF_COUNT] = {
  71. /*
  72. * Do not change these numbers! They govern how drive option
  73. * index maps to unit and bus. That mapping is ABI.
  74. *
  75. * All controllers used to implement if=T drives need to support
  76. * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
  77. * Otherwise, some index values map to "impossible" bus, unit
  78. * values.
  79. *
  80. * For instance, if you change [IF_SCSI] to 255, -drive
  81. * if=scsi,index=12 no longer means bus=1,unit=5, but
  82. * bus=0,unit=12. With an lsi53c895a controller (7 units max),
  83. * the drive can't be set up. Regression.
  84. */
  85. [IF_IDE] = 2,
  86. [IF_SCSI] = 7,
  87. };
  88. /**
  89. * Boards may call this to offer board-by-board overrides
  90. * of the default, global values.
  91. */
  92. void override_max_devs(BlockInterfaceType type, int max_devs)
  93. {
  94. BlockBackend *blk;
  95. DriveInfo *dinfo;
  96. if (max_devs <= 0) {
  97. return;
  98. }
  99. for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
  100. dinfo = blk_legacy_dinfo(blk);
  101. if (dinfo->type == type) {
  102. fprintf(stderr, "Cannot override units-per-bus property of"
  103. " the %s interface, because a drive of that type has"
  104. " already been added.\n", if_name[type]);
  105. g_assert_not_reached();
  106. }
  107. }
  108. if_max_devs[type] = max_devs;
  109. }
  110. /*
  111. * We automatically delete the drive when a device using it gets
  112. * unplugged. Questionable feature, but we can't just drop it.
  113. * Device models call blockdev_mark_auto_del() to schedule the
  114. * automatic deletion, and generic qdev code calls blockdev_auto_del()
  115. * when deletion is actually safe.
  116. */
  117. void blockdev_mark_auto_del(BlockBackend *blk)
  118. {
  119. DriveInfo *dinfo = blk_legacy_dinfo(blk);
  120. BlockDriverState *bs = blk_bs(blk);
  121. AioContext *aio_context;
  122. if (!dinfo) {
  123. return;
  124. }
  125. if (bs) {
  126. aio_context = bdrv_get_aio_context(bs);
  127. aio_context_acquire(aio_context);
  128. if (bs->job) {
  129. block_job_cancel(bs->job);
  130. }
  131. aio_context_release(aio_context);
  132. }
  133. dinfo->auto_del = 1;
  134. }
  135. void blockdev_auto_del(BlockBackend *blk)
  136. {
  137. DriveInfo *dinfo = blk_legacy_dinfo(blk);
  138. if (dinfo && dinfo->auto_del) {
  139. monitor_remove_blk(blk);
  140. blk_unref(blk);
  141. }
  142. }
  143. /**
  144. * Returns the current mapping of how many units per bus
  145. * a particular interface can support.
  146. *
  147. * A positive integer indicates n units per bus.
  148. * 0 implies the mapping has not been established.
  149. * -1 indicates an invalid BlockInterfaceType was given.
  150. */
  151. int drive_get_max_devs(BlockInterfaceType type)
  152. {
  153. if (type >= IF_IDE && type < IF_COUNT) {
  154. return if_max_devs[type];
  155. }
  156. return -1;
  157. }
  158. static int drive_index_to_bus_id(BlockInterfaceType type, int index)
  159. {
  160. int max_devs = if_max_devs[type];
  161. return max_devs ? index / max_devs : 0;
  162. }
  163. static int drive_index_to_unit_id(BlockInterfaceType type, int index)
  164. {
  165. int max_devs = if_max_devs[type];
  166. return max_devs ? index % max_devs : index;
  167. }
  168. QemuOpts *drive_def(const char *optstr)
  169. {
  170. return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
  171. }
  172. QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
  173. const char *optstr)
  174. {
  175. QemuOpts *opts;
  176. opts = drive_def(optstr);
  177. if (!opts) {
  178. return NULL;
  179. }
  180. if (type != IF_DEFAULT) {
  181. qemu_opt_set(opts, "if", if_name[type], &error_abort);
  182. }
  183. if (index >= 0) {
  184. qemu_opt_set_number(opts, "index", index, &error_abort);
  185. }
  186. if (file)
  187. qemu_opt_set(opts, "file", file, &error_abort);
  188. return opts;
  189. }
  190. DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
  191. {
  192. BlockBackend *blk;
  193. DriveInfo *dinfo;
  194. for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
  195. dinfo = blk_legacy_dinfo(blk);
  196. if (dinfo && dinfo->type == type
  197. && dinfo->bus == bus && dinfo->unit == unit) {
  198. return dinfo;
  199. }
  200. }
  201. return NULL;
  202. }
  203. void drive_check_orphaned(void)
  204. {
  205. BlockBackend *blk;
  206. DriveInfo *dinfo;
  207. Location loc;
  208. bool orphans = false;
  209. for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
  210. dinfo = blk_legacy_dinfo(blk);
  211. if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
  212. dinfo->type != IF_NONE) {
  213. loc_push_none(&loc);
  214. qemu_opts_loc_restore(dinfo->opts);
  215. error_report("machine type does not support"
  216. " if=%s,bus=%d,unit=%d",
  217. if_name[dinfo->type], dinfo->bus, dinfo->unit);
  218. loc_pop(&loc);
  219. orphans = true;
  220. }
  221. }
  222. if (orphans) {
  223. exit(1);
  224. }
  225. }
  226. DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
  227. {
  228. return drive_get(type,
  229. drive_index_to_bus_id(type, index),
  230. drive_index_to_unit_id(type, index));
  231. }
  232. int drive_get_max_bus(BlockInterfaceType type)
  233. {
  234. int max_bus;
  235. BlockBackend *blk;
  236. DriveInfo *dinfo;
  237. max_bus = -1;
  238. for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
  239. dinfo = blk_legacy_dinfo(blk);
  240. if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
  241. max_bus = dinfo->bus;
  242. }
  243. }
  244. return max_bus;
  245. }
  246. /* Get a block device. This should only be used for single-drive devices
  247. (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
  248. appropriate bus. */
  249. DriveInfo *drive_get_next(BlockInterfaceType type)
  250. {
  251. static int next_block_unit[IF_COUNT];
  252. return drive_get(type, 0, next_block_unit[type]++);
  253. }
  254. static void bdrv_format_print(void *opaque, const char *name)
  255. {
  256. error_printf(" %s", name);
  257. }
  258. typedef struct {
  259. QEMUBH *bh;
  260. BlockDriverState *bs;
  261. } BDRVPutRefBH;
  262. static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
  263. {
  264. if (!strcmp(buf, "ignore")) {
  265. return BLOCKDEV_ON_ERROR_IGNORE;
  266. } else if (!is_read && !strcmp(buf, "enospc")) {
  267. return BLOCKDEV_ON_ERROR_ENOSPC;
  268. } else if (!strcmp(buf, "stop")) {
  269. return BLOCKDEV_ON_ERROR_STOP;
  270. } else if (!strcmp(buf, "report")) {
  271. return BLOCKDEV_ON_ERROR_REPORT;
  272. } else {
  273. error_setg(errp, "'%s' invalid %s error action",
  274. buf, is_read ? "read" : "write");
  275. return -1;
  276. }
  277. }
  278. static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
  279. Error **errp)
  280. {
  281. const QListEntry *entry;
  282. for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
  283. switch (qobject_type(entry->value)) {
  284. case QTYPE_QSTRING: {
  285. unsigned long long length;
  286. const char *str = qstring_get_str(qobject_to_qstring(entry->value));
  287. if (parse_uint_full(str, &length, 10) == 0 &&
  288. length > 0 && length <= UINT_MAX) {
  289. block_acct_add_interval(stats, (unsigned) length);
  290. } else {
  291. error_setg(errp, "Invalid interval length: %s", str);
  292. return false;
  293. }
  294. break;
  295. }
  296. case QTYPE_QINT: {
  297. int64_t length = qint_get_int(qobject_to_qint(entry->value));
  298. if (length > 0 && length <= UINT_MAX) {
  299. block_acct_add_interval(stats, (unsigned) length);
  300. } else {
  301. error_setg(errp, "Invalid interval length: %" PRId64, length);
  302. return false;
  303. }
  304. break;
  305. }
  306. default:
  307. error_setg(errp, "The specification of stats-intervals is invalid");
  308. return false;
  309. }
  310. }
  311. return true;
  312. }
  313. typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
  314. /* All parameters but @opts are optional and may be set to NULL. */
  315. static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
  316. const char **throttling_group, ThrottleConfig *throttle_cfg,
  317. BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
  318. {
  319. Error *local_error = NULL;
  320. const char *aio;
  321. if (bdrv_flags) {
  322. if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
  323. *bdrv_flags |= BDRV_O_COPY_ON_READ;
  324. }
  325. if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
  326. if (!strcmp(aio, "native")) {
  327. *bdrv_flags |= BDRV_O_NATIVE_AIO;
  328. } else if (!strcmp(aio, "threads")) {
  329. /* this is the default */
  330. } else {
  331. error_setg(errp, "invalid aio option");
  332. return;
  333. }
  334. }
  335. }
  336. /* disk I/O throttling */
  337. if (throttling_group) {
  338. *throttling_group = qemu_opt_get(opts, "throttling.group");
  339. }
  340. if (throttle_cfg) {
  341. throttle_config_init(throttle_cfg);
  342. throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
  343. qemu_opt_get_number(opts, "throttling.bps-total", 0);
  344. throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
  345. qemu_opt_get_number(opts, "throttling.bps-read", 0);
  346. throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
  347. qemu_opt_get_number(opts, "throttling.bps-write", 0);
  348. throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
  349. qemu_opt_get_number(opts, "throttling.iops-total", 0);
  350. throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
  351. qemu_opt_get_number(opts, "throttling.iops-read", 0);
  352. throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
  353. qemu_opt_get_number(opts, "throttling.iops-write", 0);
  354. throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
  355. qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
  356. throttle_cfg->buckets[THROTTLE_BPS_READ].max =
  357. qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
  358. throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
  359. qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
  360. throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
  361. qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
  362. throttle_cfg->buckets[THROTTLE_OPS_READ].max =
  363. qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
  364. throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
  365. qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
  366. throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
  367. qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
  368. throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
  369. qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
  370. throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
  371. qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
  372. throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
  373. qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
  374. throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
  375. qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
  376. throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
  377. qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
  378. throttle_cfg->op_size =
  379. qemu_opt_get_number(opts, "throttling.iops-size", 0);
  380. if (!throttle_is_valid(throttle_cfg, errp)) {
  381. return;
  382. }
  383. }
  384. if (detect_zeroes) {
  385. *detect_zeroes =
  386. qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
  387. qemu_opt_get(opts, "detect-zeroes"),
  388. BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
  389. BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
  390. &local_error);
  391. if (local_error) {
  392. error_propagate(errp, local_error);
  393. return;
  394. }
  395. }
  396. }
  397. /* Takes the ownership of bs_opts */
  398. static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
  399. Error **errp)
  400. {
  401. const char *buf;
  402. int bdrv_flags = 0;
  403. int on_read_error, on_write_error;
  404. bool account_invalid, account_failed;
  405. bool writethrough, read_only;
  406. BlockBackend *blk;
  407. BlockDriverState *bs;
  408. ThrottleConfig cfg;
  409. int snapshot = 0;
  410. Error *error = NULL;
  411. QemuOpts *opts;
  412. QDict *interval_dict = NULL;
  413. QList *interval_list = NULL;
  414. const char *id;
  415. BlockdevDetectZeroesOptions detect_zeroes =
  416. BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
  417. const char *throttling_group = NULL;
  418. /* Check common options by copying from bs_opts to opts, all other options
  419. * stay in bs_opts for processing by bdrv_open(). */
  420. id = qdict_get_try_str(bs_opts, "id");
  421. opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
  422. if (error) {
  423. error_propagate(errp, error);
  424. goto err_no_opts;
  425. }
  426. qemu_opts_absorb_qdict(opts, bs_opts, &error);
  427. if (error) {
  428. error_propagate(errp, error);
  429. goto early_err;
  430. }
  431. if (id) {
  432. qdict_del(bs_opts, "id");
  433. }
  434. /* extract parameters */
  435. snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
  436. account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
  437. account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
  438. writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
  439. id = qemu_opts_id(opts);
  440. qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
  441. qdict_array_split(interval_dict, &interval_list);
  442. if (qdict_size(interval_dict) != 0) {
  443. error_setg(errp, "Invalid option stats-intervals.%s",
  444. qdict_first(interval_dict)->key);
  445. goto early_err;
  446. }
  447. extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
  448. &detect_zeroes, &error);
  449. if (error) {
  450. error_propagate(errp, error);
  451. goto early_err;
  452. }
  453. if ((buf = qemu_opt_get(opts, "format")) != NULL) {
  454. if (is_help_option(buf)) {
  455. error_printf("Supported formats:");
  456. bdrv_iterate_format(bdrv_format_print, NULL);
  457. error_printf("\n");
  458. goto early_err;
  459. }
  460. if (qdict_haskey(bs_opts, "driver")) {
  461. error_setg(errp, "Cannot specify both 'driver' and 'format'");
  462. goto early_err;
  463. }
  464. qdict_put_str(bs_opts, "driver", buf);
  465. }
  466. on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
  467. if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
  468. on_write_error = parse_block_error_action(buf, 0, &error);
  469. if (error) {
  470. error_propagate(errp, error);
  471. goto early_err;
  472. }
  473. }
  474. on_read_error = BLOCKDEV_ON_ERROR_REPORT;
  475. if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
  476. on_read_error = parse_block_error_action(buf, 1, &error);
  477. if (error) {
  478. error_propagate(errp, error);
  479. goto early_err;
  480. }
  481. }
  482. if (snapshot) {
  483. bdrv_flags |= BDRV_O_SNAPSHOT;
  484. }
  485. read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
  486. /* init */
  487. if ((!file || !*file) && !qdict_size(bs_opts)) {
  488. BlockBackendRootState *blk_rs;
  489. blk = blk_new(0, BLK_PERM_ALL);
  490. blk_rs = blk_get_root_state(blk);
  491. blk_rs->open_flags = bdrv_flags;
  492. blk_rs->read_only = read_only;
  493. blk_rs->detect_zeroes = detect_zeroes;
  494. QDECREF(bs_opts);
  495. } else {
  496. if (file && !*file) {
  497. file = NULL;
  498. }
  499. /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
  500. * with other callers) rather than what we want as the real defaults.
  501. * Apply the defaults here instead. */
  502. qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
  503. qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
  504. qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
  505. read_only ? "on" : "off");
  506. assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
  507. if (runstate_check(RUN_STATE_INMIGRATE)) {
  508. bdrv_flags |= BDRV_O_INACTIVE;
  509. }
  510. blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
  511. if (!blk) {
  512. goto err_no_bs_opts;
  513. }
  514. bs = blk_bs(blk);
  515. bs->detect_zeroes = detect_zeroes;
  516. if (bdrv_key_required(bs)) {
  517. autostart = 0;
  518. }
  519. block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
  520. if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
  521. blk_unref(blk);
  522. blk = NULL;
  523. goto err_no_bs_opts;
  524. }
  525. }
  526. /* disk I/O throttling */
  527. if (throttle_enabled(&cfg)) {
  528. if (!throttling_group) {
  529. throttling_group = id;
  530. }
  531. blk_io_limits_enable(blk, throttling_group);
  532. blk_set_io_limits(blk, &cfg);
  533. }
  534. blk_set_enable_write_cache(blk, !writethrough);
  535. blk_set_on_error(blk, on_read_error, on_write_error);
  536. if (!monitor_add_blk(blk, id, errp)) {
  537. blk_unref(blk);
  538. blk = NULL;
  539. goto err_no_bs_opts;
  540. }
  541. err_no_bs_opts:
  542. qemu_opts_del(opts);
  543. QDECREF(interval_dict);
  544. QDECREF(interval_list);
  545. return blk;
  546. early_err:
  547. qemu_opts_del(opts);
  548. QDECREF(interval_dict);
  549. QDECREF(interval_list);
  550. err_no_opts:
  551. QDECREF(bs_opts);
  552. return NULL;
  553. }
  554. /* Takes the ownership of bs_opts */
  555. static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
  556. {
  557. int bdrv_flags = 0;
  558. /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
  559. * with other callers) rather than what we want as the real defaults.
  560. * Apply the defaults here instead. */
  561. qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
  562. qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
  563. qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
  564. if (runstate_check(RUN_STATE_INMIGRATE)) {
  565. bdrv_flags |= BDRV_O_INACTIVE;
  566. }
  567. return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
  568. }
  569. void blockdev_close_all_bdrv_states(void)
  570. {
  571. BlockDriverState *bs, *next_bs;
  572. QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
  573. AioContext *ctx = bdrv_get_aio_context(bs);
  574. aio_context_acquire(ctx);
  575. bdrv_unref(bs);
  576. aio_context_release(ctx);
  577. }
  578. }
  579. /* Iterates over the list of monitor-owned BlockDriverStates */
  580. BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
  581. {
  582. return bs ? QTAILQ_NEXT(bs, monitor_list)
  583. : QTAILQ_FIRST(&monitor_bdrv_states);
  584. }
  585. static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
  586. Error **errp)
  587. {
  588. const char *value;
  589. value = qemu_opt_get(opts, from);
  590. if (value) {
  591. if (qemu_opt_find(opts, to)) {
  592. error_setg(errp, "'%s' and its alias '%s' can't be used at the "
  593. "same time", to, from);
  594. return;
  595. }
  596. }
  597. /* rename all items in opts */
  598. while ((value = qemu_opt_get(opts, from))) {
  599. qemu_opt_set(opts, to, value, &error_abort);
  600. qemu_opt_unset(opts, from);
  601. }
  602. }
  603. QemuOptsList qemu_legacy_drive_opts = {
  604. .name = "drive",
  605. .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
  606. .desc = {
  607. {
  608. .name = "bus",
  609. .type = QEMU_OPT_NUMBER,
  610. .help = "bus number",
  611. },{
  612. .name = "unit",
  613. .type = QEMU_OPT_NUMBER,
  614. .help = "unit number (i.e. lun for scsi)",
  615. },{
  616. .name = "index",
  617. .type = QEMU_OPT_NUMBER,
  618. .help = "index number",
  619. },{
  620. .name = "media",
  621. .type = QEMU_OPT_STRING,
  622. .help = "media type (disk, cdrom)",
  623. },{
  624. .name = "if",
  625. .type = QEMU_OPT_STRING,
  626. .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
  627. },{
  628. .name = "cyls",
  629. .type = QEMU_OPT_NUMBER,
  630. .help = "number of cylinders (ide disk geometry)",
  631. },{
  632. .name = "heads",
  633. .type = QEMU_OPT_NUMBER,
  634. .help = "number of heads (ide disk geometry)",
  635. },{
  636. .name = "secs",
  637. .type = QEMU_OPT_NUMBER,
  638. .help = "number of sectors (ide disk geometry)",
  639. },{
  640. .name = "trans",
  641. .type = QEMU_OPT_STRING,
  642. .help = "chs translation (auto, lba, none)",
  643. },{
  644. .name = "boot",
  645. .type = QEMU_OPT_BOOL,
  646. .help = "(deprecated, ignored)",
  647. },{
  648. .name = "addr",
  649. .type = QEMU_OPT_STRING,
  650. .help = "pci address (virtio only)",
  651. },{
  652. .name = "serial",
  653. .type = QEMU_OPT_STRING,
  654. .help = "disk serial number",
  655. },{
  656. .name = "file",
  657. .type = QEMU_OPT_STRING,
  658. .help = "file name",
  659. },
  660. /* Options that are passed on, but have special semantics with -drive */
  661. {
  662. .name = BDRV_OPT_READ_ONLY,
  663. .type = QEMU_OPT_BOOL,
  664. .help = "open drive file as read-only",
  665. },{
  666. .name = "rerror",
  667. .type = QEMU_OPT_STRING,
  668. .help = "read error action",
  669. },{
  670. .name = "werror",
  671. .type = QEMU_OPT_STRING,
  672. .help = "write error action",
  673. },{
  674. .name = "copy-on-read",
  675. .type = QEMU_OPT_BOOL,
  676. .help = "copy read data from backing file into image file",
  677. },
  678. { /* end of list */ }
  679. },
  680. };
  681. DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
  682. {
  683. const char *value;
  684. BlockBackend *blk;
  685. DriveInfo *dinfo = NULL;
  686. QDict *bs_opts;
  687. QemuOpts *legacy_opts;
  688. DriveMediaType media = MEDIA_DISK;
  689. BlockInterfaceType type;
  690. int cyls, heads, secs, translation;
  691. int max_devs, bus_id, unit_id, index;
  692. const char *devaddr;
  693. const char *werror, *rerror;
  694. bool read_only = false;
  695. bool copy_on_read;
  696. const char *serial;
  697. const char *filename;
  698. Error *local_err = NULL;
  699. int i;
  700. /* Change legacy command line options into QMP ones */
  701. static const struct {
  702. const char *from;
  703. const char *to;
  704. } opt_renames[] = {
  705. { "iops", "throttling.iops-total" },
  706. { "iops_rd", "throttling.iops-read" },
  707. { "iops_wr", "throttling.iops-write" },
  708. { "bps", "throttling.bps-total" },
  709. { "bps_rd", "throttling.bps-read" },
  710. { "bps_wr", "throttling.bps-write" },
  711. { "iops_max", "throttling.iops-total-max" },
  712. { "iops_rd_max", "throttling.iops-read-max" },
  713. { "iops_wr_max", "throttling.iops-write-max" },
  714. { "bps_max", "throttling.bps-total-max" },
  715. { "bps_rd_max", "throttling.bps-read-max" },
  716. { "bps_wr_max", "throttling.bps-write-max" },
  717. { "iops_size", "throttling.iops-size" },
  718. { "group", "throttling.group" },
  719. { "readonly", BDRV_OPT_READ_ONLY },
  720. };
  721. for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
  722. qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
  723. &local_err);
  724. if (local_err) {
  725. error_report_err(local_err);
  726. return NULL;
  727. }
  728. }
  729. value = qemu_opt_get(all_opts, "cache");
  730. if (value) {
  731. int flags = 0;
  732. bool writethrough;
  733. if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
  734. error_report("invalid cache option");
  735. return NULL;
  736. }
  737. /* Specific options take precedence */
  738. if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
  739. qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
  740. !writethrough, &error_abort);
  741. }
  742. if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
  743. qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
  744. !!(flags & BDRV_O_NOCACHE), &error_abort);
  745. }
  746. if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
  747. qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
  748. !!(flags & BDRV_O_NO_FLUSH), &error_abort);
  749. }
  750. qemu_opt_unset(all_opts, "cache");
  751. }
  752. /* Get a QDict for processing the options */
  753. bs_opts = qdict_new();
  754. qemu_opts_to_qdict(all_opts, bs_opts);
  755. legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
  756. &error_abort);
  757. qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
  758. if (local_err) {
  759. error_report_err(local_err);
  760. goto fail;
  761. }
  762. /* Deprecated option boot=[on|off] */
  763. if (qemu_opt_get(legacy_opts, "boot") != NULL) {
  764. fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
  765. "ignored. Future versions will reject this parameter. Please "
  766. "update your scripts.\n");
  767. }
  768. /* Media type */
  769. value = qemu_opt_get(legacy_opts, "media");
  770. if (value) {
  771. if (!strcmp(value, "disk")) {
  772. media = MEDIA_DISK;
  773. } else if (!strcmp(value, "cdrom")) {
  774. media = MEDIA_CDROM;
  775. read_only = true;
  776. } else {
  777. error_report("'%s' invalid media", value);
  778. goto fail;
  779. }
  780. }
  781. /* copy-on-read is disabled with a warning for read-only devices */
  782. read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
  783. copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
  784. if (read_only && copy_on_read) {
  785. error_report("warning: disabling copy-on-read on read-only drive");
  786. copy_on_read = false;
  787. }
  788. qdict_put_str(bs_opts, BDRV_OPT_READ_ONLY, read_only ? "on" : "off");
  789. qdict_put_str(bs_opts, "copy-on-read", copy_on_read ? "on" : "off");
  790. /* Controller type */
  791. value = qemu_opt_get(legacy_opts, "if");
  792. if (value) {
  793. for (type = 0;
  794. type < IF_COUNT && strcmp(value, if_name[type]);
  795. type++) {
  796. }
  797. if (type == IF_COUNT) {
  798. error_report("unsupported bus type '%s'", value);
  799. goto fail;
  800. }
  801. } else {
  802. type = block_default_type;
  803. }
  804. /* Geometry */
  805. cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
  806. heads = qemu_opt_get_number(legacy_opts, "heads", 0);
  807. secs = qemu_opt_get_number(legacy_opts, "secs", 0);
  808. if (cyls || heads || secs) {
  809. if (cyls < 1) {
  810. error_report("invalid physical cyls number");
  811. goto fail;
  812. }
  813. if (heads < 1) {
  814. error_report("invalid physical heads number");
  815. goto fail;
  816. }
  817. if (secs < 1) {
  818. error_report("invalid physical secs number");
  819. goto fail;
  820. }
  821. }
  822. translation = BIOS_ATA_TRANSLATION_AUTO;
  823. value = qemu_opt_get(legacy_opts, "trans");
  824. if (value != NULL) {
  825. if (!cyls) {
  826. error_report("'%s' trans must be used with cyls, heads and secs",
  827. value);
  828. goto fail;
  829. }
  830. if (!strcmp(value, "none")) {
  831. translation = BIOS_ATA_TRANSLATION_NONE;
  832. } else if (!strcmp(value, "lba")) {
  833. translation = BIOS_ATA_TRANSLATION_LBA;
  834. } else if (!strcmp(value, "large")) {
  835. translation = BIOS_ATA_TRANSLATION_LARGE;
  836. } else if (!strcmp(value, "rechs")) {
  837. translation = BIOS_ATA_TRANSLATION_RECHS;
  838. } else if (!strcmp(value, "auto")) {
  839. translation = BIOS_ATA_TRANSLATION_AUTO;
  840. } else {
  841. error_report("'%s' invalid translation type", value);
  842. goto fail;
  843. }
  844. }
  845. if (media == MEDIA_CDROM) {
  846. if (cyls || secs || heads) {
  847. error_report("CHS can't be set with media=cdrom");
  848. goto fail;
  849. }
  850. }
  851. /* Device address specified by bus/unit or index.
  852. * If none was specified, try to find the first free one. */
  853. bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
  854. unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
  855. index = qemu_opt_get_number(legacy_opts, "index", -1);
  856. max_devs = if_max_devs[type];
  857. if (index != -1) {
  858. if (bus_id != 0 || unit_id != -1) {
  859. error_report("index cannot be used with bus and unit");
  860. goto fail;
  861. }
  862. bus_id = drive_index_to_bus_id(type, index);
  863. unit_id = drive_index_to_unit_id(type, index);
  864. }
  865. if (unit_id == -1) {
  866. unit_id = 0;
  867. while (drive_get(type, bus_id, unit_id) != NULL) {
  868. unit_id++;
  869. if (max_devs && unit_id >= max_devs) {
  870. unit_id -= max_devs;
  871. bus_id++;
  872. }
  873. }
  874. }
  875. if (max_devs && unit_id >= max_devs) {
  876. error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
  877. goto fail;
  878. }
  879. if (drive_get(type, bus_id, unit_id) != NULL) {
  880. error_report("drive with bus=%d, unit=%d (index=%d) exists",
  881. bus_id, unit_id, index);
  882. goto fail;
  883. }
  884. /* Serial number */
  885. serial = qemu_opt_get(legacy_opts, "serial");
  886. /* no id supplied -> create one */
  887. if (qemu_opts_id(all_opts) == NULL) {
  888. char *new_id;
  889. const char *mediastr = "";
  890. if (type == IF_IDE || type == IF_SCSI) {
  891. mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
  892. }
  893. if (max_devs) {
  894. new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
  895. mediastr, unit_id);
  896. } else {
  897. new_id = g_strdup_printf("%s%s%i", if_name[type],
  898. mediastr, unit_id);
  899. }
  900. qdict_put_str(bs_opts, "id", new_id);
  901. g_free(new_id);
  902. }
  903. /* Add virtio block device */
  904. devaddr = qemu_opt_get(legacy_opts, "addr");
  905. if (devaddr && type != IF_VIRTIO) {
  906. error_report("addr is not supported by this bus type");
  907. goto fail;
  908. }
  909. if (type == IF_VIRTIO) {
  910. QemuOpts *devopts;
  911. devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
  912. &error_abort);
  913. if (arch_type == QEMU_ARCH_S390X) {
  914. qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
  915. } else {
  916. qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
  917. }
  918. qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
  919. &error_abort);
  920. if (devaddr) {
  921. qemu_opt_set(devopts, "addr", devaddr, &error_abort);
  922. }
  923. }
  924. filename = qemu_opt_get(legacy_opts, "file");
  925. /* Check werror/rerror compatibility with if=... */
  926. werror = qemu_opt_get(legacy_opts, "werror");
  927. if (werror != NULL) {
  928. if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
  929. type != IF_NONE) {
  930. error_report("werror is not supported by this bus type");
  931. goto fail;
  932. }
  933. qdict_put_str(bs_opts, "werror", werror);
  934. }
  935. rerror = qemu_opt_get(legacy_opts, "rerror");
  936. if (rerror != NULL) {
  937. if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
  938. type != IF_NONE) {
  939. error_report("rerror is not supported by this bus type");
  940. goto fail;
  941. }
  942. qdict_put_str(bs_opts, "rerror", rerror);
  943. }
  944. /* Actual block device init: Functionality shared with blockdev-add */
  945. blk = blockdev_init(filename, bs_opts, &local_err);
  946. bs_opts = NULL;
  947. if (!blk) {
  948. if (local_err) {
  949. error_report_err(local_err);
  950. }
  951. goto fail;
  952. } else {
  953. assert(!local_err);
  954. }
  955. /* Create legacy DriveInfo */
  956. dinfo = g_malloc0(sizeof(*dinfo));
  957. dinfo->opts = all_opts;
  958. dinfo->cyls = cyls;
  959. dinfo->heads = heads;
  960. dinfo->secs = secs;
  961. dinfo->trans = translation;
  962. dinfo->type = type;
  963. dinfo->bus = bus_id;
  964. dinfo->unit = unit_id;
  965. dinfo->devaddr = devaddr;
  966. dinfo->serial = g_strdup(serial);
  967. blk_set_legacy_dinfo(blk, dinfo);
  968. switch(type) {
  969. case IF_IDE:
  970. case IF_SCSI:
  971. case IF_XEN:
  972. case IF_NONE:
  973. dinfo->media_cd = media == MEDIA_CDROM;
  974. break;
  975. default:
  976. break;
  977. }
  978. fail:
  979. qemu_opts_del(legacy_opts);
  980. QDECREF(bs_opts);
  981. return dinfo;
  982. }
  983. static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
  984. {
  985. BlockDriverState *bs;
  986. bs = bdrv_lookup_bs(name, name, errp);
  987. if (bs == NULL) {
  988. return NULL;
  989. }
  990. if (!bdrv_is_root_node(bs)) {
  991. error_setg(errp, "Need a root block node");
  992. return NULL;
  993. }
  994. if (!bdrv_is_inserted(bs)) {
  995. error_setg(errp, "Device has no medium");
  996. return NULL;
  997. }
  998. return bs;
  999. }
  1000. static BlockBackend *qmp_get_blk(const char *blk_name, const char *qdev_id,
  1001. Error **errp)
  1002. {
  1003. BlockBackend *blk;
  1004. if (!blk_name == !qdev_id) {
  1005. error_setg(errp, "Need exactly one of 'device' and 'id'");
  1006. return NULL;
  1007. }
  1008. if (qdev_id) {
  1009. blk = blk_by_qdev_id(qdev_id, errp);
  1010. } else {
  1011. blk = blk_by_name(blk_name);
  1012. if (blk == NULL) {
  1013. error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
  1014. "Device '%s' not found", blk_name);
  1015. }
  1016. }
  1017. return blk;
  1018. }
  1019. void hmp_commit(Monitor *mon, const QDict *qdict)
  1020. {
  1021. const char *device = qdict_get_str(qdict, "device");
  1022. BlockBackend *blk;
  1023. int ret;
  1024. if (!strcmp(device, "all")) {
  1025. ret = blk_commit_all();
  1026. } else {
  1027. BlockDriverState *bs;
  1028. AioContext *aio_context;
  1029. blk = blk_by_name(device);
  1030. if (!blk) {
  1031. monitor_printf(mon, "Device '%s' not found\n", device);
  1032. return;
  1033. }
  1034. if (!blk_is_available(blk)) {
  1035. monitor_printf(mon, "Device '%s' has no medium\n", device);
  1036. return;
  1037. }
  1038. bs = blk_bs(blk);
  1039. aio_context = bdrv_get_aio_context(bs);
  1040. aio_context_acquire(aio_context);
  1041. ret = bdrv_commit(bs);
  1042. aio_context_release(aio_context);
  1043. }
  1044. if (ret < 0) {
  1045. monitor_printf(mon, "'commit' error for '%s': %s\n", device,
  1046. strerror(-ret));
  1047. }
  1048. }
  1049. static void blockdev_do_action(TransactionAction *action, Error **errp)
  1050. {
  1051. TransactionActionList list;
  1052. list.value = action;
  1053. list.next = NULL;
  1054. qmp_transaction(&list, false, NULL, errp);
  1055. }
  1056. void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
  1057. bool has_node_name, const char *node_name,
  1058. const char *snapshot_file,
  1059. bool has_snapshot_node_name,
  1060. const char *snapshot_node_name,
  1061. bool has_format, const char *format,
  1062. bool has_mode, NewImageMode mode, Error **errp)
  1063. {
  1064. BlockdevSnapshotSync snapshot = {
  1065. .has_device = has_device,
  1066. .device = (char *) device,
  1067. .has_node_name = has_node_name,
  1068. .node_name = (char *) node_name,
  1069. .snapshot_file = (char *) snapshot_file,
  1070. .has_snapshot_node_name = has_snapshot_node_name,
  1071. .snapshot_node_name = (char *) snapshot_node_name,
  1072. .has_format = has_format,
  1073. .format = (char *) format,
  1074. .has_mode = has_mode,
  1075. .mode = mode,
  1076. };
  1077. TransactionAction action = {
  1078. .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
  1079. .u.blockdev_snapshot_sync.data = &snapshot,
  1080. };
  1081. blockdev_do_action(&action, errp);
  1082. }
  1083. void qmp_blockdev_snapshot(const char *node, const char *overlay,
  1084. Error **errp)
  1085. {
  1086. BlockdevSnapshot snapshot_data = {
  1087. .node = (char *) node,
  1088. .overlay = (char *) overlay
  1089. };
  1090. TransactionAction action = {
  1091. .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
  1092. .u.blockdev_snapshot.data = &snapshot_data,
  1093. };
  1094. blockdev_do_action(&action, errp);
  1095. }
  1096. void qmp_blockdev_snapshot_internal_sync(const char *device,
  1097. const char *name,
  1098. Error **errp)
  1099. {
  1100. BlockdevSnapshotInternal snapshot = {
  1101. .device = (char *) device,
  1102. .name = (char *) name
  1103. };
  1104. TransactionAction action = {
  1105. .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
  1106. .u.blockdev_snapshot_internal_sync.data = &snapshot,
  1107. };
  1108. blockdev_do_action(&action, errp);
  1109. }
  1110. SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
  1111. bool has_id,
  1112. const char *id,
  1113. bool has_name,
  1114. const char *name,
  1115. Error **errp)
  1116. {
  1117. BlockDriverState *bs;
  1118. AioContext *aio_context;
  1119. QEMUSnapshotInfo sn;
  1120. Error *local_err = NULL;
  1121. SnapshotInfo *info = NULL;
  1122. int ret;
  1123. bs = qmp_get_root_bs(device, errp);
  1124. if (!bs) {
  1125. return NULL;
  1126. }
  1127. aio_context = bdrv_get_aio_context(bs);
  1128. aio_context_acquire(aio_context);
  1129. if (!has_id) {
  1130. id = NULL;
  1131. }
  1132. if (!has_name) {
  1133. name = NULL;
  1134. }
  1135. if (!id && !name) {
  1136. error_setg(errp, "Name or id must be provided");
  1137. goto out_aio_context;
  1138. }
  1139. if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
  1140. goto out_aio_context;
  1141. }
  1142. ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
  1143. if (local_err) {
  1144. error_propagate(errp, local_err);
  1145. goto out_aio_context;
  1146. }
  1147. if (!ret) {
  1148. error_setg(errp,
  1149. "Snapshot with id '%s' and name '%s' does not exist on "
  1150. "device '%s'",
  1151. STR_OR_NULL(id), STR_OR_NULL(name), device);
  1152. goto out_aio_context;
  1153. }
  1154. bdrv_snapshot_delete(bs, id, name, &local_err);
  1155. if (local_err) {
  1156. error_propagate(errp, local_err);
  1157. goto out_aio_context;
  1158. }
  1159. aio_context_release(aio_context);
  1160. info = g_new0(SnapshotInfo, 1);
  1161. info->id = g_strdup(sn.id_str);
  1162. info->name = g_strdup(sn.name);
  1163. info->date_nsec = sn.date_nsec;
  1164. info->date_sec = sn.date_sec;
  1165. info->vm_state_size = sn.vm_state_size;
  1166. info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
  1167. info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
  1168. return info;
  1169. out_aio_context:
  1170. aio_context_release(aio_context);
  1171. return NULL;
  1172. }
  1173. /**
  1174. * block_dirty_bitmap_lookup:
  1175. * Return a dirty bitmap (if present), after validating
  1176. * the node reference and bitmap names.
  1177. *
  1178. * @node: The name of the BDS node to search for bitmaps
  1179. * @name: The name of the bitmap to search for
  1180. * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
  1181. * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
  1182. * @errp: Output pointer for error information. Can be NULL.
  1183. *
  1184. * @return: A bitmap object on success, or NULL on failure.
  1185. */
  1186. static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
  1187. const char *name,
  1188. BlockDriverState **pbs,
  1189. AioContext **paio,
  1190. Error **errp)
  1191. {
  1192. BlockDriverState *bs;
  1193. BdrvDirtyBitmap *bitmap;
  1194. AioContext *aio_context;
  1195. if (!node) {
  1196. error_setg(errp, "Node cannot be NULL");
  1197. return NULL;
  1198. }
  1199. if (!name) {
  1200. error_setg(errp, "Bitmap name cannot be NULL");
  1201. return NULL;
  1202. }
  1203. bs = bdrv_lookup_bs(node, node, NULL);
  1204. if (!bs) {
  1205. error_setg(errp, "Node '%s' not found", node);
  1206. return NULL;
  1207. }
  1208. aio_context = bdrv_get_aio_context(bs);
  1209. aio_context_acquire(aio_context);
  1210. bitmap = bdrv_find_dirty_bitmap(bs, name);
  1211. if (!bitmap) {
  1212. error_setg(errp, "Dirty bitmap '%s' not found", name);
  1213. goto fail;
  1214. }
  1215. if (pbs) {
  1216. *pbs = bs;
  1217. }
  1218. if (paio) {
  1219. *paio = aio_context;
  1220. } else {
  1221. aio_context_release(aio_context);
  1222. }
  1223. return bitmap;
  1224. fail:
  1225. aio_context_release(aio_context);
  1226. return NULL;
  1227. }
  1228. /* New and old BlockDriverState structs for atomic group operations */
  1229. typedef struct BlkActionState BlkActionState;
  1230. /**
  1231. * BlkActionOps:
  1232. * Table of operations that define an Action.
  1233. *
  1234. * @instance_size: Size of state struct, in bytes.
  1235. * @prepare: Prepare the work, must NOT be NULL.
  1236. * @commit: Commit the changes, can be NULL.
  1237. * @abort: Abort the changes on fail, can be NULL.
  1238. * @clean: Clean up resources after all transaction actions have called
  1239. * commit() or abort(). Can be NULL.
  1240. *
  1241. * Only prepare() may fail. In a single transaction, only one of commit() or
  1242. * abort() will be called. clean() will always be called if it is present.
  1243. */
  1244. typedef struct BlkActionOps {
  1245. size_t instance_size;
  1246. void (*prepare)(BlkActionState *common, Error **errp);
  1247. void (*commit)(BlkActionState *common);
  1248. void (*abort)(BlkActionState *common);
  1249. void (*clean)(BlkActionState *common);
  1250. } BlkActionOps;
  1251. /**
  1252. * BlkActionState:
  1253. * Describes one Action's state within a Transaction.
  1254. *
  1255. * @action: QAPI-defined enum identifying which Action to perform.
  1256. * @ops: Table of ActionOps this Action can perform.
  1257. * @block_job_txn: Transaction which this action belongs to.
  1258. * @entry: List membership for all Actions in this Transaction.
  1259. *
  1260. * This structure must be arranged as first member in a subclassed type,
  1261. * assuming that the compiler will also arrange it to the same offsets as the
  1262. * base class.
  1263. */
  1264. struct BlkActionState {
  1265. TransactionAction *action;
  1266. const BlkActionOps *ops;
  1267. BlockJobTxn *block_job_txn;
  1268. TransactionProperties *txn_props;
  1269. QSIMPLEQ_ENTRY(BlkActionState) entry;
  1270. };
  1271. /* internal snapshot private data */
  1272. typedef struct InternalSnapshotState {
  1273. BlkActionState common;
  1274. BlockDriverState *bs;
  1275. AioContext *aio_context;
  1276. QEMUSnapshotInfo sn;
  1277. bool created;
  1278. } InternalSnapshotState;
  1279. static int action_check_completion_mode(BlkActionState *s, Error **errp)
  1280. {
  1281. if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
  1282. error_setg(errp,
  1283. "Action '%s' does not support Transaction property "
  1284. "completion-mode = %s",
  1285. TransactionActionKind_lookup[s->action->type],
  1286. ActionCompletionMode_lookup[s->txn_props->completion_mode]);
  1287. return -1;
  1288. }
  1289. return 0;
  1290. }
  1291. static void internal_snapshot_prepare(BlkActionState *common,
  1292. Error **errp)
  1293. {
  1294. Error *local_err = NULL;
  1295. const char *device;
  1296. const char *name;
  1297. BlockDriverState *bs;
  1298. QEMUSnapshotInfo old_sn, *sn;
  1299. bool ret;
  1300. qemu_timeval tv;
  1301. BlockdevSnapshotInternal *internal;
  1302. InternalSnapshotState *state;
  1303. int ret1;
  1304. g_assert(common->action->type ==
  1305. TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
  1306. internal = common->action->u.blockdev_snapshot_internal_sync.data;
  1307. state = DO_UPCAST(InternalSnapshotState, common, common);
  1308. /* 1. parse input */
  1309. device = internal->device;
  1310. name = internal->name;
  1311. /* 2. check for validation */
  1312. if (action_check_completion_mode(common, errp) < 0) {
  1313. return;
  1314. }
  1315. bs = qmp_get_root_bs(device, errp);
  1316. if (!bs) {
  1317. return;
  1318. }
  1319. /* AioContext is released in .clean() */
  1320. state->aio_context = bdrv_get_aio_context(bs);
  1321. aio_context_acquire(state->aio_context);
  1322. state->bs = bs;
  1323. bdrv_drained_begin(bs);
  1324. if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
  1325. return;
  1326. }
  1327. if (bdrv_is_read_only(bs)) {
  1328. error_setg(errp, "Device '%s' is read only", device);
  1329. return;
  1330. }
  1331. if (!bdrv_can_snapshot(bs)) {
  1332. error_setg(errp, "Block format '%s' used by device '%s' "
  1333. "does not support internal snapshots",
  1334. bs->drv->format_name, device);
  1335. return;
  1336. }
  1337. if (!strlen(name)) {
  1338. error_setg(errp, "Name is empty");
  1339. return;
  1340. }
  1341. /* check whether a snapshot with name exist */
  1342. ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
  1343. &local_err);
  1344. if (local_err) {
  1345. error_propagate(errp, local_err);
  1346. return;
  1347. } else if (ret) {
  1348. error_setg(errp,
  1349. "Snapshot with name '%s' already exists on device '%s'",
  1350. name, device);
  1351. return;
  1352. }
  1353. /* 3. take the snapshot */
  1354. sn = &state->sn;
  1355. pstrcpy(sn->name, sizeof(sn->name), name);
  1356. qemu_gettimeofday(&tv);
  1357. sn->date_sec = tv.tv_sec;
  1358. sn->date_nsec = tv.tv_usec * 1000;
  1359. sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
  1360. ret1 = bdrv_snapshot_create(bs, sn);
  1361. if (ret1 < 0) {
  1362. error_setg_errno(errp, -ret1,
  1363. "Failed to create snapshot '%s' on device '%s'",
  1364. name, device);
  1365. return;
  1366. }
  1367. /* 4. succeed, mark a snapshot is created */
  1368. state->created = true;
  1369. }
  1370. static void internal_snapshot_abort(BlkActionState *common)
  1371. {
  1372. InternalSnapshotState *state =
  1373. DO_UPCAST(InternalSnapshotState, common, common);
  1374. BlockDriverState *bs = state->bs;
  1375. QEMUSnapshotInfo *sn = &state->sn;
  1376. Error *local_error = NULL;
  1377. if (!state->created) {
  1378. return;
  1379. }
  1380. if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
  1381. error_reportf_err(local_error,
  1382. "Failed to delete snapshot with id '%s' and "
  1383. "name '%s' on device '%s' in abort: ",
  1384. sn->id_str, sn->name,
  1385. bdrv_get_device_name(bs));
  1386. }
  1387. }
  1388. static void internal_snapshot_clean(BlkActionState *common)
  1389. {
  1390. InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
  1391. common, common);
  1392. if (state->aio_context) {
  1393. if (state->bs) {
  1394. bdrv_drained_end(state->bs);
  1395. }
  1396. aio_context_release(state->aio_context);
  1397. }
  1398. }
  1399. /* external snapshot private data */
  1400. typedef struct ExternalSnapshotState {
  1401. BlkActionState common;
  1402. BlockDriverState *old_bs;
  1403. BlockDriverState *new_bs;
  1404. AioContext *aio_context;
  1405. bool overlay_appended;
  1406. } ExternalSnapshotState;
  1407. static void external_snapshot_prepare(BlkActionState *common,
  1408. Error **errp)
  1409. {
  1410. int flags = 0;
  1411. QDict *options = NULL;
  1412. Error *local_err = NULL;
  1413. /* Device and node name of the image to generate the snapshot from */
  1414. const char *device;
  1415. const char *node_name;
  1416. /* Reference to the new image (for 'blockdev-snapshot') */
  1417. const char *snapshot_ref;
  1418. /* File name of the new image (for 'blockdev-snapshot-sync') */
  1419. const char *new_image_file;
  1420. ExternalSnapshotState *state =
  1421. DO_UPCAST(ExternalSnapshotState, common, common);
  1422. TransactionAction *action = common->action;
  1423. /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
  1424. * purpose but a different set of parameters */
  1425. switch (action->type) {
  1426. case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
  1427. {
  1428. BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
  1429. device = s->node;
  1430. node_name = s->node;
  1431. new_image_file = NULL;
  1432. snapshot_ref = s->overlay;
  1433. }
  1434. break;
  1435. case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
  1436. {
  1437. BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
  1438. device = s->has_device ? s->device : NULL;
  1439. node_name = s->has_node_name ? s->node_name : NULL;
  1440. new_image_file = s->snapshot_file;
  1441. snapshot_ref = NULL;
  1442. }
  1443. break;
  1444. default:
  1445. g_assert_not_reached();
  1446. }
  1447. /* start processing */
  1448. if (action_check_completion_mode(common, errp) < 0) {
  1449. return;
  1450. }
  1451. state->old_bs = bdrv_lookup_bs(device, node_name, errp);
  1452. if (!state->old_bs) {
  1453. return;
  1454. }
  1455. /* Acquire AioContext now so any threads operating on old_bs stop */
  1456. state->aio_context = bdrv_get_aio_context(state->old_bs);
  1457. aio_context_acquire(state->aio_context);
  1458. bdrv_drained_begin(state->old_bs);
  1459. if (!bdrv_is_inserted(state->old_bs)) {
  1460. error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
  1461. return;
  1462. }
  1463. if (bdrv_op_is_blocked(state->old_bs,
  1464. BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
  1465. return;
  1466. }
  1467. if (!bdrv_is_read_only(state->old_bs)) {
  1468. if (bdrv_flush(state->old_bs)) {
  1469. error_setg(errp, QERR_IO_ERROR);
  1470. return;
  1471. }
  1472. }
  1473. if (!bdrv_is_first_non_filter(state->old_bs)) {
  1474. error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
  1475. return;
  1476. }
  1477. if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
  1478. BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
  1479. const char *format = s->has_format ? s->format : "qcow2";
  1480. enum NewImageMode mode;
  1481. const char *snapshot_node_name =
  1482. s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
  1483. if (node_name && !snapshot_node_name) {
  1484. error_setg(errp, "New snapshot node name missing");
  1485. return;
  1486. }
  1487. if (snapshot_node_name &&
  1488. bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
  1489. error_setg(errp, "New snapshot node name already in use");
  1490. return;
  1491. }
  1492. flags = state->old_bs->open_flags;
  1493. flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
  1494. /* create new image w/backing file */
  1495. mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
  1496. if (mode != NEW_IMAGE_MODE_EXISTING) {
  1497. int64_t size = bdrv_getlength(state->old_bs);
  1498. if (size < 0) {
  1499. error_setg_errno(errp, -size, "bdrv_getlength failed");
  1500. return;
  1501. }
  1502. bdrv_img_create(new_image_file, format,
  1503. state->old_bs->filename,
  1504. state->old_bs->drv->format_name,
  1505. NULL, size, flags, &local_err, false);
  1506. if (local_err) {
  1507. error_propagate(errp, local_err);
  1508. return;
  1509. }
  1510. }
  1511. options = qdict_new();
  1512. if (s->has_snapshot_node_name) {
  1513. qdict_put_str(options, "node-name", snapshot_node_name);
  1514. }
  1515. qdict_put_str(options, "driver", format);
  1516. flags |= BDRV_O_NO_BACKING;
  1517. }
  1518. state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
  1519. errp);
  1520. /* We will manually add the backing_hd field to the bs later */
  1521. if (!state->new_bs) {
  1522. return;
  1523. }
  1524. if (bdrv_has_blk(state->new_bs)) {
  1525. error_setg(errp, "The snapshot is already in use");
  1526. return;
  1527. }
  1528. if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
  1529. errp)) {
  1530. return;
  1531. }
  1532. if (state->new_bs->backing != NULL) {
  1533. error_setg(errp, "The snapshot already has a backing image");
  1534. return;
  1535. }
  1536. if (!state->new_bs->drv->supports_backing) {
  1537. error_setg(errp, "The snapshot does not support backing images");
  1538. return;
  1539. }
  1540. bdrv_set_aio_context(state->new_bs, state->aio_context);
  1541. /* This removes our old bs and adds the new bs. This is an operation that
  1542. * can fail, so we need to do it in .prepare; undoing it for abort is
  1543. * always possible. */
  1544. bdrv_ref(state->new_bs);
  1545. bdrv_append(state->new_bs, state->old_bs, &local_err);
  1546. if (local_err) {
  1547. error_propagate(errp, local_err);
  1548. return;
  1549. }
  1550. state->overlay_appended = true;
  1551. }
  1552. static void external_snapshot_commit(BlkActionState *common)
  1553. {
  1554. ExternalSnapshotState *state =
  1555. DO_UPCAST(ExternalSnapshotState, common, common);
  1556. /* We don't need (or want) to use the transactional
  1557. * bdrv_reopen_multiple() across all the entries at once, because we
  1558. * don't want to abort all of them if one of them fails the reopen */
  1559. if (!state->old_bs->copy_on_read) {
  1560. bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
  1561. NULL);
  1562. }
  1563. }
  1564. static void external_snapshot_abort(BlkActionState *common)
  1565. {
  1566. ExternalSnapshotState *state =
  1567. DO_UPCAST(ExternalSnapshotState, common, common);
  1568. if (state->new_bs) {
  1569. if (state->overlay_appended) {
  1570. bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
  1571. }
  1572. }
  1573. }
  1574. static void external_snapshot_clean(BlkActionState *common)
  1575. {
  1576. ExternalSnapshotState *state =
  1577. DO_UPCAST(ExternalSnapshotState, common, common);
  1578. if (state->aio_context) {
  1579. bdrv_drained_end(state->old_bs);
  1580. aio_context_release(state->aio_context);
  1581. bdrv_unref(state->new_bs);
  1582. }
  1583. }
  1584. typedef struct DriveBackupState {
  1585. BlkActionState common;
  1586. BlockDriverState *bs;
  1587. AioContext *aio_context;
  1588. BlockJob *job;
  1589. } DriveBackupState;
  1590. static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
  1591. Error **errp);
  1592. static void drive_backup_prepare(BlkActionState *common, Error **errp)
  1593. {
  1594. DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
  1595. BlockDriverState *bs;
  1596. DriveBackup *backup;
  1597. Error *local_err = NULL;
  1598. assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
  1599. backup = common->action->u.drive_backup.data;
  1600. bs = qmp_get_root_bs(backup->device, errp);
  1601. if (!bs) {
  1602. return;
  1603. }
  1604. /* AioContext is released in .clean() */
  1605. state->aio_context = bdrv_get_aio_context(bs);
  1606. aio_context_acquire(state->aio_context);
  1607. bdrv_drained_begin(bs);
  1608. state->bs = bs;
  1609. state->job = do_drive_backup(backup, common->block_job_txn, &local_err);
  1610. if (local_err) {
  1611. error_propagate(errp, local_err);
  1612. return;
  1613. }
  1614. }
  1615. static void drive_backup_commit(BlkActionState *common)
  1616. {
  1617. DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
  1618. assert(state->job);
  1619. block_job_start(state->job);
  1620. }
  1621. static void drive_backup_abort(BlkActionState *common)
  1622. {
  1623. DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
  1624. if (state->job) {
  1625. block_job_cancel_sync(state->job);
  1626. }
  1627. }
  1628. static void drive_backup_clean(BlkActionState *common)
  1629. {
  1630. DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
  1631. if (state->aio_context) {
  1632. bdrv_drained_end(state->bs);
  1633. aio_context_release(state->aio_context);
  1634. }
  1635. }
  1636. typedef struct BlockdevBackupState {
  1637. BlkActionState common;
  1638. BlockDriverState *bs;
  1639. BlockJob *job;
  1640. AioContext *aio_context;
  1641. } BlockdevBackupState;
  1642. static BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
  1643. Error **errp);
  1644. static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
  1645. {
  1646. BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
  1647. BlockdevBackup *backup;
  1648. BlockDriverState *bs, *target;
  1649. Error *local_err = NULL;
  1650. assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
  1651. backup = common->action->u.blockdev_backup.data;
  1652. bs = qmp_get_root_bs(backup->device, errp);
  1653. if (!bs) {
  1654. return;
  1655. }
  1656. target = bdrv_lookup_bs(backup->target, backup->target, errp);
  1657. if (!target) {
  1658. return;
  1659. }
  1660. /* AioContext is released in .clean() */
  1661. state->aio_context = bdrv_get_aio_context(bs);
  1662. if (state->aio_context != bdrv_get_aio_context(target)) {
  1663. state->aio_context = NULL;
  1664. error_setg(errp, "Backup between two IO threads is not implemented");
  1665. return;
  1666. }
  1667. aio_context_acquire(state->aio_context);
  1668. state->bs = bs;
  1669. bdrv_drained_begin(state->bs);
  1670. state->job = do_blockdev_backup(backup, common->block_job_txn, &local_err);
  1671. if (local_err) {
  1672. error_propagate(errp, local_err);
  1673. return;
  1674. }
  1675. }
  1676. static void blockdev_backup_commit(BlkActionState *common)
  1677. {
  1678. BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
  1679. assert(state->job);
  1680. block_job_start(state->job);
  1681. }
  1682. static void blockdev_backup_abort(BlkActionState *common)
  1683. {
  1684. BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
  1685. if (state->job) {
  1686. block_job_cancel_sync(state->job);
  1687. }
  1688. }
  1689. static void blockdev_backup_clean(BlkActionState *common)
  1690. {
  1691. BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
  1692. if (state->aio_context) {
  1693. bdrv_drained_end(state->bs);
  1694. aio_context_release(state->aio_context);
  1695. }
  1696. }
  1697. typedef struct BlockDirtyBitmapState {
  1698. BlkActionState common;
  1699. BdrvDirtyBitmap *bitmap;
  1700. BlockDriverState *bs;
  1701. AioContext *aio_context;
  1702. HBitmap *backup;
  1703. bool prepared;
  1704. } BlockDirtyBitmapState;
  1705. static void block_dirty_bitmap_add_prepare(BlkActionState *common,
  1706. Error **errp)
  1707. {
  1708. Error *local_err = NULL;
  1709. BlockDirtyBitmapAdd *action;
  1710. BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
  1711. common, common);
  1712. if (action_check_completion_mode(common, errp) < 0) {
  1713. return;
  1714. }
  1715. action = common->action->u.block_dirty_bitmap_add.data;
  1716. /* AIO context taken and released within qmp_block_dirty_bitmap_add */
  1717. qmp_block_dirty_bitmap_add(action->node, action->name,
  1718. action->has_granularity, action->granularity,
  1719. &local_err);
  1720. if (!local_err) {
  1721. state->prepared = true;
  1722. } else {
  1723. error_propagate(errp, local_err);
  1724. }
  1725. }
  1726. static void block_dirty_bitmap_add_abort(BlkActionState *common)
  1727. {
  1728. BlockDirtyBitmapAdd *action;
  1729. BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
  1730. common, common);
  1731. action = common->action->u.block_dirty_bitmap_add.data;
  1732. /* Should not be able to fail: IF the bitmap was added via .prepare(),
  1733. * then the node reference and bitmap name must have been valid.
  1734. */
  1735. if (state->prepared) {
  1736. qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
  1737. }
  1738. }
  1739. static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
  1740. Error **errp)
  1741. {
  1742. BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
  1743. common, common);
  1744. BlockDirtyBitmap *action;
  1745. if (action_check_completion_mode(common, errp) < 0) {
  1746. return;
  1747. }
  1748. action = common->action->u.block_dirty_bitmap_clear.data;
  1749. state->bitmap = block_dirty_bitmap_lookup(action->node,
  1750. action->name,
  1751. &state->bs,
  1752. &state->aio_context,
  1753. errp);
  1754. if (!state->bitmap) {
  1755. return;
  1756. }
  1757. if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
  1758. error_setg(errp, "Cannot modify a frozen bitmap");
  1759. return;
  1760. } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
  1761. error_setg(errp, "Cannot clear a disabled bitmap");
  1762. return;
  1763. }
  1764. bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
  1765. /* AioContext is released in .clean() */
  1766. }
  1767. static void block_dirty_bitmap_clear_abort(BlkActionState *common)
  1768. {
  1769. BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
  1770. common, common);
  1771. if (state->backup) {
  1772. bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
  1773. }
  1774. }
  1775. static void block_dirty_bitmap_clear_commit(BlkActionState *common)
  1776. {
  1777. BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
  1778. common, common);
  1779. hbitmap_free(state->backup);
  1780. }
  1781. static void block_dirty_bitmap_clear_clean(BlkActionState *common)
  1782. {
  1783. BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
  1784. common, common);
  1785. if (state->aio_context) {
  1786. aio_context_release(state->aio_context);
  1787. }
  1788. }
  1789. static void abort_prepare(BlkActionState *common, Error **errp)
  1790. {
  1791. error_setg(errp, "Transaction aborted using Abort action");
  1792. }
  1793. static void abort_commit(BlkActionState *common)
  1794. {
  1795. g_assert_not_reached(); /* this action never succeeds */
  1796. }
  1797. static const BlkActionOps actions[] = {
  1798. [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
  1799. .instance_size = sizeof(ExternalSnapshotState),
  1800. .prepare = external_snapshot_prepare,
  1801. .commit = external_snapshot_commit,
  1802. .abort = external_snapshot_abort,
  1803. .clean = external_snapshot_clean,
  1804. },
  1805. [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
  1806. .instance_size = sizeof(ExternalSnapshotState),
  1807. .prepare = external_snapshot_prepare,
  1808. .commit = external_snapshot_commit,
  1809. .abort = external_snapshot_abort,
  1810. .clean = external_snapshot_clean,
  1811. },
  1812. [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
  1813. .instance_size = sizeof(DriveBackupState),
  1814. .prepare = drive_backup_prepare,
  1815. .commit = drive_backup_commit,
  1816. .abort = drive_backup_abort,
  1817. .clean = drive_backup_clean,
  1818. },
  1819. [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
  1820. .instance_size = sizeof(BlockdevBackupState),
  1821. .prepare = blockdev_backup_prepare,
  1822. .commit = blockdev_backup_commit,
  1823. .abort = blockdev_backup_abort,
  1824. .clean = blockdev_backup_clean,
  1825. },
  1826. [TRANSACTION_ACTION_KIND_ABORT] = {
  1827. .instance_size = sizeof(BlkActionState),
  1828. .prepare = abort_prepare,
  1829. .commit = abort_commit,
  1830. },
  1831. [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
  1832. .instance_size = sizeof(InternalSnapshotState),
  1833. .prepare = internal_snapshot_prepare,
  1834. .abort = internal_snapshot_abort,
  1835. .clean = internal_snapshot_clean,
  1836. },
  1837. [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
  1838. .instance_size = sizeof(BlockDirtyBitmapState),
  1839. .prepare = block_dirty_bitmap_add_prepare,
  1840. .abort = block_dirty_bitmap_add_abort,
  1841. },
  1842. [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
  1843. .instance_size = sizeof(BlockDirtyBitmapState),
  1844. .prepare = block_dirty_bitmap_clear_prepare,
  1845. .commit = block_dirty_bitmap_clear_commit,
  1846. .abort = block_dirty_bitmap_clear_abort,
  1847. .clean = block_dirty_bitmap_clear_clean,
  1848. }
  1849. };
  1850. /**
  1851. * Allocate a TransactionProperties structure if necessary, and fill
  1852. * that structure with desired defaults if they are unset.
  1853. */
  1854. static TransactionProperties *get_transaction_properties(
  1855. TransactionProperties *props)
  1856. {
  1857. if (!props) {
  1858. props = g_new0(TransactionProperties, 1);
  1859. }
  1860. if (!props->has_completion_mode) {
  1861. props->has_completion_mode = true;
  1862. props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
  1863. }
  1864. return props;
  1865. }
  1866. /*
  1867. * 'Atomic' group operations. The operations are performed as a set, and if
  1868. * any fail then we roll back all operations in the group.
  1869. */
  1870. void qmp_transaction(TransactionActionList *dev_list,
  1871. bool has_props,
  1872. struct TransactionProperties *props,
  1873. Error **errp)
  1874. {
  1875. TransactionActionList *dev_entry = dev_list;
  1876. BlockJobTxn *block_job_txn = NULL;
  1877. BlkActionState *state, *next;
  1878. Error *local_err = NULL;
  1879. QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
  1880. QSIMPLEQ_INIT(&snap_bdrv_states);
  1881. /* Does this transaction get canceled as a group on failure?
  1882. * If not, we don't really need to make a BlockJobTxn.
  1883. */
  1884. props = get_transaction_properties(props);
  1885. if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
  1886. block_job_txn = block_job_txn_new();
  1887. }
  1888. /* drain all i/o before any operations */
  1889. bdrv_drain_all();
  1890. /* We don't do anything in this loop that commits us to the operations */
  1891. while (NULL != dev_entry) {
  1892. TransactionAction *dev_info = NULL;
  1893. const BlkActionOps *ops;
  1894. dev_info = dev_entry->value;
  1895. dev_entry = dev_entry->next;
  1896. assert(dev_info->type < ARRAY_SIZE(actions));
  1897. ops = &actions[dev_info->type];
  1898. assert(ops->instance_size > 0);
  1899. state = g_malloc0(ops->instance_size);
  1900. state->ops = ops;
  1901. state->action = dev_info;
  1902. state->block_job_txn = block_job_txn;
  1903. state->txn_props = props;
  1904. QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
  1905. state->ops->prepare(state, &local_err);
  1906. if (local_err) {
  1907. error_propagate(errp, local_err);
  1908. goto delete_and_fail;
  1909. }
  1910. }
  1911. QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
  1912. if (state->ops->commit) {
  1913. state->ops->commit(state);
  1914. }
  1915. }
  1916. /* success */
  1917. goto exit;
  1918. delete_and_fail:
  1919. /* failure, and it is all-or-none; roll back all operations */
  1920. QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
  1921. if (state->ops->abort) {
  1922. state->ops->abort(state);
  1923. }
  1924. }
  1925. exit:
  1926. QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
  1927. if (state->ops->clean) {
  1928. state->ops->clean(state);
  1929. }
  1930. g_free(state);
  1931. }
  1932. if (!has_props) {
  1933. qapi_free_TransactionProperties(props);
  1934. }
  1935. block_job_txn_unref(block_job_txn);
  1936. }
  1937. void qmp_eject(bool has_device, const char *device,
  1938. bool has_id, const char *id,
  1939. bool has_force, bool force, Error **errp)
  1940. {
  1941. Error *local_err = NULL;
  1942. int rc;
  1943. if (!has_force) {
  1944. force = false;
  1945. }
  1946. rc = do_open_tray(has_device ? device : NULL,
  1947. has_id ? id : NULL,
  1948. force, &local_err);
  1949. if (rc && rc != -ENOSYS) {
  1950. error_propagate(errp, local_err);
  1951. return;
  1952. }
  1953. error_free(local_err);
  1954. qmp_x_blockdev_remove_medium(has_device, device, has_id, id, errp);
  1955. }
  1956. void qmp_block_passwd(bool has_device, const char *device,
  1957. bool has_node_name, const char *node_name,
  1958. const char *password, Error **errp)
  1959. {
  1960. Error *local_err = NULL;
  1961. BlockDriverState *bs;
  1962. AioContext *aio_context;
  1963. bs = bdrv_lookup_bs(has_device ? device : NULL,
  1964. has_node_name ? node_name : NULL,
  1965. &local_err);
  1966. if (local_err) {
  1967. error_propagate(errp, local_err);
  1968. return;
  1969. }
  1970. aio_context = bdrv_get_aio_context(bs);
  1971. aio_context_acquire(aio_context);
  1972. bdrv_add_key(bs, password, errp);
  1973. aio_context_release(aio_context);
  1974. }
  1975. /*
  1976. * Attempt to open the tray of @device.
  1977. * If @force, ignore its tray lock.
  1978. * Else, if the tray is locked, don't open it, but ask the guest to open it.
  1979. * On error, store an error through @errp and return -errno.
  1980. * If @device does not exist, return -ENODEV.
  1981. * If it has no removable media, return -ENOTSUP.
  1982. * If it has no tray, return -ENOSYS.
  1983. * If the guest was asked to open the tray, return -EINPROGRESS.
  1984. * Else, return 0.
  1985. */
  1986. static int do_open_tray(const char *blk_name, const char *qdev_id,
  1987. bool force, Error **errp)
  1988. {
  1989. BlockBackend *blk;
  1990. const char *device = qdev_id ?: blk_name;
  1991. bool locked;
  1992. blk = qmp_get_blk(blk_name, qdev_id, errp);
  1993. if (!blk) {
  1994. return -ENODEV;
  1995. }
  1996. if (!blk_dev_has_removable_media(blk)) {
  1997. error_setg(errp, "Device '%s' is not removable", device);
  1998. return -ENOTSUP;
  1999. }
  2000. if (!blk_dev_has_tray(blk)) {
  2001. error_setg(errp, "Device '%s' does not have a tray", device);
  2002. return -ENOSYS;
  2003. }
  2004. if (blk_dev_is_tray_open(blk)) {
  2005. return 0;
  2006. }
  2007. locked = blk_dev_is_medium_locked(blk);
  2008. if (locked) {
  2009. blk_dev_eject_request(blk, force);
  2010. }
  2011. if (!locked || force) {
  2012. blk_dev_change_media_cb(blk, false, &error_abort);
  2013. }
  2014. if (locked && !force) {
  2015. error_setg(errp, "Device '%s' is locked and force was not specified, "
  2016. "wait for tray to open and try again", device);
  2017. return -EINPROGRESS;
  2018. }
  2019. return 0;
  2020. }
  2021. void qmp_blockdev_open_tray(bool has_device, const char *device,
  2022. bool has_id, const char *id,
  2023. bool has_force, bool force,
  2024. Error **errp)
  2025. {
  2026. Error *local_err = NULL;
  2027. int rc;
  2028. if (!has_force) {
  2029. force = false;
  2030. }
  2031. rc = do_open_tray(has_device ? device : NULL,
  2032. has_id ? id : NULL,
  2033. force, &local_err);
  2034. if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
  2035. error_propagate(errp, local_err);
  2036. return;
  2037. }
  2038. error_free(local_err);
  2039. }
  2040. void qmp_blockdev_close_tray(bool has_device, const char *device,
  2041. bool has_id, const char *id,
  2042. Error **errp)
  2043. {
  2044. BlockBackend *blk;
  2045. Error *local_err = NULL;
  2046. device = has_device ? device : NULL;
  2047. id = has_id ? id : NULL;
  2048. blk = qmp_get_blk(device, id, errp);
  2049. if (!blk) {
  2050. return;
  2051. }
  2052. if (!blk_dev_has_removable_media(blk)) {
  2053. error_setg(errp, "Device '%s' is not removable", device ?: id);
  2054. return;
  2055. }
  2056. if (!blk_dev_has_tray(blk)) {
  2057. /* Ignore this command on tray-less devices */
  2058. return;
  2059. }
  2060. if (!blk_dev_is_tray_open(blk)) {
  2061. return;
  2062. }
  2063. blk_dev_change_media_cb(blk, true, &local_err);
  2064. if (local_err) {
  2065. error_propagate(errp, local_err);
  2066. return;
  2067. }
  2068. }
  2069. void qmp_x_blockdev_remove_medium(bool has_device, const char *device,
  2070. bool has_id, const char *id, Error **errp)
  2071. {
  2072. BlockBackend *blk;
  2073. BlockDriverState *bs;
  2074. AioContext *aio_context;
  2075. bool has_attached_device;
  2076. device = has_device ? device : NULL;
  2077. id = has_id ? id : NULL;
  2078. blk = qmp_get_blk(device, id, errp);
  2079. if (!blk) {
  2080. return;
  2081. }
  2082. /* For BBs without a device, we can exchange the BDS tree at will */
  2083. has_attached_device = blk_get_attached_dev(blk);
  2084. if (has_attached_device && !blk_dev_has_removable_media(blk)) {
  2085. error_setg(errp, "Device '%s' is not removable", device ?: id);
  2086. return;
  2087. }
  2088. if (has_attached_device && blk_dev_has_tray(blk) &&
  2089. !blk_dev_is_tray_open(blk))
  2090. {
  2091. error_setg(errp, "Tray of device '%s' is not open", device ?: id);
  2092. return;
  2093. }
  2094. bs = blk_bs(blk);
  2095. if (!bs) {
  2096. return;
  2097. }
  2098. aio_context = bdrv_get_aio_context(bs);
  2099. aio_context_acquire(aio_context);
  2100. if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
  2101. goto out;
  2102. }
  2103. blk_remove_bs(blk);
  2104. if (!blk_dev_has_tray(blk)) {
  2105. /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
  2106. * called at all); therefore, the medium needs to be ejected here.
  2107. * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
  2108. * value passed here (i.e. false). */
  2109. blk_dev_change_media_cb(blk, false, &error_abort);
  2110. }
  2111. out:
  2112. aio_context_release(aio_context);
  2113. }
  2114. static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
  2115. BlockDriverState *bs, Error **errp)
  2116. {
  2117. Error *local_err = NULL;
  2118. bool has_device;
  2119. int ret;
  2120. /* For BBs without a device, we can exchange the BDS tree at will */
  2121. has_device = blk_get_attached_dev(blk);
  2122. if (has_device && !blk_dev_has_removable_media(blk)) {
  2123. error_setg(errp, "Device is not removable");
  2124. return;
  2125. }
  2126. if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
  2127. error_setg(errp, "Tray of the device is not open");
  2128. return;
  2129. }
  2130. if (blk_bs(blk)) {
  2131. error_setg(errp, "There already is a medium in the device");
  2132. return;
  2133. }
  2134. ret = blk_insert_bs(blk, bs, errp);
  2135. if (ret < 0) {
  2136. return;
  2137. }
  2138. if (!blk_dev_has_tray(blk)) {
  2139. /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
  2140. * called at all); therefore, the medium needs to be pushed into the
  2141. * slot here.
  2142. * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
  2143. * value passed here (i.e. true). */
  2144. blk_dev_change_media_cb(blk, true, &local_err);
  2145. if (local_err) {
  2146. error_propagate(errp, local_err);
  2147. blk_remove_bs(blk);
  2148. return;
  2149. }
  2150. }
  2151. }
  2152. void qmp_x_blockdev_insert_medium(bool has_device, const char *device,
  2153. bool has_id, const char *id,
  2154. const char *node_name, Error **errp)
  2155. {
  2156. BlockBackend *blk;
  2157. BlockDriverState *bs;
  2158. blk = qmp_get_blk(has_device ? device : NULL,
  2159. has_id ? id : NULL,
  2160. errp);
  2161. if (!blk) {
  2162. return;
  2163. }
  2164. bs = bdrv_find_node(node_name);
  2165. if (!bs) {
  2166. error_setg(errp, "Node '%s' not found", node_name);
  2167. return;
  2168. }
  2169. if (bdrv_has_blk(bs)) {
  2170. error_setg(errp, "Node '%s' is already in use", node_name);
  2171. return;
  2172. }
  2173. qmp_blockdev_insert_anon_medium(blk, bs, errp);
  2174. }
  2175. void qmp_blockdev_change_medium(bool has_device, const char *device,
  2176. bool has_id, const char *id,
  2177. const char *filename,
  2178. bool has_format, const char *format,
  2179. bool has_read_only,
  2180. BlockdevChangeReadOnlyMode read_only,
  2181. Error **errp)
  2182. {
  2183. BlockBackend *blk;
  2184. BlockDriverState *medium_bs = NULL;
  2185. int bdrv_flags;
  2186. bool detect_zeroes;
  2187. int rc;
  2188. QDict *options = NULL;
  2189. Error *err = NULL;
  2190. blk = qmp_get_blk(has_device ? device : NULL,
  2191. has_id ? id : NULL,
  2192. errp);
  2193. if (!blk) {
  2194. goto fail;
  2195. }
  2196. if (blk_bs(blk)) {
  2197. blk_update_root_state(blk);
  2198. }
  2199. bdrv_flags = blk_get_open_flags_from_root_state(blk);
  2200. bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
  2201. BDRV_O_PROTOCOL);
  2202. if (!has_read_only) {
  2203. read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
  2204. }
  2205. switch (read_only) {
  2206. case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
  2207. break;
  2208. case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
  2209. bdrv_flags &= ~BDRV_O_RDWR;
  2210. break;
  2211. case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
  2212. bdrv_flags |= BDRV_O_RDWR;
  2213. break;
  2214. default:
  2215. abort();
  2216. }
  2217. options = qdict_new();
  2218. detect_zeroes = blk_get_detect_zeroes_from_root_state(blk);
  2219. qdict_put_str(options, "detect-zeroes", detect_zeroes ? "on" : "off");
  2220. if (has_format) {
  2221. qdict_put_str(options, "driver", format);
  2222. }
  2223. medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
  2224. if (!medium_bs) {
  2225. goto fail;
  2226. }
  2227. bdrv_add_key(medium_bs, NULL, &err);
  2228. if (err) {
  2229. error_propagate(errp, err);
  2230. goto fail;
  2231. }
  2232. rc = do_open_tray(has_device ? device : NULL,
  2233. has_id ? id : NULL,
  2234. false, &err);
  2235. if (rc && rc != -ENOSYS) {
  2236. error_propagate(errp, err);
  2237. goto fail;
  2238. }
  2239. error_free(err);
  2240. err = NULL;
  2241. qmp_x_blockdev_remove_medium(has_device, device, has_id, id, &err);
  2242. if (err) {
  2243. error_propagate(errp, err);
  2244. goto fail;
  2245. }
  2246. qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
  2247. if (err) {
  2248. error_propagate(errp, err);
  2249. goto fail;
  2250. }
  2251. qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
  2252. fail:
  2253. /* If the medium has been inserted, the device has its own reference, so
  2254. * ours must be relinquished; and if it has not been inserted successfully,
  2255. * the reference must be relinquished anyway */
  2256. bdrv_unref(medium_bs);
  2257. }
  2258. /* throttling disk I/O limits */
  2259. void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
  2260. {
  2261. ThrottleConfig cfg;
  2262. BlockDriverState *bs;
  2263. BlockBackend *blk;
  2264. AioContext *aio_context;
  2265. blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
  2266. arg->has_id ? arg->id : NULL,
  2267. errp);
  2268. if (!blk) {
  2269. return;
  2270. }
  2271. aio_context = blk_get_aio_context(blk);
  2272. aio_context_acquire(aio_context);
  2273. bs = blk_bs(blk);
  2274. if (!bs) {
  2275. error_setg(errp, "Device has no medium");
  2276. goto out;
  2277. }
  2278. throttle_config_init(&cfg);
  2279. cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
  2280. cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
  2281. cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
  2282. cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
  2283. cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
  2284. cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
  2285. if (arg->has_bps_max) {
  2286. cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
  2287. }
  2288. if (arg->has_bps_rd_max) {
  2289. cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
  2290. }
  2291. if (arg->has_bps_wr_max) {
  2292. cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
  2293. }
  2294. if (arg->has_iops_max) {
  2295. cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
  2296. }
  2297. if (arg->has_iops_rd_max) {
  2298. cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
  2299. }
  2300. if (arg->has_iops_wr_max) {
  2301. cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
  2302. }
  2303. if (arg->has_bps_max_length) {
  2304. cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
  2305. }
  2306. if (arg->has_bps_rd_max_length) {
  2307. cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
  2308. }
  2309. if (arg->has_bps_wr_max_length) {
  2310. cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
  2311. }
  2312. if (arg->has_iops_max_length) {
  2313. cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
  2314. }
  2315. if (arg->has_iops_rd_max_length) {
  2316. cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
  2317. }
  2318. if (arg->has_iops_wr_max_length) {
  2319. cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
  2320. }
  2321. if (arg->has_iops_size) {
  2322. cfg.op_size = arg->iops_size;
  2323. }
  2324. if (!throttle_is_valid(&cfg, errp)) {
  2325. goto out;
  2326. }
  2327. if (throttle_enabled(&cfg)) {
  2328. /* Enable I/O limits if they're not enabled yet, otherwise
  2329. * just update the throttling group. */
  2330. if (!blk_get_public(blk)->throttle_state) {
  2331. blk_io_limits_enable(blk,
  2332. arg->has_group ? arg->group :
  2333. arg->has_device ? arg->device :
  2334. arg->id);
  2335. } else if (arg->has_group) {
  2336. blk_io_limits_update_group(blk, arg->group);
  2337. }
  2338. /* Set the new throttling configuration */
  2339. blk_set_io_limits(blk, &cfg);
  2340. } else if (blk_get_public(blk)->throttle_state) {
  2341. /* If all throttling settings are set to 0, disable I/O limits */
  2342. blk_io_limits_disable(blk);
  2343. }
  2344. out:
  2345. aio_context_release(aio_context);
  2346. }
  2347. void qmp_block_dirty_bitmap_add(const char *node, const char *name,
  2348. bool has_granularity, uint32_t granularity,
  2349. Error **errp)
  2350. {
  2351. AioContext *aio_context;
  2352. BlockDriverState *bs;
  2353. if (!name || name[0] == '\0') {
  2354. error_setg(errp, "Bitmap name cannot be empty");
  2355. return;
  2356. }
  2357. bs = bdrv_lookup_bs(node, node, errp);
  2358. if (!bs) {
  2359. return;
  2360. }
  2361. aio_context = bdrv_get_aio_context(bs);
  2362. aio_context_acquire(aio_context);
  2363. if (has_granularity) {
  2364. if (granularity < 512 || !is_power_of_2(granularity)) {
  2365. error_setg(errp, "Granularity must be power of 2 "
  2366. "and at least 512");
  2367. goto out;
  2368. }
  2369. } else {
  2370. /* Default to cluster size, if available: */
  2371. granularity = bdrv_get_default_bitmap_granularity(bs);
  2372. }
  2373. bdrv_create_dirty_bitmap(bs, granularity, name, errp);
  2374. out:
  2375. aio_context_release(aio_context);
  2376. }
  2377. void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
  2378. Error **errp)
  2379. {
  2380. AioContext *aio_context;
  2381. BlockDriverState *bs;
  2382. BdrvDirtyBitmap *bitmap;
  2383. bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
  2384. if (!bitmap || !bs) {
  2385. return;
  2386. }
  2387. if (bdrv_dirty_bitmap_frozen(bitmap)) {
  2388. error_setg(errp,
  2389. "Bitmap '%s' is currently frozen and cannot be removed",
  2390. name);
  2391. goto out;
  2392. }
  2393. bdrv_dirty_bitmap_make_anon(bitmap);
  2394. bdrv_release_dirty_bitmap(bs, bitmap);
  2395. out:
  2396. aio_context_release(aio_context);
  2397. }
  2398. /**
  2399. * Completely clear a bitmap, for the purposes of synchronizing a bitmap
  2400. * immediately after a full backup operation.
  2401. */
  2402. void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
  2403. Error **errp)
  2404. {
  2405. AioContext *aio_context;
  2406. BdrvDirtyBitmap *bitmap;
  2407. BlockDriverState *bs;
  2408. bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
  2409. if (!bitmap || !bs) {
  2410. return;
  2411. }
  2412. if (bdrv_dirty_bitmap_frozen(bitmap)) {
  2413. error_setg(errp,
  2414. "Bitmap '%s' is currently frozen and cannot be modified",
  2415. name);
  2416. goto out;
  2417. } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
  2418. error_setg(errp,
  2419. "Bitmap '%s' is currently disabled and cannot be cleared",
  2420. name);
  2421. goto out;
  2422. }
  2423. bdrv_clear_dirty_bitmap(bitmap, NULL);
  2424. out:
  2425. aio_context_release(aio_context);
  2426. }
  2427. void hmp_drive_del(Monitor *mon, const QDict *qdict)
  2428. {
  2429. const char *id = qdict_get_str(qdict, "id");
  2430. BlockBackend *blk;
  2431. BlockDriverState *bs;
  2432. AioContext *aio_context;
  2433. Error *local_err = NULL;
  2434. bs = bdrv_find_node(id);
  2435. if (bs) {
  2436. qmp_blockdev_del(id, &local_err);
  2437. if (local_err) {
  2438. error_report_err(local_err);
  2439. }
  2440. return;
  2441. }
  2442. blk = blk_by_name(id);
  2443. if (!blk) {
  2444. error_report("Device '%s' not found", id);
  2445. return;
  2446. }
  2447. if (!blk_legacy_dinfo(blk)) {
  2448. error_report("Deleting device added with blockdev-add"
  2449. " is not supported");
  2450. return;
  2451. }
  2452. aio_context = blk_get_aio_context(blk);
  2453. aio_context_acquire(aio_context);
  2454. bs = blk_bs(blk);
  2455. if (bs) {
  2456. if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
  2457. error_report_err(local_err);
  2458. aio_context_release(aio_context);
  2459. return;
  2460. }
  2461. blk_remove_bs(blk);
  2462. }
  2463. /* Make the BlockBackend and the attached BlockDriverState anonymous */
  2464. monitor_remove_blk(blk);
  2465. /* If this BlockBackend has a device attached to it, its refcount will be
  2466. * decremented when the device is removed; otherwise we have to do so here.
  2467. */
  2468. if (blk_get_attached_dev(blk)) {
  2469. /* Further I/O must not pause the guest */
  2470. blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
  2471. BLOCKDEV_ON_ERROR_REPORT);
  2472. } else {
  2473. blk_unref(blk);
  2474. }
  2475. aio_context_release(aio_context);
  2476. }
  2477. void qmp_block_resize(bool has_device, const char *device,
  2478. bool has_node_name, const char *node_name,
  2479. int64_t size, Error **errp)
  2480. {
  2481. Error *local_err = NULL;
  2482. BlockBackend *blk = NULL;
  2483. BlockDriverState *bs;
  2484. AioContext *aio_context;
  2485. int ret;
  2486. bs = bdrv_lookup_bs(has_device ? device : NULL,
  2487. has_node_name ? node_name : NULL,
  2488. &local_err);
  2489. if (local_err) {
  2490. error_propagate(errp, local_err);
  2491. return;
  2492. }
  2493. aio_context = bdrv_get_aio_context(bs);
  2494. aio_context_acquire(aio_context);
  2495. if (!bdrv_is_first_non_filter(bs)) {
  2496. error_setg(errp, QERR_FEATURE_DISABLED, "resize");
  2497. goto out;
  2498. }
  2499. if (size < 0) {
  2500. error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
  2501. goto out;
  2502. }
  2503. if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
  2504. error_setg(errp, QERR_DEVICE_IN_USE, device);
  2505. goto out;
  2506. }
  2507. blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
  2508. ret = blk_insert_bs(blk, bs, errp);
  2509. if (ret < 0) {
  2510. goto out;
  2511. }
  2512. bdrv_drained_begin(bs);
  2513. ret = blk_truncate(blk, size, errp);
  2514. bdrv_drained_end(bs);
  2515. out:
  2516. blk_unref(blk);
  2517. aio_context_release(aio_context);
  2518. }
  2519. void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
  2520. bool has_base, const char *base,
  2521. bool has_base_node, const char *base_node,
  2522. bool has_backing_file, const char *backing_file,
  2523. bool has_speed, int64_t speed,
  2524. bool has_on_error, BlockdevOnError on_error,
  2525. Error **errp)
  2526. {
  2527. BlockDriverState *bs, *iter;
  2528. BlockDriverState *base_bs = NULL;
  2529. AioContext *aio_context;
  2530. Error *local_err = NULL;
  2531. const char *base_name = NULL;
  2532. if (!has_on_error) {
  2533. on_error = BLOCKDEV_ON_ERROR_REPORT;
  2534. }
  2535. bs = bdrv_lookup_bs(device, device, errp);
  2536. if (!bs) {
  2537. return;
  2538. }
  2539. aio_context = bdrv_get_aio_context(bs);
  2540. aio_context_acquire(aio_context);
  2541. if (has_base && has_base_node) {
  2542. error_setg(errp, "'base' and 'base-node' cannot be specified "
  2543. "at the same time");
  2544. goto out;
  2545. }
  2546. if (has_base) {
  2547. base_bs = bdrv_find_backing_image(bs, base);
  2548. if (base_bs == NULL) {
  2549. error_setg(errp, QERR_BASE_NOT_FOUND, base);
  2550. goto out;
  2551. }
  2552. assert(bdrv_get_aio_context(base_bs) == aio_context);
  2553. base_name = base;
  2554. }
  2555. if (has_base_node) {
  2556. base_bs = bdrv_lookup_bs(NULL, base_node, errp);
  2557. if (!base_bs) {
  2558. goto out;
  2559. }
  2560. if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
  2561. error_setg(errp, "Node '%s' is not a backing image of '%s'",
  2562. base_node, device);
  2563. goto out;
  2564. }
  2565. assert(bdrv_get_aio_context(base_bs) == aio_context);
  2566. base_name = base_bs->filename;
  2567. }
  2568. /* Check for op blockers in the whole chain between bs and base */
  2569. for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
  2570. if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
  2571. goto out;
  2572. }
  2573. }
  2574. /* if we are streaming the entire chain, the result will have no backing
  2575. * file, and specifying one is therefore an error */
  2576. if (base_bs == NULL && has_backing_file) {
  2577. error_setg(errp, "backing file specified, but streaming the "
  2578. "entire chain");
  2579. goto out;
  2580. }
  2581. /* backing_file string overrides base bs filename */
  2582. base_name = has_backing_file ? backing_file : base_name;
  2583. stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
  2584. has_speed ? speed : 0, on_error, &local_err);
  2585. if (local_err) {
  2586. error_propagate(errp, local_err);
  2587. goto out;
  2588. }
  2589. trace_qmp_block_stream(bs, bs->job);
  2590. out:
  2591. aio_context_release(aio_context);
  2592. }
  2593. void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
  2594. bool has_base, const char *base,
  2595. bool has_top, const char *top,
  2596. bool has_backing_file, const char *backing_file,
  2597. bool has_speed, int64_t speed,
  2598. bool has_filter_node_name, const char *filter_node_name,
  2599. Error **errp)
  2600. {
  2601. BlockDriverState *bs;
  2602. BlockDriverState *iter;
  2603. BlockDriverState *base_bs, *top_bs;
  2604. AioContext *aio_context;
  2605. Error *local_err = NULL;
  2606. /* This will be part of the QMP command, if/when the
  2607. * BlockdevOnError change for blkmirror makes it in
  2608. */
  2609. BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
  2610. if (!has_speed) {
  2611. speed = 0;
  2612. }
  2613. if (!has_filter_node_name) {
  2614. filter_node_name = NULL;
  2615. }
  2616. /* Important Note:
  2617. * libvirt relies on the DeviceNotFound error class in order to probe for
  2618. * live commit feature versions; for this to work, we must make sure to
  2619. * perform the device lookup before any generic errors that may occur in a
  2620. * scenario in which all optional arguments are omitted. */
  2621. bs = qmp_get_root_bs(device, &local_err);
  2622. if (!bs) {
  2623. bs = bdrv_lookup_bs(device, device, NULL);
  2624. if (!bs) {
  2625. error_free(local_err);
  2626. error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
  2627. "Device '%s' not found", device);
  2628. } else {
  2629. error_propagate(errp, local_err);
  2630. }
  2631. return;
  2632. }
  2633. aio_context = bdrv_get_aio_context(bs);
  2634. aio_context_acquire(aio_context);
  2635. if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
  2636. goto out;
  2637. }
  2638. /* default top_bs is the active layer */
  2639. top_bs = bs;
  2640. if (has_top && top) {
  2641. if (strcmp(bs->filename, top) != 0) {
  2642. top_bs = bdrv_find_backing_image(bs, top);
  2643. }
  2644. }
  2645. if (top_bs == NULL) {
  2646. error_setg(errp, "Top image file %s not found", top ? top : "NULL");
  2647. goto out;
  2648. }
  2649. assert(bdrv_get_aio_context(top_bs) == aio_context);
  2650. if (has_base && base) {
  2651. base_bs = bdrv_find_backing_image(top_bs, base);
  2652. } else {
  2653. base_bs = bdrv_find_base(top_bs);
  2654. }
  2655. if (base_bs == NULL) {
  2656. error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
  2657. goto out;
  2658. }
  2659. assert(bdrv_get_aio_context(base_bs) == aio_context);
  2660. for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
  2661. if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
  2662. goto out;
  2663. }
  2664. }
  2665. /* Do not allow attempts to commit an image into itself */
  2666. if (top_bs == base_bs) {
  2667. error_setg(errp, "cannot commit an image into itself");
  2668. goto out;
  2669. }
  2670. if (top_bs == bs) {
  2671. if (has_backing_file) {
  2672. error_setg(errp, "'backing-file' specified,"
  2673. " but 'top' is the active layer");
  2674. goto out;
  2675. }
  2676. commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
  2677. BLOCK_JOB_DEFAULT, speed, on_error,
  2678. filter_node_name, NULL, NULL, &local_err, false);
  2679. } else {
  2680. BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
  2681. if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
  2682. goto out;
  2683. }
  2684. commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
  2685. on_error, has_backing_file ? backing_file : NULL,
  2686. filter_node_name, &local_err);
  2687. }
  2688. if (local_err != NULL) {
  2689. error_propagate(errp, local_err);
  2690. goto out;
  2691. }
  2692. out:
  2693. aio_context_release(aio_context);
  2694. }
  2695. static BlockJob *do_drive_backup(DriveBackup *backup, BlockJobTxn *txn,
  2696. Error **errp)
  2697. {
  2698. BlockDriverState *bs;
  2699. BlockDriverState *target_bs;
  2700. BlockDriverState *source = NULL;
  2701. BlockJob *job = NULL;
  2702. BdrvDirtyBitmap *bmap = NULL;
  2703. AioContext *aio_context;
  2704. QDict *options = NULL;
  2705. Error *local_err = NULL;
  2706. int flags;
  2707. int64_t size;
  2708. bool set_backing_hd = false;
  2709. if (!backup->has_speed) {
  2710. backup->speed = 0;
  2711. }
  2712. if (!backup->has_on_source_error) {
  2713. backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
  2714. }
  2715. if (!backup->has_on_target_error) {
  2716. backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
  2717. }
  2718. if (!backup->has_mode) {
  2719. backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
  2720. }
  2721. if (!backup->has_job_id) {
  2722. backup->job_id = NULL;
  2723. }
  2724. if (!backup->has_compress) {
  2725. backup->compress = false;
  2726. }
  2727. bs = qmp_get_root_bs(backup->device, errp);
  2728. if (!bs) {
  2729. return NULL;
  2730. }
  2731. aio_context = bdrv_get_aio_context(bs);
  2732. aio_context_acquire(aio_context);
  2733. if (!backup->has_format) {
  2734. backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
  2735. NULL : (char*) bs->drv->format_name;
  2736. }
  2737. /* Early check to avoid creating target */
  2738. if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
  2739. goto out;
  2740. }
  2741. flags = bs->open_flags | BDRV_O_RDWR;
  2742. /* See if we have a backing HD we can use to create our new image
  2743. * on top of. */
  2744. if (backup->sync == MIRROR_SYNC_MODE_TOP) {
  2745. source = backing_bs(bs);
  2746. if (!source) {
  2747. backup->sync = MIRROR_SYNC_MODE_FULL;
  2748. }
  2749. }
  2750. if (backup->sync == MIRROR_SYNC_MODE_NONE) {
  2751. source = bs;
  2752. flags |= BDRV_O_NO_BACKING;
  2753. set_backing_hd = true;
  2754. }
  2755. size = bdrv_getlength(bs);
  2756. if (size < 0) {
  2757. error_setg_errno(errp, -size, "bdrv_getlength failed");
  2758. goto out;
  2759. }
  2760. if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
  2761. assert(backup->format);
  2762. if (source) {
  2763. bdrv_img_create(backup->target, backup->format, source->filename,
  2764. source->drv->format_name, NULL,
  2765. size, flags, &local_err, false);
  2766. } else {
  2767. bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
  2768. size, flags, &local_err, false);
  2769. }
  2770. }
  2771. if (local_err) {
  2772. error_propagate(errp, local_err);
  2773. goto out;
  2774. }
  2775. if (backup->format) {
  2776. if (!options) {
  2777. options = qdict_new();
  2778. }
  2779. qdict_put_str(options, "driver", backup->format);
  2780. }
  2781. target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
  2782. if (!target_bs) {
  2783. goto out;
  2784. }
  2785. bdrv_set_aio_context(target_bs, aio_context);
  2786. if (set_backing_hd) {
  2787. bdrv_set_backing_hd(target_bs, source, &local_err);
  2788. if (local_err) {
  2789. bdrv_unref(target_bs);
  2790. goto out;
  2791. }
  2792. }
  2793. if (backup->has_bitmap) {
  2794. bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
  2795. if (!bmap) {
  2796. error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
  2797. bdrv_unref(target_bs);
  2798. goto out;
  2799. }
  2800. }
  2801. job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
  2802. backup->sync, bmap, backup->compress,
  2803. backup->on_source_error, backup->on_target_error,
  2804. BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
  2805. bdrv_unref(target_bs);
  2806. if (local_err != NULL) {
  2807. error_propagate(errp, local_err);
  2808. goto out;
  2809. }
  2810. out:
  2811. aio_context_release(aio_context);
  2812. return job;
  2813. }
  2814. void qmp_drive_backup(DriveBackup *arg, Error **errp)
  2815. {
  2816. BlockJob *job;
  2817. job = do_drive_backup(arg, NULL, errp);
  2818. if (job) {
  2819. block_job_start(job);
  2820. }
  2821. }
  2822. BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
  2823. {
  2824. return bdrv_named_nodes_list(errp);
  2825. }
  2826. BlockJob *do_blockdev_backup(BlockdevBackup *backup, BlockJobTxn *txn,
  2827. Error **errp)
  2828. {
  2829. BlockDriverState *bs;
  2830. BlockDriverState *target_bs;
  2831. Error *local_err = NULL;
  2832. AioContext *aio_context;
  2833. BlockJob *job = NULL;
  2834. if (!backup->has_speed) {
  2835. backup->speed = 0;
  2836. }
  2837. if (!backup->has_on_source_error) {
  2838. backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
  2839. }
  2840. if (!backup->has_on_target_error) {
  2841. backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
  2842. }
  2843. if (!backup->has_job_id) {
  2844. backup->job_id = NULL;
  2845. }
  2846. if (!backup->has_compress) {
  2847. backup->compress = false;
  2848. }
  2849. bs = qmp_get_root_bs(backup->device, errp);
  2850. if (!bs) {
  2851. return NULL;
  2852. }
  2853. aio_context = bdrv_get_aio_context(bs);
  2854. aio_context_acquire(aio_context);
  2855. target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
  2856. if (!target_bs) {
  2857. goto out;
  2858. }
  2859. if (bdrv_get_aio_context(target_bs) != aio_context) {
  2860. if (!bdrv_has_blk(target_bs)) {
  2861. /* The target BDS is not attached, we can safely move it to another
  2862. * AioContext. */
  2863. bdrv_set_aio_context(target_bs, aio_context);
  2864. } else {
  2865. error_setg(errp, "Target is attached to a different thread from "
  2866. "source.");
  2867. goto out;
  2868. }
  2869. }
  2870. job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
  2871. backup->sync, NULL, backup->compress,
  2872. backup->on_source_error, backup->on_target_error,
  2873. BLOCK_JOB_DEFAULT, NULL, NULL, txn, &local_err);
  2874. if (local_err != NULL) {
  2875. error_propagate(errp, local_err);
  2876. }
  2877. out:
  2878. aio_context_release(aio_context);
  2879. return job;
  2880. }
  2881. void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)
  2882. {
  2883. BlockJob *job;
  2884. job = do_blockdev_backup(arg, NULL, errp);
  2885. if (job) {
  2886. block_job_start(job);
  2887. }
  2888. }
  2889. /* Parameter check and block job starting for drive mirroring.
  2890. * Caller should hold @device and @target's aio context (must be the same).
  2891. **/
  2892. static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
  2893. BlockDriverState *target,
  2894. bool has_replaces, const char *replaces,
  2895. enum MirrorSyncMode sync,
  2896. BlockMirrorBackingMode backing_mode,
  2897. bool has_speed, int64_t speed,
  2898. bool has_granularity, uint32_t granularity,
  2899. bool has_buf_size, int64_t buf_size,
  2900. bool has_on_source_error,
  2901. BlockdevOnError on_source_error,
  2902. bool has_on_target_error,
  2903. BlockdevOnError on_target_error,
  2904. bool has_unmap, bool unmap,
  2905. bool has_filter_node_name,
  2906. const char *filter_node_name,
  2907. Error **errp)
  2908. {
  2909. if (!has_speed) {
  2910. speed = 0;
  2911. }
  2912. if (!has_on_source_error) {
  2913. on_source_error = BLOCKDEV_ON_ERROR_REPORT;
  2914. }
  2915. if (!has_on_target_error) {
  2916. on_target_error = BLOCKDEV_ON_ERROR_REPORT;
  2917. }
  2918. if (!has_granularity) {
  2919. granularity = 0;
  2920. }
  2921. if (!has_buf_size) {
  2922. buf_size = 0;
  2923. }
  2924. if (!has_unmap) {
  2925. unmap = true;
  2926. }
  2927. if (!has_filter_node_name) {
  2928. filter_node_name = NULL;
  2929. }
  2930. if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
  2931. error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
  2932. "a value in range [512B, 64MB]");
  2933. return;
  2934. }
  2935. if (granularity & (granularity - 1)) {
  2936. error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
  2937. "power of 2");
  2938. return;
  2939. }
  2940. if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
  2941. return;
  2942. }
  2943. if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
  2944. return;
  2945. }
  2946. if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
  2947. sync = MIRROR_SYNC_MODE_FULL;
  2948. }
  2949. /* pass the node name to replace to mirror start since it's loose coupling
  2950. * and will allow to check whether the node still exist at mirror completion
  2951. */
  2952. mirror_start(job_id, bs, target,
  2953. has_replaces ? replaces : NULL,
  2954. speed, granularity, buf_size, sync, backing_mode,
  2955. on_source_error, on_target_error, unmap, filter_node_name,
  2956. errp);
  2957. }
  2958. void qmp_drive_mirror(DriveMirror *arg, Error **errp)
  2959. {
  2960. BlockDriverState *bs;
  2961. BlockDriverState *source, *target_bs;
  2962. AioContext *aio_context;
  2963. BlockMirrorBackingMode backing_mode;
  2964. Error *local_err = NULL;
  2965. QDict *options = NULL;
  2966. int flags;
  2967. int64_t size;
  2968. const char *format = arg->format;
  2969. bs = qmp_get_root_bs(arg->device, errp);
  2970. if (!bs) {
  2971. return;
  2972. }
  2973. aio_context = bdrv_get_aio_context(bs);
  2974. aio_context_acquire(aio_context);
  2975. if (!arg->has_mode) {
  2976. arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
  2977. }
  2978. if (!arg->has_format) {
  2979. format = (arg->mode == NEW_IMAGE_MODE_EXISTING
  2980. ? NULL : bs->drv->format_name);
  2981. }
  2982. flags = bs->open_flags | BDRV_O_RDWR;
  2983. source = backing_bs(bs);
  2984. if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
  2985. arg->sync = MIRROR_SYNC_MODE_FULL;
  2986. }
  2987. if (arg->sync == MIRROR_SYNC_MODE_NONE) {
  2988. source = bs;
  2989. }
  2990. size = bdrv_getlength(bs);
  2991. if (size < 0) {
  2992. error_setg_errno(errp, -size, "bdrv_getlength failed");
  2993. goto out;
  2994. }
  2995. if (arg->has_replaces) {
  2996. BlockDriverState *to_replace_bs;
  2997. AioContext *replace_aio_context;
  2998. int64_t replace_size;
  2999. if (!arg->has_node_name) {
  3000. error_setg(errp, "a node-name must be provided when replacing a"
  3001. " named node of the graph");
  3002. goto out;
  3003. }
  3004. to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
  3005. if (!to_replace_bs) {
  3006. error_propagate(errp, local_err);
  3007. goto out;
  3008. }
  3009. replace_aio_context = bdrv_get_aio_context(to_replace_bs);
  3010. aio_context_acquire(replace_aio_context);
  3011. replace_size = bdrv_getlength(to_replace_bs);
  3012. aio_context_release(replace_aio_context);
  3013. if (size != replace_size) {
  3014. error_setg(errp, "cannot replace image with a mirror image of "
  3015. "different size");
  3016. goto out;
  3017. }
  3018. }
  3019. if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
  3020. backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
  3021. } else {
  3022. backing_mode = MIRROR_OPEN_BACKING_CHAIN;
  3023. }
  3024. if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
  3025. && arg->mode != NEW_IMAGE_MODE_EXISTING)
  3026. {
  3027. /* create new image w/o backing file */
  3028. assert(format);
  3029. bdrv_img_create(arg->target, format,
  3030. NULL, NULL, NULL, size, flags, &local_err, false);
  3031. } else {
  3032. switch (arg->mode) {
  3033. case NEW_IMAGE_MODE_EXISTING:
  3034. break;
  3035. case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
  3036. /* create new image with backing file */
  3037. bdrv_img_create(arg->target, format,
  3038. source->filename,
  3039. source->drv->format_name,
  3040. NULL, size, flags, &local_err, false);
  3041. break;
  3042. default:
  3043. abort();
  3044. }
  3045. }
  3046. if (local_err) {
  3047. error_propagate(errp, local_err);
  3048. goto out;
  3049. }
  3050. options = qdict_new();
  3051. if (arg->has_node_name) {
  3052. qdict_put_str(options, "node-name", arg->node_name);
  3053. }
  3054. if (format) {
  3055. qdict_put_str(options, "driver", format);
  3056. }
  3057. /* Mirroring takes care of copy-on-write using the source's backing
  3058. * file.
  3059. */
  3060. target_bs = bdrv_open(arg->target, NULL, options,
  3061. flags | BDRV_O_NO_BACKING, errp);
  3062. if (!target_bs) {
  3063. goto out;
  3064. }
  3065. bdrv_set_aio_context(target_bs, aio_context);
  3066. blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
  3067. arg->has_replaces, arg->replaces, arg->sync,
  3068. backing_mode, arg->has_speed, arg->speed,
  3069. arg->has_granularity, arg->granularity,
  3070. arg->has_buf_size, arg->buf_size,
  3071. arg->has_on_source_error, arg->on_source_error,
  3072. arg->has_on_target_error, arg->on_target_error,
  3073. arg->has_unmap, arg->unmap,
  3074. false, NULL,
  3075. &local_err);
  3076. bdrv_unref(target_bs);
  3077. error_propagate(errp, local_err);
  3078. out:
  3079. aio_context_release(aio_context);
  3080. }
  3081. void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
  3082. const char *device, const char *target,
  3083. bool has_replaces, const char *replaces,
  3084. MirrorSyncMode sync,
  3085. bool has_speed, int64_t speed,
  3086. bool has_granularity, uint32_t granularity,
  3087. bool has_buf_size, int64_t buf_size,
  3088. bool has_on_source_error,
  3089. BlockdevOnError on_source_error,
  3090. bool has_on_target_error,
  3091. BlockdevOnError on_target_error,
  3092. bool has_filter_node_name,
  3093. const char *filter_node_name,
  3094. Error **errp)
  3095. {
  3096. BlockDriverState *bs;
  3097. BlockDriverState *target_bs;
  3098. AioContext *aio_context;
  3099. BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
  3100. Error *local_err = NULL;
  3101. bs = qmp_get_root_bs(device, errp);
  3102. if (!bs) {
  3103. return;
  3104. }
  3105. target_bs = bdrv_lookup_bs(target, target, errp);
  3106. if (!target_bs) {
  3107. return;
  3108. }
  3109. aio_context = bdrv_get_aio_context(bs);
  3110. aio_context_acquire(aio_context);
  3111. bdrv_set_aio_context(target_bs, aio_context);
  3112. blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
  3113. has_replaces, replaces, sync, backing_mode,
  3114. has_speed, speed,
  3115. has_granularity, granularity,
  3116. has_buf_size, buf_size,
  3117. has_on_source_error, on_source_error,
  3118. has_on_target_error, on_target_error,
  3119. true, true,
  3120. has_filter_node_name, filter_node_name,
  3121. &local_err);
  3122. error_propagate(errp, local_err);
  3123. aio_context_release(aio_context);
  3124. }
  3125. /* Get a block job using its ID and acquire its AioContext */
  3126. static BlockJob *find_block_job(const char *id, AioContext **aio_context,
  3127. Error **errp)
  3128. {
  3129. BlockJob *job;
  3130. assert(id != NULL);
  3131. *aio_context = NULL;
  3132. job = block_job_get(id);
  3133. if (!job) {
  3134. error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
  3135. "Block job '%s' not found", id);
  3136. return NULL;
  3137. }
  3138. *aio_context = blk_get_aio_context(job->blk);
  3139. aio_context_acquire(*aio_context);
  3140. return job;
  3141. }
  3142. void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
  3143. {
  3144. AioContext *aio_context;
  3145. BlockJob *job = find_block_job(device, &aio_context, errp);
  3146. if (!job) {
  3147. return;
  3148. }
  3149. block_job_set_speed(job, speed, errp);
  3150. aio_context_release(aio_context);
  3151. }
  3152. void qmp_block_job_cancel(const char *device,
  3153. bool has_force, bool force, Error **errp)
  3154. {
  3155. AioContext *aio_context;
  3156. BlockJob *job = find_block_job(device, &aio_context, errp);
  3157. if (!job) {
  3158. return;
  3159. }
  3160. if (!has_force) {
  3161. force = false;
  3162. }
  3163. if (block_job_user_paused(job) && !force) {
  3164. error_setg(errp, "The block job for device '%s' is currently paused",
  3165. device);
  3166. goto out;
  3167. }
  3168. trace_qmp_block_job_cancel(job);
  3169. block_job_cancel(job);
  3170. out:
  3171. aio_context_release(aio_context);
  3172. }
  3173. void qmp_block_job_pause(const char *device, Error **errp)
  3174. {
  3175. AioContext *aio_context;
  3176. BlockJob *job = find_block_job(device, &aio_context, errp);
  3177. if (!job || block_job_user_paused(job)) {
  3178. return;
  3179. }
  3180. trace_qmp_block_job_pause(job);
  3181. block_job_user_pause(job);
  3182. aio_context_release(aio_context);
  3183. }
  3184. void qmp_block_job_resume(const char *device, Error **errp)
  3185. {
  3186. AioContext *aio_context;
  3187. BlockJob *job = find_block_job(device, &aio_context, errp);
  3188. if (!job || !block_job_user_paused(job)) {
  3189. return;
  3190. }
  3191. trace_qmp_block_job_resume(job);
  3192. block_job_iostatus_reset(job);
  3193. block_job_user_resume(job);
  3194. aio_context_release(aio_context);
  3195. }
  3196. void qmp_block_job_complete(const char *device, Error **errp)
  3197. {
  3198. AioContext *aio_context;
  3199. BlockJob *job = find_block_job(device, &aio_context, errp);
  3200. if (!job) {
  3201. return;
  3202. }
  3203. trace_qmp_block_job_complete(job);
  3204. block_job_complete(job, errp);
  3205. aio_context_release(aio_context);
  3206. }
  3207. void qmp_change_backing_file(const char *device,
  3208. const char *image_node_name,
  3209. const char *backing_file,
  3210. Error **errp)
  3211. {
  3212. BlockDriverState *bs = NULL;
  3213. AioContext *aio_context;
  3214. BlockDriverState *image_bs = NULL;
  3215. Error *local_err = NULL;
  3216. bool ro;
  3217. int open_flags;
  3218. int ret;
  3219. bs = qmp_get_root_bs(device, errp);
  3220. if (!bs) {
  3221. return;
  3222. }
  3223. aio_context = bdrv_get_aio_context(bs);
  3224. aio_context_acquire(aio_context);
  3225. image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
  3226. if (local_err) {
  3227. error_propagate(errp, local_err);
  3228. goto out;
  3229. }
  3230. if (!image_bs) {
  3231. error_setg(errp, "image file not found");
  3232. goto out;
  3233. }
  3234. if (bdrv_find_base(image_bs) == image_bs) {
  3235. error_setg(errp, "not allowing backing file change on an image "
  3236. "without a backing file");
  3237. goto out;
  3238. }
  3239. /* even though we are not necessarily operating on bs, we need it to
  3240. * determine if block ops are currently prohibited on the chain */
  3241. if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
  3242. goto out;
  3243. }
  3244. /* final sanity check */
  3245. if (!bdrv_chain_contains(bs, image_bs)) {
  3246. error_setg(errp, "'%s' and image file are not in the same chain",
  3247. device);
  3248. goto out;
  3249. }
  3250. /* if not r/w, reopen to make r/w */
  3251. open_flags = image_bs->open_flags;
  3252. ro = bdrv_is_read_only(image_bs);
  3253. if (ro) {
  3254. bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
  3255. if (local_err) {
  3256. error_propagate(errp, local_err);
  3257. goto out;
  3258. }
  3259. }
  3260. ret = bdrv_change_backing_file(image_bs, backing_file,
  3261. image_bs->drv ? image_bs->drv->format_name : "");
  3262. if (ret < 0) {
  3263. error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
  3264. backing_file);
  3265. /* don't exit here, so we can try to restore open flags if
  3266. * appropriate */
  3267. }
  3268. if (ro) {
  3269. bdrv_reopen(image_bs, open_flags, &local_err);
  3270. error_propagate(errp, local_err);
  3271. }
  3272. out:
  3273. aio_context_release(aio_context);
  3274. }
  3275. void hmp_drive_add_node(Monitor *mon, const char *optstr)
  3276. {
  3277. QemuOpts *opts;
  3278. QDict *qdict;
  3279. Error *local_err = NULL;
  3280. opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
  3281. if (!opts) {
  3282. return;
  3283. }
  3284. qdict = qemu_opts_to_qdict(opts, NULL);
  3285. if (!qdict_get_try_str(qdict, "node-name")) {
  3286. QDECREF(qdict);
  3287. error_report("'node-name' needs to be specified");
  3288. goto out;
  3289. }
  3290. BlockDriverState *bs = bds_tree_init(qdict, &local_err);
  3291. if (!bs) {
  3292. error_report_err(local_err);
  3293. goto out;
  3294. }
  3295. QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
  3296. out:
  3297. qemu_opts_del(opts);
  3298. }
  3299. void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
  3300. {
  3301. BlockDriverState *bs;
  3302. QObject *obj;
  3303. Visitor *v = qobject_output_visitor_new(&obj);
  3304. QDict *qdict;
  3305. Error *local_err = NULL;
  3306. visit_type_BlockdevOptions(v, NULL, &options, &local_err);
  3307. if (local_err) {
  3308. error_propagate(errp, local_err);
  3309. goto fail;
  3310. }
  3311. visit_complete(v, &obj);
  3312. qdict = qobject_to_qdict(obj);
  3313. qdict_flatten(qdict);
  3314. if (!qdict_get_try_str(qdict, "node-name")) {
  3315. error_setg(errp, "'node-name' must be specified for the root node");
  3316. goto fail;
  3317. }
  3318. bs = bds_tree_init(qdict, errp);
  3319. if (!bs) {
  3320. goto fail;
  3321. }
  3322. QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
  3323. if (bs && bdrv_key_required(bs)) {
  3324. QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
  3325. bdrv_unref(bs);
  3326. error_setg(errp, "blockdev-add doesn't support encrypted devices");
  3327. goto fail;
  3328. }
  3329. fail:
  3330. visit_free(v);
  3331. }
  3332. void qmp_blockdev_del(const char *node_name, Error **errp)
  3333. {
  3334. AioContext *aio_context;
  3335. BlockDriverState *bs;
  3336. bs = bdrv_find_node(node_name);
  3337. if (!bs) {
  3338. error_setg(errp, "Cannot find node %s", node_name);
  3339. return;
  3340. }
  3341. if (bdrv_has_blk(bs)) {
  3342. error_setg(errp, "Node %s is in use", node_name);
  3343. return;
  3344. }
  3345. aio_context = bdrv_get_aio_context(bs);
  3346. aio_context_acquire(aio_context);
  3347. if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
  3348. goto out;
  3349. }
  3350. if (!bs->monitor_list.tqe_prev) {
  3351. error_setg(errp, "Node %s is not owned by the monitor",
  3352. bs->node_name);
  3353. goto out;
  3354. }
  3355. if (bs->refcnt > 1) {
  3356. error_setg(errp, "Block device %s is in use",
  3357. bdrv_get_device_or_node_name(bs));
  3358. goto out;
  3359. }
  3360. QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
  3361. bdrv_unref(bs);
  3362. out:
  3363. aio_context_release(aio_context);
  3364. }
  3365. static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
  3366. const char *child_name)
  3367. {
  3368. BdrvChild *child;
  3369. QLIST_FOREACH(child, &parent_bs->children, next) {
  3370. if (strcmp(child->name, child_name) == 0) {
  3371. return child;
  3372. }
  3373. }
  3374. return NULL;
  3375. }
  3376. void qmp_x_blockdev_change(const char *parent, bool has_child,
  3377. const char *child, bool has_node,
  3378. const char *node, Error **errp)
  3379. {
  3380. BlockDriverState *parent_bs, *new_bs = NULL;
  3381. BdrvChild *p_child;
  3382. parent_bs = bdrv_lookup_bs(parent, parent, errp);
  3383. if (!parent_bs) {
  3384. return;
  3385. }
  3386. if (has_child == has_node) {
  3387. if (has_child) {
  3388. error_setg(errp, "The parameters child and node are in conflict");
  3389. } else {
  3390. error_setg(errp, "Either child or node must be specified");
  3391. }
  3392. return;
  3393. }
  3394. if (has_child) {
  3395. p_child = bdrv_find_child(parent_bs, child);
  3396. if (!p_child) {
  3397. error_setg(errp, "Node '%s' does not have child '%s'",
  3398. parent, child);
  3399. return;
  3400. }
  3401. bdrv_del_child(parent_bs, p_child, errp);
  3402. }
  3403. if (has_node) {
  3404. new_bs = bdrv_find_node(node);
  3405. if (!new_bs) {
  3406. error_setg(errp, "Node '%s' not found", node);
  3407. return;
  3408. }
  3409. bdrv_add_child(parent_bs, new_bs, errp);
  3410. }
  3411. }
  3412. BlockJobInfoList *qmp_query_block_jobs(Error **errp)
  3413. {
  3414. BlockJobInfoList *head = NULL, **p_next = &head;
  3415. BlockJob *job;
  3416. for (job = block_job_next(NULL); job; job = block_job_next(job)) {
  3417. BlockJobInfoList *elem;
  3418. AioContext *aio_context;
  3419. if (block_job_is_internal(job)) {
  3420. continue;
  3421. }
  3422. elem = g_new0(BlockJobInfoList, 1);
  3423. aio_context = blk_get_aio_context(job->blk);
  3424. aio_context_acquire(aio_context);
  3425. elem->value = block_job_query(job, errp);
  3426. aio_context_release(aio_context);
  3427. if (!elem->value) {
  3428. g_free(elem);
  3429. qapi_free_BlockJobInfoList(head);
  3430. return NULL;
  3431. }
  3432. *p_next = elem;
  3433. p_next = &elem->next;
  3434. }
  3435. return head;
  3436. }
  3437. QemuOptsList qemu_common_drive_opts = {
  3438. .name = "drive",
  3439. .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
  3440. .desc = {
  3441. {
  3442. .name = "snapshot",
  3443. .type = QEMU_OPT_BOOL,
  3444. .help = "enable/disable snapshot mode",
  3445. },{
  3446. .name = "aio",
  3447. .type = QEMU_OPT_STRING,
  3448. .help = "host AIO implementation (threads, native)",
  3449. },{
  3450. .name = BDRV_OPT_CACHE_WB,
  3451. .type = QEMU_OPT_BOOL,
  3452. .help = "Enable writeback mode",
  3453. },{
  3454. .name = "format",
  3455. .type = QEMU_OPT_STRING,
  3456. .help = "disk format (raw, qcow2, ...)",
  3457. },{
  3458. .name = "rerror",
  3459. .type = QEMU_OPT_STRING,
  3460. .help = "read error action",
  3461. },{
  3462. .name = "werror",
  3463. .type = QEMU_OPT_STRING,
  3464. .help = "write error action",
  3465. },{
  3466. .name = BDRV_OPT_READ_ONLY,
  3467. .type = QEMU_OPT_BOOL,
  3468. .help = "open drive file as read-only",
  3469. },
  3470. THROTTLE_OPTS,
  3471. {
  3472. .name = "throttling.group",
  3473. .type = QEMU_OPT_STRING,
  3474. .help = "name of the block throttling group",
  3475. },{
  3476. .name = "copy-on-read",
  3477. .type = QEMU_OPT_BOOL,
  3478. .help = "copy read data from backing file into image file",
  3479. },{
  3480. .name = "detect-zeroes",
  3481. .type = QEMU_OPT_STRING,
  3482. .help = "try to optimize zero writes (off, on, unmap)",
  3483. },{
  3484. .name = "stats-account-invalid",
  3485. .type = QEMU_OPT_BOOL,
  3486. .help = "whether to account for invalid I/O operations "
  3487. "in the statistics",
  3488. },{
  3489. .name = "stats-account-failed",
  3490. .type = QEMU_OPT_BOOL,
  3491. .help = "whether to account for failed I/O operations "
  3492. "in the statistics",
  3493. },
  3494. { /* end of list */ }
  3495. },
  3496. };
  3497. QemuOptsList qemu_drive_opts = {
  3498. .name = "drive",
  3499. .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
  3500. .desc = {
  3501. /*
  3502. * no elements => accept any params
  3503. * validation will happen later
  3504. */
  3505. { /* end of list */ }
  3506. },
  3507. };