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