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