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