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