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