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