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