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