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