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