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