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