qemu-img: Avoid duplicate block device IDs
[qemu/ar7.git] / blockdev.c
blob3a11a620196c831e1fe8f4156b07892c601a74c2
1 /*
2 * QEMU host block devices
4 * Copyright (c) 2003-2008 Fabrice Bellard
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.
9 * This file incorporates work covered by the following copyright and
10 * permission notice:
12 * Copyright (c) 2003-2008 Fabrice Bellard
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:
21 * The above copyright notice and this permission notice shall be included in
22 * all copies or substantial portions of the Software.
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.
33 #include "sysemu/blockdev.h"
34 #include "hw/block/block.h"
35 #include "block/blockjob.h"
36 #include "monitor/monitor.h"
37 #include "qapi/qmp/qerror.h"
38 #include "qemu/option.h"
39 #include "qemu/config-file.h"
40 #include "qapi/qmp/types.h"
41 #include "qapi-visit.h"
42 #include "qapi/qmp-output-visitor.h"
43 #include "sysemu/sysemu.h"
44 #include "block/block_int.h"
45 #include "qmp-commands.h"
46 #include "trace.h"
47 #include "sysemu/arch_init.h"
49 static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
51 static const char *const if_name[IF_COUNT] = {
52 [IF_NONE] = "none",
53 [IF_IDE] = "ide",
54 [IF_SCSI] = "scsi",
55 [IF_FLOPPY] = "floppy",
56 [IF_PFLASH] = "pflash",
57 [IF_MTD] = "mtd",
58 [IF_SD] = "sd",
59 [IF_VIRTIO] = "virtio",
60 [IF_XEN] = "xen",
63 static const int if_max_devs[IF_COUNT] = {
65 * Do not change these numbers! They govern how drive option
66 * index maps to unit and bus. That mapping is ABI.
68 * All controllers used to imlement if=T drives need to support
69 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
70 * Otherwise, some index values map to "impossible" bus, unit
71 * values.
73 * For instance, if you change [IF_SCSI] to 255, -drive
74 * if=scsi,index=12 no longer means bus=1,unit=5, but
75 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
76 * the drive can't be set up. Regression.
78 [IF_IDE] = 2,
79 [IF_SCSI] = 7,
83 * We automatically delete the drive when a device using it gets
84 * unplugged. Questionable feature, but we can't just drop it.
85 * Device models call blockdev_mark_auto_del() to schedule the
86 * automatic deletion, and generic qdev code calls blockdev_auto_del()
87 * when deletion is actually safe.
89 void blockdev_mark_auto_del(BlockDriverState *bs)
91 DriveInfo *dinfo = drive_get_by_blockdev(bs);
93 if (dinfo && !dinfo->enable_auto_del) {
94 return;
97 if (bs->job) {
98 block_job_cancel(bs->job);
100 if (dinfo) {
101 dinfo->auto_del = 1;
105 void blockdev_auto_del(BlockDriverState *bs)
107 DriveInfo *dinfo = drive_get_by_blockdev(bs);
109 if (dinfo && dinfo->auto_del) {
110 drive_put_ref(dinfo);
114 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
116 int max_devs = if_max_devs[type];
117 return max_devs ? index / max_devs : 0;
120 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
122 int max_devs = if_max_devs[type];
123 return max_devs ? index % max_devs : index;
126 QemuOpts *drive_def(const char *optstr)
128 return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
131 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
132 const char *optstr)
134 QemuOpts *opts;
135 char buf[32];
137 opts = drive_def(optstr);
138 if (!opts) {
139 return NULL;
141 if (type != IF_DEFAULT) {
142 qemu_opt_set(opts, "if", if_name[type]);
144 if (index >= 0) {
145 snprintf(buf, sizeof(buf), "%d", index);
146 qemu_opt_set(opts, "index", buf);
148 if (file)
149 qemu_opt_set(opts, "file", file);
150 return opts;
153 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
155 DriveInfo *dinfo;
157 /* seek interface, bus and unit */
159 QTAILQ_FOREACH(dinfo, &drives, next) {
160 if (dinfo->type == type &&
161 dinfo->bus == bus &&
162 dinfo->unit == unit)
163 return dinfo;
166 return NULL;
169 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
171 return drive_get(type,
172 drive_index_to_bus_id(type, index),
173 drive_index_to_unit_id(type, index));
176 int drive_get_max_bus(BlockInterfaceType type)
178 int max_bus;
179 DriveInfo *dinfo;
181 max_bus = -1;
182 QTAILQ_FOREACH(dinfo, &drives, next) {
183 if(dinfo->type == type &&
184 dinfo->bus > max_bus)
185 max_bus = dinfo->bus;
187 return max_bus;
190 /* Get a block device. This should only be used for single-drive devices
191 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
192 appropriate bus. */
193 DriveInfo *drive_get_next(BlockInterfaceType type)
195 static int next_block_unit[IF_COUNT];
197 return drive_get(type, 0, next_block_unit[type]++);
200 DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
202 DriveInfo *dinfo;
204 QTAILQ_FOREACH(dinfo, &drives, next) {
205 if (dinfo->bdrv == bs) {
206 return dinfo;
209 return NULL;
212 static void bdrv_format_print(void *opaque, const char *name)
214 error_printf(" %s", name);
217 static void drive_uninit(DriveInfo *dinfo)
219 if (dinfo->opts) {
220 qemu_opts_del(dinfo->opts);
223 bdrv_unref(dinfo->bdrv);
224 g_free(dinfo->id);
225 QTAILQ_REMOVE(&drives, dinfo, next);
226 g_free(dinfo->serial);
227 g_free(dinfo);
230 void drive_put_ref(DriveInfo *dinfo)
232 assert(dinfo->refcount);
233 if (--dinfo->refcount == 0) {
234 drive_uninit(dinfo);
238 void drive_get_ref(DriveInfo *dinfo)
240 dinfo->refcount++;
243 typedef struct {
244 QEMUBH *bh;
245 BlockDriverState *bs;
246 } BDRVPutRefBH;
248 static void bdrv_put_ref_bh(void *opaque)
250 BDRVPutRefBH *s = opaque;
252 bdrv_unref(s->bs);
253 qemu_bh_delete(s->bh);
254 g_free(s);
258 * Release a BDS reference in a BH
260 * It is not safe to use bdrv_unref() from a callback function when the callers
261 * still need the BlockDriverState. In such cases we schedule a BH to release
262 * the reference.
264 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
266 BDRVPutRefBH *s;
268 s = g_new(BDRVPutRefBH, 1);
269 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
270 s->bs = bs;
271 qemu_bh_schedule(s->bh);
274 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
276 if (!strcmp(buf, "ignore")) {
277 return BLOCKDEV_ON_ERROR_IGNORE;
278 } else if (!is_read && !strcmp(buf, "enospc")) {
279 return BLOCKDEV_ON_ERROR_ENOSPC;
280 } else if (!strcmp(buf, "stop")) {
281 return BLOCKDEV_ON_ERROR_STOP;
282 } else if (!strcmp(buf, "report")) {
283 return BLOCKDEV_ON_ERROR_REPORT;
284 } else {
285 error_setg(errp, "'%s' invalid %s error action",
286 buf, is_read ? "read" : "write");
287 return -1;
291 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
293 if (throttle_conflicting(cfg)) {
294 error_setg(errp, "bps/iops/max total values and read/write values"
295 " cannot be used at the same time");
296 return false;
299 if (!throttle_is_valid(cfg)) {
300 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
301 return false;
304 return true;
307 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
309 /* Takes the ownership of bs_opts */
310 static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
311 Error **errp)
313 const char *buf;
314 const char *serial;
315 int ro = 0;
316 int bdrv_flags = 0;
317 int on_read_error, on_write_error;
318 DriveInfo *dinfo;
319 ThrottleConfig cfg;
320 int snapshot = 0;
321 bool copy_on_read;
322 int ret;
323 Error *error = NULL;
324 QemuOpts *opts;
325 const char *id;
326 bool has_driver_specific_opts;
327 BlockDriver *drv = NULL;
329 /* Check common options by copying from bs_opts to opts, all other options
330 * stay in bs_opts for processing by bdrv_open(). */
331 id = qdict_get_try_str(bs_opts, "id");
332 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
333 if (error) {
334 error_propagate(errp, error);
335 return NULL;
338 qemu_opts_absorb_qdict(opts, bs_opts, &error);
339 if (error) {
340 error_propagate(errp, error);
341 goto early_err;
344 if (id) {
345 qdict_del(bs_opts, "id");
348 has_driver_specific_opts = !!qdict_size(bs_opts);
350 /* extract parameters */
351 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
352 ro = qemu_opt_get_bool(opts, "read-only", 0);
353 copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
355 serial = qemu_opt_get(opts, "serial");
357 if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
358 if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
359 error_setg(errp, "invalid discard option");
360 goto early_err;
364 if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
365 bdrv_flags |= BDRV_O_CACHE_WB;
367 if (qemu_opt_get_bool(opts, "cache.direct", false)) {
368 bdrv_flags |= BDRV_O_NOCACHE;
370 if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
371 bdrv_flags |= BDRV_O_NO_FLUSH;
374 #ifdef CONFIG_LINUX_AIO
375 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
376 if (!strcmp(buf, "native")) {
377 bdrv_flags |= BDRV_O_NATIVE_AIO;
378 } else if (!strcmp(buf, "threads")) {
379 /* this is the default */
380 } else {
381 error_setg(errp, "invalid aio option");
382 goto early_err;
385 #endif
387 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
388 if (is_help_option(buf)) {
389 error_printf("Supported formats:");
390 bdrv_iterate_format(bdrv_format_print, NULL);
391 error_printf("\n");
392 goto early_err;
395 drv = bdrv_find_format(buf);
396 if (!drv) {
397 error_setg(errp, "'%s' invalid format", buf);
398 goto early_err;
402 /* disk I/O throttling */
403 memset(&cfg, 0, sizeof(cfg));
404 cfg.buckets[THROTTLE_BPS_TOTAL].avg =
405 qemu_opt_get_number(opts, "throttling.bps-total", 0);
406 cfg.buckets[THROTTLE_BPS_READ].avg =
407 qemu_opt_get_number(opts, "throttling.bps-read", 0);
408 cfg.buckets[THROTTLE_BPS_WRITE].avg =
409 qemu_opt_get_number(opts, "throttling.bps-write", 0);
410 cfg.buckets[THROTTLE_OPS_TOTAL].avg =
411 qemu_opt_get_number(opts, "throttling.iops-total", 0);
412 cfg.buckets[THROTTLE_OPS_READ].avg =
413 qemu_opt_get_number(opts, "throttling.iops-read", 0);
414 cfg.buckets[THROTTLE_OPS_WRITE].avg =
415 qemu_opt_get_number(opts, "throttling.iops-write", 0);
417 cfg.buckets[THROTTLE_BPS_TOTAL].max =
418 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
419 cfg.buckets[THROTTLE_BPS_READ].max =
420 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
421 cfg.buckets[THROTTLE_BPS_WRITE].max =
422 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
423 cfg.buckets[THROTTLE_OPS_TOTAL].max =
424 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
425 cfg.buckets[THROTTLE_OPS_READ].max =
426 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
427 cfg.buckets[THROTTLE_OPS_WRITE].max =
428 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
430 cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
432 if (!check_throttle_config(&cfg, &error)) {
433 error_propagate(errp, error);
434 goto early_err;
437 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
438 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
439 on_write_error = parse_block_error_action(buf, 0, &error);
440 if (error) {
441 error_propagate(errp, error);
442 goto early_err;
446 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
447 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
448 on_read_error = parse_block_error_action(buf, 1, &error);
449 if (error) {
450 error_propagate(errp, error);
451 goto early_err;
455 if (bdrv_find_node(qemu_opts_id(opts))) {
456 error_setg(errp, "device id=%s is conflicting with a node-name",
457 qemu_opts_id(opts));
458 goto early_err;
461 /* init */
462 dinfo = g_malloc0(sizeof(*dinfo));
463 dinfo->id = g_strdup(qemu_opts_id(opts));
464 dinfo->bdrv = bdrv_new(dinfo->id, &error);
465 if (error) {
466 error_propagate(errp, error);
467 goto bdrv_new_err;
469 dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
470 dinfo->bdrv->read_only = ro;
471 dinfo->refcount = 1;
472 if (serial != NULL) {
473 dinfo->serial = g_strdup(serial);
475 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
477 bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);
479 /* disk I/O throttling */
480 if (throttle_enabled(&cfg)) {
481 bdrv_io_limits_enable(dinfo->bdrv);
482 bdrv_set_io_limits(dinfo->bdrv, &cfg);
485 if (!file || !*file) {
486 if (has_driver_specific_opts) {
487 file = NULL;
488 } else {
489 QDECREF(bs_opts);
490 qemu_opts_del(opts);
491 return dinfo;
494 if (snapshot) {
495 /* always use cache=unsafe with snapshot */
496 bdrv_flags &= ~BDRV_O_CACHE_MASK;
497 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
500 if (copy_on_read) {
501 bdrv_flags |= BDRV_O_COPY_ON_READ;
504 if (runstate_check(RUN_STATE_INMIGRATE)) {
505 bdrv_flags |= BDRV_O_INCOMING;
508 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
510 QINCREF(bs_opts);
511 ret = bdrv_open(&dinfo->bdrv, file, NULL, bs_opts, bdrv_flags, drv, &error);
513 if (ret < 0) {
514 error_setg(errp, "could not open disk image %s: %s",
515 file ?: dinfo->id, error_get_pretty(error));
516 error_free(error);
517 goto err;
520 if (bdrv_key_required(dinfo->bdrv))
521 autostart = 0;
523 QDECREF(bs_opts);
524 qemu_opts_del(opts);
526 return dinfo;
528 err:
529 bdrv_unref(dinfo->bdrv);
530 QTAILQ_REMOVE(&drives, dinfo, next);
531 bdrv_new_err:
532 g_free(dinfo->id);
533 g_free(dinfo);
534 early_err:
535 QDECREF(bs_opts);
536 qemu_opts_del(opts);
537 return NULL;
540 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to)
542 const char *value;
544 value = qemu_opt_get(opts, from);
545 if (value) {
546 qemu_opt_set(opts, to, value);
547 qemu_opt_unset(opts, from);
551 QemuOptsList qemu_legacy_drive_opts = {
552 .name = "drive",
553 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
554 .desc = {
556 .name = "bus",
557 .type = QEMU_OPT_NUMBER,
558 .help = "bus number",
560 .name = "unit",
561 .type = QEMU_OPT_NUMBER,
562 .help = "unit number (i.e. lun for scsi)",
564 .name = "index",
565 .type = QEMU_OPT_NUMBER,
566 .help = "index number",
568 .name = "media",
569 .type = QEMU_OPT_STRING,
570 .help = "media type (disk, cdrom)",
572 .name = "if",
573 .type = QEMU_OPT_STRING,
574 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
576 .name = "cyls",
577 .type = QEMU_OPT_NUMBER,
578 .help = "number of cylinders (ide disk geometry)",
580 .name = "heads",
581 .type = QEMU_OPT_NUMBER,
582 .help = "number of heads (ide disk geometry)",
584 .name = "secs",
585 .type = QEMU_OPT_NUMBER,
586 .help = "number of sectors (ide disk geometry)",
588 .name = "trans",
589 .type = QEMU_OPT_STRING,
590 .help = "chs translation (auto, lba, none)",
592 .name = "boot",
593 .type = QEMU_OPT_BOOL,
594 .help = "(deprecated, ignored)",
596 .name = "addr",
597 .type = QEMU_OPT_STRING,
598 .help = "pci address (virtio only)",
600 .name = "file",
601 .type = QEMU_OPT_STRING,
602 .help = "file name",
605 /* Options that are passed on, but have special semantics with -drive */
607 .name = "read-only",
608 .type = QEMU_OPT_BOOL,
609 .help = "open drive file as read-only",
611 .name = "rerror",
612 .type = QEMU_OPT_STRING,
613 .help = "read error action",
615 .name = "werror",
616 .type = QEMU_OPT_STRING,
617 .help = "write error action",
619 .name = "copy-on-read",
620 .type = QEMU_OPT_BOOL,
621 .help = "copy read data from backing file into image file",
624 { /* end of list */ }
628 DriveInfo *drive_init(QemuOpts *all_opts, BlockInterfaceType block_default_type)
630 const char *value;
631 DriveInfo *dinfo = NULL;
632 QDict *bs_opts;
633 QemuOpts *legacy_opts;
634 DriveMediaType media = MEDIA_DISK;
635 BlockInterfaceType type;
636 int cyls, heads, secs, translation;
637 int max_devs, bus_id, unit_id, index;
638 const char *devaddr;
639 const char *werror, *rerror;
640 bool read_only = false;
641 bool copy_on_read;
642 const char *filename;
643 Error *local_err = NULL;
645 /* Change legacy command line options into QMP ones */
646 qemu_opt_rename(all_opts, "iops", "throttling.iops-total");
647 qemu_opt_rename(all_opts, "iops_rd", "throttling.iops-read");
648 qemu_opt_rename(all_opts, "iops_wr", "throttling.iops-write");
650 qemu_opt_rename(all_opts, "bps", "throttling.bps-total");
651 qemu_opt_rename(all_opts, "bps_rd", "throttling.bps-read");
652 qemu_opt_rename(all_opts, "bps_wr", "throttling.bps-write");
654 qemu_opt_rename(all_opts, "iops_max", "throttling.iops-total-max");
655 qemu_opt_rename(all_opts, "iops_rd_max", "throttling.iops-read-max");
656 qemu_opt_rename(all_opts, "iops_wr_max", "throttling.iops-write-max");
658 qemu_opt_rename(all_opts, "bps_max", "throttling.bps-total-max");
659 qemu_opt_rename(all_opts, "bps_rd_max", "throttling.bps-read-max");
660 qemu_opt_rename(all_opts, "bps_wr_max", "throttling.bps-write-max");
662 qemu_opt_rename(all_opts,
663 "iops_size", "throttling.iops-size");
665 qemu_opt_rename(all_opts, "readonly", "read-only");
667 value = qemu_opt_get(all_opts, "cache");
668 if (value) {
669 int flags = 0;
671 if (bdrv_parse_cache_flags(value, &flags) != 0) {
672 error_report("invalid cache option");
673 return NULL;
676 /* Specific options take precedence */
677 if (!qemu_opt_get(all_opts, "cache.writeback")) {
678 qemu_opt_set_bool(all_opts, "cache.writeback",
679 !!(flags & BDRV_O_CACHE_WB));
681 if (!qemu_opt_get(all_opts, "cache.direct")) {
682 qemu_opt_set_bool(all_opts, "cache.direct",
683 !!(flags & BDRV_O_NOCACHE));
685 if (!qemu_opt_get(all_opts, "cache.no-flush")) {
686 qemu_opt_set_bool(all_opts, "cache.no-flush",
687 !!(flags & BDRV_O_NO_FLUSH));
689 qemu_opt_unset(all_opts, "cache");
692 /* Get a QDict for processing the options */
693 bs_opts = qdict_new();
694 qemu_opts_to_qdict(all_opts, bs_opts);
696 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
697 &error_abort);
698 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
699 if (local_err) {
700 qerror_report_err(local_err);
701 error_free(local_err);
702 goto fail;
705 /* Deprecated option boot=[on|off] */
706 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
707 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
708 "ignored. Future versions will reject this parameter. Please "
709 "update your scripts.\n");
712 /* Media type */
713 value = qemu_opt_get(legacy_opts, "media");
714 if (value) {
715 if (!strcmp(value, "disk")) {
716 media = MEDIA_DISK;
717 } else if (!strcmp(value, "cdrom")) {
718 media = MEDIA_CDROM;
719 read_only = true;
720 } else {
721 error_report("'%s' invalid media", value);
722 goto fail;
726 /* copy-on-read is disabled with a warning for read-only devices */
727 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
728 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
730 if (read_only && copy_on_read) {
731 error_report("warning: disabling copy-on-read on read-only drive");
732 copy_on_read = false;
735 qdict_put(bs_opts, "read-only",
736 qstring_from_str(read_only ? "on" : "off"));
737 qdict_put(bs_opts, "copy-on-read",
738 qstring_from_str(copy_on_read ? "on" :"off"));
740 /* Controller type */
741 value = qemu_opt_get(legacy_opts, "if");
742 if (value) {
743 for (type = 0;
744 type < IF_COUNT && strcmp(value, if_name[type]);
745 type++) {
747 if (type == IF_COUNT) {
748 error_report("unsupported bus type '%s'", value);
749 goto fail;
751 } else {
752 type = block_default_type;
755 /* Geometry */
756 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
757 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
758 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
760 if (cyls || heads || secs) {
761 if (cyls < 1) {
762 error_report("invalid physical cyls number");
763 goto fail;
765 if (heads < 1) {
766 error_report("invalid physical heads number");
767 goto fail;
769 if (secs < 1) {
770 error_report("invalid physical secs number");
771 goto fail;
775 translation = BIOS_ATA_TRANSLATION_AUTO;
776 value = qemu_opt_get(legacy_opts, "trans");
777 if (value != NULL) {
778 if (!cyls) {
779 error_report("'%s' trans must be used with cyls, heads and secs",
780 value);
781 goto fail;
783 if (!strcmp(value, "none")) {
784 translation = BIOS_ATA_TRANSLATION_NONE;
785 } else if (!strcmp(value, "lba")) {
786 translation = BIOS_ATA_TRANSLATION_LBA;
787 } else if (!strcmp(value, "large")) {
788 translation = BIOS_ATA_TRANSLATION_LARGE;
789 } else if (!strcmp(value, "rechs")) {
790 translation = BIOS_ATA_TRANSLATION_RECHS;
791 } else if (!strcmp(value, "auto")) {
792 translation = BIOS_ATA_TRANSLATION_AUTO;
793 } else {
794 error_report("'%s' invalid translation type", value);
795 goto fail;
799 if (media == MEDIA_CDROM) {
800 if (cyls || secs || heads) {
801 error_report("CHS can't be set with media=cdrom");
802 goto fail;
806 /* Device address specified by bus/unit or index.
807 * If none was specified, try to find the first free one. */
808 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
809 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
810 index = qemu_opt_get_number(legacy_opts, "index", -1);
812 max_devs = if_max_devs[type];
814 if (index != -1) {
815 if (bus_id != 0 || unit_id != -1) {
816 error_report("index cannot be used with bus and unit");
817 goto fail;
819 bus_id = drive_index_to_bus_id(type, index);
820 unit_id = drive_index_to_unit_id(type, index);
823 if (unit_id == -1) {
824 unit_id = 0;
825 while (drive_get(type, bus_id, unit_id) != NULL) {
826 unit_id++;
827 if (max_devs && unit_id >= max_devs) {
828 unit_id -= max_devs;
829 bus_id++;
834 if (max_devs && unit_id >= max_devs) {
835 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
836 goto fail;
839 if (drive_get(type, bus_id, unit_id) != NULL) {
840 error_report("drive with bus=%d, unit=%d (index=%d) exists",
841 bus_id, unit_id, index);
842 goto fail;
845 /* no id supplied -> create one */
846 if (qemu_opts_id(all_opts) == NULL) {
847 char *new_id;
848 const char *mediastr = "";
849 if (type == IF_IDE || type == IF_SCSI) {
850 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
852 if (max_devs) {
853 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
854 mediastr, unit_id);
855 } else {
856 new_id = g_strdup_printf("%s%s%i", if_name[type],
857 mediastr, unit_id);
859 qdict_put(bs_opts, "id", qstring_from_str(new_id));
860 g_free(new_id);
863 /* Add virtio block device */
864 devaddr = qemu_opt_get(legacy_opts, "addr");
865 if (devaddr && type != IF_VIRTIO) {
866 error_report("addr is not supported by this bus type");
867 goto fail;
870 if (type == IF_VIRTIO) {
871 QemuOpts *devopts;
872 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
873 &error_abort);
874 if (arch_type == QEMU_ARCH_S390X) {
875 qemu_opt_set(devopts, "driver", "virtio-blk-s390");
876 } else {
877 qemu_opt_set(devopts, "driver", "virtio-blk-pci");
879 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
880 if (devaddr) {
881 qemu_opt_set(devopts, "addr", devaddr);
885 filename = qemu_opt_get(legacy_opts, "file");
887 /* Check werror/rerror compatibility with if=... */
888 werror = qemu_opt_get(legacy_opts, "werror");
889 if (werror != NULL) {
890 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
891 type != IF_NONE) {
892 error_report("werror is not supported by this bus type");
893 goto fail;
895 qdict_put(bs_opts, "werror", qstring_from_str(werror));
898 rerror = qemu_opt_get(legacy_opts, "rerror");
899 if (rerror != NULL) {
900 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
901 type != IF_NONE) {
902 error_report("rerror is not supported by this bus type");
903 goto fail;
905 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
908 /* Actual block device init: Functionality shared with blockdev-add */
909 dinfo = blockdev_init(filename, bs_opts, &local_err);
910 if (dinfo == NULL) {
911 if (local_err) {
912 qerror_report_err(local_err);
913 error_free(local_err);
915 goto fail;
916 } else {
917 assert(!local_err);
920 /* Set legacy DriveInfo fields */
921 dinfo->enable_auto_del = true;
922 dinfo->opts = all_opts;
924 dinfo->cyls = cyls;
925 dinfo->heads = heads;
926 dinfo->secs = secs;
927 dinfo->trans = translation;
929 dinfo->type = type;
930 dinfo->bus = bus_id;
931 dinfo->unit = unit_id;
932 dinfo->devaddr = devaddr;
934 switch(type) {
935 case IF_IDE:
936 case IF_SCSI:
937 case IF_XEN:
938 case IF_NONE:
939 dinfo->media_cd = media == MEDIA_CDROM;
940 break;
941 default:
942 break;
945 fail:
946 qemu_opts_del(legacy_opts);
947 return dinfo;
950 void do_commit(Monitor *mon, const QDict *qdict)
952 const char *device = qdict_get_str(qdict, "device");
953 BlockDriverState *bs;
954 int ret;
956 if (!strcmp(device, "all")) {
957 ret = bdrv_commit_all();
958 } else {
959 bs = bdrv_find(device);
960 if (!bs) {
961 monitor_printf(mon, "Device '%s' not found\n", device);
962 return;
964 ret = bdrv_commit(bs);
966 if (ret < 0) {
967 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
968 strerror(-ret));
972 static void blockdev_do_action(int kind, void *data, Error **errp)
974 TransactionAction action;
975 TransactionActionList list;
977 action.kind = kind;
978 action.data = data;
979 list.value = &action;
980 list.next = NULL;
981 qmp_transaction(&list, errp);
984 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
985 bool has_node_name, const char *node_name,
986 const char *snapshot_file,
987 bool has_snapshot_node_name,
988 const char *snapshot_node_name,
989 bool has_format, const char *format,
990 bool has_mode, NewImageMode mode, Error **errp)
992 BlockdevSnapshot snapshot = {
993 .has_device = has_device,
994 .device = (char *) device,
995 .has_node_name = has_node_name,
996 .node_name = (char *) node_name,
997 .snapshot_file = (char *) snapshot_file,
998 .has_snapshot_node_name = has_snapshot_node_name,
999 .snapshot_node_name = (char *) snapshot_node_name,
1000 .has_format = has_format,
1001 .format = (char *) format,
1002 .has_mode = has_mode,
1003 .mode = mode,
1005 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1006 &snapshot, errp);
1009 void qmp_blockdev_snapshot_internal_sync(const char *device,
1010 const char *name,
1011 Error **errp)
1013 BlockdevSnapshotInternal snapshot = {
1014 .device = (char *) device,
1015 .name = (char *) name
1018 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1019 &snapshot, errp);
1022 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1023 bool has_id,
1024 const char *id,
1025 bool has_name,
1026 const char *name,
1027 Error **errp)
1029 BlockDriverState *bs = bdrv_find(device);
1030 QEMUSnapshotInfo sn;
1031 Error *local_err = NULL;
1032 SnapshotInfo *info = NULL;
1033 int ret;
1035 if (!bs) {
1036 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1037 return NULL;
1040 if (!has_id) {
1041 id = NULL;
1044 if (!has_name) {
1045 name = NULL;
1048 if (!id && !name) {
1049 error_setg(errp, "Name or id must be provided");
1050 return NULL;
1053 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1054 if (local_err) {
1055 error_propagate(errp, local_err);
1056 return NULL;
1058 if (!ret) {
1059 error_setg(errp,
1060 "Snapshot with id '%s' and name '%s' does not exist on "
1061 "device '%s'",
1062 STR_OR_NULL(id), STR_OR_NULL(name), device);
1063 return NULL;
1066 bdrv_snapshot_delete(bs, id, name, &local_err);
1067 if (local_err) {
1068 error_propagate(errp, local_err);
1069 return NULL;
1072 info = g_malloc0(sizeof(SnapshotInfo));
1073 info->id = g_strdup(sn.id_str);
1074 info->name = g_strdup(sn.name);
1075 info->date_nsec = sn.date_nsec;
1076 info->date_sec = sn.date_sec;
1077 info->vm_state_size = sn.vm_state_size;
1078 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1079 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1081 return info;
1084 /* New and old BlockDriverState structs for group snapshots */
1086 typedef struct BlkTransactionState BlkTransactionState;
1088 /* Only prepare() may fail. In a single transaction, only one of commit() or
1089 abort() will be called, clean() will always be called if it present. */
1090 typedef struct BdrvActionOps {
1091 /* Size of state struct, in bytes. */
1092 size_t instance_size;
1093 /* Prepare the work, must NOT be NULL. */
1094 void (*prepare)(BlkTransactionState *common, Error **errp);
1095 /* Commit the changes, can be NULL. */
1096 void (*commit)(BlkTransactionState *common);
1097 /* Abort the changes on fail, can be NULL. */
1098 void (*abort)(BlkTransactionState *common);
1099 /* Clean up resource in the end, can be NULL. */
1100 void (*clean)(BlkTransactionState *common);
1101 } BdrvActionOps;
1104 * This structure must be arranged as first member in child type, assuming
1105 * that compiler will also arrange it to the same address with parent instance.
1106 * Later it will be used in free().
1108 struct BlkTransactionState {
1109 TransactionAction *action;
1110 const BdrvActionOps *ops;
1111 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1114 /* internal snapshot private data */
1115 typedef struct InternalSnapshotState {
1116 BlkTransactionState common;
1117 BlockDriverState *bs;
1118 QEMUSnapshotInfo sn;
1119 } InternalSnapshotState;
1121 static void internal_snapshot_prepare(BlkTransactionState *common,
1122 Error **errp)
1124 const char *device;
1125 const char *name;
1126 BlockDriverState *bs;
1127 QEMUSnapshotInfo old_sn, *sn;
1128 bool ret;
1129 qemu_timeval tv;
1130 BlockdevSnapshotInternal *internal;
1131 InternalSnapshotState *state;
1132 int ret1;
1134 g_assert(common->action->kind ==
1135 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1136 internal = common->action->blockdev_snapshot_internal_sync;
1137 state = DO_UPCAST(InternalSnapshotState, common, common);
1139 /* 1. parse input */
1140 device = internal->device;
1141 name = internal->name;
1143 /* 2. check for validation */
1144 bs = bdrv_find(device);
1145 if (!bs) {
1146 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1147 return;
1150 if (!bdrv_is_inserted(bs)) {
1151 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1152 return;
1155 if (bdrv_is_read_only(bs)) {
1156 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1157 return;
1160 if (!bdrv_can_snapshot(bs)) {
1161 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1162 bs->drv->format_name, device, "internal snapshot");
1163 return;
1166 if (!strlen(name)) {
1167 error_setg(errp, "Name is empty");
1168 return;
1171 /* check whether a snapshot with name exist */
1172 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn, errp);
1173 if (error_is_set(errp)) {
1174 return;
1175 } else if (ret) {
1176 error_setg(errp,
1177 "Snapshot with name '%s' already exists on device '%s'",
1178 name, device);
1179 return;
1182 /* 3. take the snapshot */
1183 sn = &state->sn;
1184 pstrcpy(sn->name, sizeof(sn->name), name);
1185 qemu_gettimeofday(&tv);
1186 sn->date_sec = tv.tv_sec;
1187 sn->date_nsec = tv.tv_usec * 1000;
1188 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1190 ret1 = bdrv_snapshot_create(bs, sn);
1191 if (ret1 < 0) {
1192 error_setg_errno(errp, -ret1,
1193 "Failed to create snapshot '%s' on device '%s'",
1194 name, device);
1195 return;
1198 /* 4. succeed, mark a snapshot is created */
1199 state->bs = bs;
1202 static void internal_snapshot_abort(BlkTransactionState *common)
1204 InternalSnapshotState *state =
1205 DO_UPCAST(InternalSnapshotState, common, common);
1206 BlockDriverState *bs = state->bs;
1207 QEMUSnapshotInfo *sn = &state->sn;
1208 Error *local_error = NULL;
1210 if (!bs) {
1211 return;
1214 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1215 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1216 "device '%s' in abort: %s",
1217 sn->id_str,
1218 sn->name,
1219 bdrv_get_device_name(bs),
1220 error_get_pretty(local_error));
1221 error_free(local_error);
1225 /* external snapshot private data */
1226 typedef struct ExternalSnapshotState {
1227 BlkTransactionState common;
1228 BlockDriverState *old_bs;
1229 BlockDriverState *new_bs;
1230 } ExternalSnapshotState;
1232 static void external_snapshot_prepare(BlkTransactionState *common,
1233 Error **errp)
1235 BlockDriver *drv;
1236 int flags, ret;
1237 QDict *options = NULL;
1238 Error *local_err = NULL;
1239 bool has_device = false;
1240 const char *device;
1241 bool has_node_name = false;
1242 const char *node_name;
1243 bool has_snapshot_node_name = false;
1244 const char *snapshot_node_name;
1245 const char *new_image_file;
1246 const char *format = "qcow2";
1247 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1248 ExternalSnapshotState *state =
1249 DO_UPCAST(ExternalSnapshotState, common, common);
1250 TransactionAction *action = common->action;
1252 /* get parameters */
1253 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1255 has_device = action->blockdev_snapshot_sync->has_device;
1256 device = action->blockdev_snapshot_sync->device;
1257 has_node_name = action->blockdev_snapshot_sync->has_node_name;
1258 node_name = action->blockdev_snapshot_sync->node_name;
1259 has_snapshot_node_name =
1260 action->blockdev_snapshot_sync->has_snapshot_node_name;
1261 snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1263 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1264 if (action->blockdev_snapshot_sync->has_format) {
1265 format = action->blockdev_snapshot_sync->format;
1267 if (action->blockdev_snapshot_sync->has_mode) {
1268 mode = action->blockdev_snapshot_sync->mode;
1271 /* start processing */
1272 drv = bdrv_find_format(format);
1273 if (!drv) {
1274 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1275 return;
1278 state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1279 has_node_name ? node_name : NULL,
1280 &local_err);
1281 if (local_err) {
1282 error_propagate(errp, local_err);
1283 return;
1286 if (has_node_name && !has_snapshot_node_name) {
1287 error_setg(errp, "New snapshot node name missing");
1288 return;
1291 if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1292 error_setg(errp, "New snapshot node name already existing");
1293 return;
1296 if (!bdrv_is_inserted(state->old_bs)) {
1297 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1298 return;
1301 if (bdrv_in_use(state->old_bs)) {
1302 error_set(errp, QERR_DEVICE_IN_USE, device);
1303 return;
1306 if (!bdrv_is_read_only(state->old_bs)) {
1307 if (bdrv_flush(state->old_bs)) {
1308 error_set(errp, QERR_IO_ERROR);
1309 return;
1313 if (!bdrv_is_first_non_filter(state->old_bs)) {
1314 error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1315 return;
1318 flags = state->old_bs->open_flags;
1320 /* create new image w/backing file */
1321 if (mode != NEW_IMAGE_MODE_EXISTING) {
1322 bdrv_img_create(new_image_file, format,
1323 state->old_bs->filename,
1324 state->old_bs->drv->format_name,
1325 NULL, -1, flags, &local_err, false);
1326 if (local_err) {
1327 error_propagate(errp, local_err);
1328 return;
1332 if (has_snapshot_node_name) {
1333 options = qdict_new();
1334 qdict_put(options, "node-name",
1335 qstring_from_str(snapshot_node_name));
1338 /* TODO Inherit bs->options or only take explicit options with an
1339 * extended QMP command? */
1340 assert(state->new_bs == NULL);
1341 ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1342 flags | BDRV_O_NO_BACKING, drv, &local_err);
1343 /* We will manually add the backing_hd field to the bs later */
1344 if (ret != 0) {
1345 error_propagate(errp, local_err);
1349 static void external_snapshot_commit(BlkTransactionState *common)
1351 ExternalSnapshotState *state =
1352 DO_UPCAST(ExternalSnapshotState, common, common);
1354 /* This removes our old bs and adds the new bs */
1355 bdrv_append(state->new_bs, state->old_bs);
1356 /* We don't need (or want) to use the transactional
1357 * bdrv_reopen_multiple() across all the entries at once, because we
1358 * don't want to abort all of them if one of them fails the reopen */
1359 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1360 NULL);
1363 static void external_snapshot_abort(BlkTransactionState *common)
1365 ExternalSnapshotState *state =
1366 DO_UPCAST(ExternalSnapshotState, common, common);
1367 if (state->new_bs) {
1368 bdrv_unref(state->new_bs);
1372 typedef struct DriveBackupState {
1373 BlkTransactionState common;
1374 BlockDriverState *bs;
1375 BlockJob *job;
1376 } DriveBackupState;
1378 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1380 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1381 DriveBackup *backup;
1382 Error *local_err = NULL;
1384 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1385 backup = common->action->drive_backup;
1387 qmp_drive_backup(backup->device, backup->target,
1388 backup->has_format, backup->format,
1389 backup->sync,
1390 backup->has_mode, backup->mode,
1391 backup->has_speed, backup->speed,
1392 backup->has_on_source_error, backup->on_source_error,
1393 backup->has_on_target_error, backup->on_target_error,
1394 &local_err);
1395 if (local_err) {
1396 error_propagate(errp, local_err);
1397 state->bs = NULL;
1398 state->job = NULL;
1399 return;
1402 state->bs = bdrv_find(backup->device);
1403 state->job = state->bs->job;
1406 static void drive_backup_abort(BlkTransactionState *common)
1408 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1409 BlockDriverState *bs = state->bs;
1411 /* Only cancel if it's the job we started */
1412 if (bs && bs->job && bs->job == state->job) {
1413 block_job_cancel_sync(bs->job);
1417 static void abort_prepare(BlkTransactionState *common, Error **errp)
1419 error_setg(errp, "Transaction aborted using Abort action");
1422 static void abort_commit(BlkTransactionState *common)
1424 g_assert_not_reached(); /* this action never succeeds */
1427 static const BdrvActionOps actions[] = {
1428 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1429 .instance_size = sizeof(ExternalSnapshotState),
1430 .prepare = external_snapshot_prepare,
1431 .commit = external_snapshot_commit,
1432 .abort = external_snapshot_abort,
1434 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1435 .instance_size = sizeof(DriveBackupState),
1436 .prepare = drive_backup_prepare,
1437 .abort = drive_backup_abort,
1439 [TRANSACTION_ACTION_KIND_ABORT] = {
1440 .instance_size = sizeof(BlkTransactionState),
1441 .prepare = abort_prepare,
1442 .commit = abort_commit,
1444 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1445 .instance_size = sizeof(InternalSnapshotState),
1446 .prepare = internal_snapshot_prepare,
1447 .abort = internal_snapshot_abort,
1452 * 'Atomic' group snapshots. The snapshots are taken as a set, and if any fail
1453 * then we do not pivot any of the devices in the group, and abandon the
1454 * snapshots
1456 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1458 TransactionActionList *dev_entry = dev_list;
1459 BlkTransactionState *state, *next;
1460 Error *local_err = NULL;
1462 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1463 QSIMPLEQ_INIT(&snap_bdrv_states);
1465 /* drain all i/o before any snapshots */
1466 bdrv_drain_all();
1468 /* We don't do anything in this loop that commits us to the snapshot */
1469 while (NULL != dev_entry) {
1470 TransactionAction *dev_info = NULL;
1471 const BdrvActionOps *ops;
1473 dev_info = dev_entry->value;
1474 dev_entry = dev_entry->next;
1476 assert(dev_info->kind < ARRAY_SIZE(actions));
1478 ops = &actions[dev_info->kind];
1479 assert(ops->instance_size > 0);
1481 state = g_malloc0(ops->instance_size);
1482 state->ops = ops;
1483 state->action = dev_info;
1484 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1486 state->ops->prepare(state, &local_err);
1487 if (local_err) {
1488 error_propagate(errp, local_err);
1489 goto delete_and_fail;
1493 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1494 if (state->ops->commit) {
1495 state->ops->commit(state);
1499 /* success */
1500 goto exit;
1502 delete_and_fail:
1504 * failure, and it is all-or-none; abandon each new bs, and keep using
1505 * the original bs for all images
1507 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1508 if (state->ops->abort) {
1509 state->ops->abort(state);
1512 exit:
1513 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1514 if (state->ops->clean) {
1515 state->ops->clean(state);
1517 g_free(state);
1522 static void eject_device(BlockDriverState *bs, int force, Error **errp)
1524 if (bdrv_in_use(bs)) {
1525 error_set(errp, QERR_DEVICE_IN_USE, bdrv_get_device_name(bs));
1526 return;
1528 if (!bdrv_dev_has_removable_media(bs)) {
1529 error_set(errp, QERR_DEVICE_NOT_REMOVABLE, bdrv_get_device_name(bs));
1530 return;
1533 if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
1534 bdrv_dev_eject_request(bs, force);
1535 if (!force) {
1536 error_set(errp, QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
1537 return;
1541 bdrv_close(bs);
1544 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1546 BlockDriverState *bs;
1548 bs = bdrv_find(device);
1549 if (!bs) {
1550 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1551 return;
1554 eject_device(bs, force, errp);
1557 void qmp_block_passwd(bool has_device, const char *device,
1558 bool has_node_name, const char *node_name,
1559 const char *password, Error **errp)
1561 Error *local_err = NULL;
1562 BlockDriverState *bs;
1563 int err;
1565 bs = bdrv_lookup_bs(has_device ? device : NULL,
1566 has_node_name ? node_name : NULL,
1567 &local_err);
1568 if (local_err) {
1569 error_propagate(errp, local_err);
1570 return;
1573 err = bdrv_set_key(bs, password);
1574 if (err == -EINVAL) {
1575 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1576 return;
1577 } else if (err < 0) {
1578 error_set(errp, QERR_INVALID_PASSWORD);
1579 return;
1583 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1584 int bdrv_flags, BlockDriver *drv,
1585 const char *password, Error **errp)
1587 Error *local_err = NULL;
1588 int ret;
1590 ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1591 if (ret < 0) {
1592 error_propagate(errp, local_err);
1593 return;
1596 if (bdrv_key_required(bs)) {
1597 if (password) {
1598 if (bdrv_set_key(bs, password) < 0) {
1599 error_set(errp, QERR_INVALID_PASSWORD);
1601 } else {
1602 error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1603 bdrv_get_encrypted_filename(bs));
1605 } else if (password) {
1606 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1610 void qmp_change_blockdev(const char *device, const char *filename,
1611 const char *format, Error **errp)
1613 BlockDriverState *bs;
1614 BlockDriver *drv = NULL;
1615 int bdrv_flags;
1616 Error *err = NULL;
1618 bs = bdrv_find(device);
1619 if (!bs) {
1620 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1621 return;
1624 if (format) {
1625 drv = bdrv_find_whitelisted_format(format, bs->read_only);
1626 if (!drv) {
1627 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1628 return;
1632 eject_device(bs, 0, &err);
1633 if (err) {
1634 error_propagate(errp, err);
1635 return;
1638 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1639 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1641 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1644 /* throttling disk I/O limits */
1645 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1646 int64_t bps_wr,
1647 int64_t iops,
1648 int64_t iops_rd,
1649 int64_t iops_wr,
1650 bool has_bps_max,
1651 int64_t bps_max,
1652 bool has_bps_rd_max,
1653 int64_t bps_rd_max,
1654 bool has_bps_wr_max,
1655 int64_t bps_wr_max,
1656 bool has_iops_max,
1657 int64_t iops_max,
1658 bool has_iops_rd_max,
1659 int64_t iops_rd_max,
1660 bool has_iops_wr_max,
1661 int64_t iops_wr_max,
1662 bool has_iops_size,
1663 int64_t iops_size, Error **errp)
1665 ThrottleConfig cfg;
1666 BlockDriverState *bs;
1668 bs = bdrv_find(device);
1669 if (!bs) {
1670 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1671 return;
1674 memset(&cfg, 0, sizeof(cfg));
1675 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1676 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1677 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1679 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1680 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1681 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1683 if (has_bps_max) {
1684 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1686 if (has_bps_rd_max) {
1687 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1689 if (has_bps_wr_max) {
1690 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1692 if (has_iops_max) {
1693 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1695 if (has_iops_rd_max) {
1696 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1698 if (has_iops_wr_max) {
1699 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1702 if (has_iops_size) {
1703 cfg.op_size = iops_size;
1706 if (!check_throttle_config(&cfg, errp)) {
1707 return;
1710 if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
1711 bdrv_io_limits_enable(bs);
1712 } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
1713 bdrv_io_limits_disable(bs);
1716 if (bs->io_limits_enabled) {
1717 bdrv_set_io_limits(bs, &cfg);
1721 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1723 const char *id = qdict_get_str(qdict, "id");
1724 BlockDriverState *bs;
1726 bs = bdrv_find(id);
1727 if (!bs) {
1728 qerror_report(QERR_DEVICE_NOT_FOUND, id);
1729 return -1;
1731 if (bdrv_in_use(bs)) {
1732 qerror_report(QERR_DEVICE_IN_USE, id);
1733 return -1;
1736 /* quiesce block driver; prevent further io */
1737 bdrv_drain_all();
1738 bdrv_flush(bs);
1739 bdrv_close(bs);
1741 /* if we have a device attached to this BlockDriverState
1742 * then we need to make the drive anonymous until the device
1743 * can be removed. If this is a drive with no device backing
1744 * then we can just get rid of the block driver state right here.
1746 if (bdrv_get_attached_dev(bs)) {
1747 bdrv_make_anon(bs);
1749 /* Further I/O must not pause the guest */
1750 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1751 BLOCKDEV_ON_ERROR_REPORT);
1752 } else {
1753 drive_uninit(drive_get_by_blockdev(bs));
1756 return 0;
1759 void qmp_block_resize(bool has_device, const char *device,
1760 bool has_node_name, const char *node_name,
1761 int64_t size, Error **errp)
1763 Error *local_err = NULL;
1764 BlockDriverState *bs;
1765 int ret;
1767 bs = bdrv_lookup_bs(has_device ? device : NULL,
1768 has_node_name ? node_name : NULL,
1769 &local_err);
1770 if (local_err) {
1771 error_propagate(errp, local_err);
1772 return;
1775 if (!bdrv_is_first_non_filter(bs)) {
1776 error_set(errp, QERR_FEATURE_DISABLED, "resize");
1777 return;
1780 if (size < 0) {
1781 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1782 return;
1785 /* complete all in-flight operations before resizing the device */
1786 bdrv_drain_all();
1788 ret = bdrv_truncate(bs, size);
1789 switch (ret) {
1790 case 0:
1791 break;
1792 case -ENOMEDIUM:
1793 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1794 break;
1795 case -ENOTSUP:
1796 error_set(errp, QERR_UNSUPPORTED);
1797 break;
1798 case -EACCES:
1799 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1800 break;
1801 case -EBUSY:
1802 error_set(errp, QERR_DEVICE_IN_USE, device);
1803 break;
1804 default:
1805 error_setg_errno(errp, -ret, "Could not resize");
1806 break;
1810 static void block_job_cb(void *opaque, int ret)
1812 BlockDriverState *bs = opaque;
1813 QObject *obj;
1815 trace_block_job_cb(bs, bs->job, ret);
1817 assert(bs->job);
1818 obj = qobject_from_block_job(bs->job);
1819 if (ret < 0) {
1820 QDict *dict = qobject_to_qdict(obj);
1821 qdict_put(dict, "error", qstring_from_str(strerror(-ret)));
1824 if (block_job_is_cancelled(bs->job)) {
1825 monitor_protocol_event(QEVENT_BLOCK_JOB_CANCELLED, obj);
1826 } else {
1827 monitor_protocol_event(QEVENT_BLOCK_JOB_COMPLETED, obj);
1829 qobject_decref(obj);
1831 bdrv_put_ref_bh_schedule(bs);
1834 void qmp_block_stream(const char *device, bool has_base,
1835 const char *base, bool has_speed, int64_t speed,
1836 bool has_on_error, BlockdevOnError on_error,
1837 Error **errp)
1839 BlockDriverState *bs;
1840 BlockDriverState *base_bs = NULL;
1841 Error *local_err = NULL;
1843 if (!has_on_error) {
1844 on_error = BLOCKDEV_ON_ERROR_REPORT;
1847 bs = bdrv_find(device);
1848 if (!bs) {
1849 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1850 return;
1853 if (base) {
1854 base_bs = bdrv_find_backing_image(bs, base);
1855 if (base_bs == NULL) {
1856 error_set(errp, QERR_BASE_NOT_FOUND, base);
1857 return;
1861 stream_start(bs, base_bs, base, has_speed ? speed : 0,
1862 on_error, block_job_cb, bs, &local_err);
1863 if (local_err) {
1864 error_propagate(errp, local_err);
1865 return;
1868 trace_qmp_block_stream(bs, bs->job);
1871 void qmp_block_commit(const char *device,
1872 bool has_base, const char *base, const char *top,
1873 bool has_speed, int64_t speed,
1874 Error **errp)
1876 BlockDriverState *bs;
1877 BlockDriverState *base_bs, *top_bs;
1878 Error *local_err = NULL;
1879 /* This will be part of the QMP command, if/when the
1880 * BlockdevOnError change for blkmirror makes it in
1882 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
1884 if (!has_speed) {
1885 speed = 0;
1888 /* drain all i/o before commits */
1889 bdrv_drain_all();
1891 bs = bdrv_find(device);
1892 if (!bs) {
1893 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1894 return;
1897 /* default top_bs is the active layer */
1898 top_bs = bs;
1900 if (top) {
1901 if (strcmp(bs->filename, top) != 0) {
1902 top_bs = bdrv_find_backing_image(bs, top);
1906 if (top_bs == NULL) {
1907 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
1908 return;
1911 if (has_base && base) {
1912 base_bs = bdrv_find_backing_image(top_bs, base);
1913 } else {
1914 base_bs = bdrv_find_base(top_bs);
1917 if (base_bs == NULL) {
1918 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
1919 return;
1922 if (top_bs == bs) {
1923 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
1924 bs, &local_err);
1925 } else {
1926 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
1927 &local_err);
1929 if (local_err != NULL) {
1930 error_propagate(errp, local_err);
1931 return;
1935 void qmp_drive_backup(const char *device, const char *target,
1936 bool has_format, const char *format,
1937 enum MirrorSyncMode sync,
1938 bool has_mode, enum NewImageMode mode,
1939 bool has_speed, int64_t speed,
1940 bool has_on_source_error, BlockdevOnError on_source_error,
1941 bool has_on_target_error, BlockdevOnError on_target_error,
1942 Error **errp)
1944 BlockDriverState *bs;
1945 BlockDriverState *target_bs;
1946 BlockDriverState *source = NULL;
1947 BlockDriver *drv = NULL;
1948 Error *local_err = NULL;
1949 int flags;
1950 int64_t size;
1951 int ret;
1953 if (!has_speed) {
1954 speed = 0;
1956 if (!has_on_source_error) {
1957 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
1959 if (!has_on_target_error) {
1960 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
1962 if (!has_mode) {
1963 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1966 bs = bdrv_find(device);
1967 if (!bs) {
1968 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1969 return;
1972 if (!bdrv_is_inserted(bs)) {
1973 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1974 return;
1977 if (!has_format) {
1978 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
1980 if (format) {
1981 drv = bdrv_find_format(format);
1982 if (!drv) {
1983 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1984 return;
1988 if (bdrv_in_use(bs)) {
1989 error_set(errp, QERR_DEVICE_IN_USE, device);
1990 return;
1993 flags = bs->open_flags | BDRV_O_RDWR;
1995 /* See if we have a backing HD we can use to create our new image
1996 * on top of. */
1997 if (sync == MIRROR_SYNC_MODE_TOP) {
1998 source = bs->backing_hd;
1999 if (!source) {
2000 sync = MIRROR_SYNC_MODE_FULL;
2003 if (sync == MIRROR_SYNC_MODE_NONE) {
2004 source = bs;
2007 size = bdrv_getlength(bs);
2008 if (size < 0) {
2009 error_setg_errno(errp, -size, "bdrv_getlength failed");
2010 return;
2013 if (mode != NEW_IMAGE_MODE_EXISTING) {
2014 assert(format && drv);
2015 if (source) {
2016 bdrv_img_create(target, format, source->filename,
2017 source->drv->format_name, NULL,
2018 size, flags, &local_err, false);
2019 } else {
2020 bdrv_img_create(target, format, NULL, NULL, NULL,
2021 size, flags, &local_err, false);
2025 if (local_err) {
2026 error_propagate(errp, local_err);
2027 return;
2030 target_bs = NULL;
2031 ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2032 if (ret < 0) {
2033 error_propagate(errp, local_err);
2034 return;
2037 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2038 block_job_cb, bs, &local_err);
2039 if (local_err != NULL) {
2040 bdrv_unref(target_bs);
2041 error_propagate(errp, local_err);
2042 return;
2046 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2048 return bdrv_named_nodes_list();
2051 #define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
2053 void qmp_drive_mirror(const char *device, const char *target,
2054 bool has_format, const char *format,
2055 enum MirrorSyncMode sync,
2056 bool has_mode, enum NewImageMode mode,
2057 bool has_speed, int64_t speed,
2058 bool has_granularity, uint32_t granularity,
2059 bool has_buf_size, int64_t buf_size,
2060 bool has_on_source_error, BlockdevOnError on_source_error,
2061 bool has_on_target_error, BlockdevOnError on_target_error,
2062 Error **errp)
2064 BlockDriverState *bs;
2065 BlockDriverState *source, *target_bs;
2066 BlockDriver *drv = NULL;
2067 Error *local_err = NULL;
2068 int flags;
2069 int64_t size;
2070 int ret;
2072 if (!has_speed) {
2073 speed = 0;
2075 if (!has_on_source_error) {
2076 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2078 if (!has_on_target_error) {
2079 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2081 if (!has_mode) {
2082 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2084 if (!has_granularity) {
2085 granularity = 0;
2087 if (!has_buf_size) {
2088 buf_size = DEFAULT_MIRROR_BUF_SIZE;
2091 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2092 error_set(errp, QERR_INVALID_PARAMETER, device);
2093 return;
2095 if (granularity & (granularity - 1)) {
2096 error_set(errp, QERR_INVALID_PARAMETER, device);
2097 return;
2100 bs = bdrv_find(device);
2101 if (!bs) {
2102 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2103 return;
2106 if (!bdrv_is_inserted(bs)) {
2107 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2108 return;
2111 if (!has_format) {
2112 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2114 if (format) {
2115 drv = bdrv_find_format(format);
2116 if (!drv) {
2117 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2118 return;
2122 if (bdrv_in_use(bs)) {
2123 error_set(errp, QERR_DEVICE_IN_USE, device);
2124 return;
2127 flags = bs->open_flags | BDRV_O_RDWR;
2128 source = bs->backing_hd;
2129 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2130 sync = MIRROR_SYNC_MODE_FULL;
2132 if (sync == MIRROR_SYNC_MODE_NONE) {
2133 source = bs;
2136 size = bdrv_getlength(bs);
2137 if (size < 0) {
2138 error_setg_errno(errp, -size, "bdrv_getlength failed");
2139 return;
2142 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2143 && mode != NEW_IMAGE_MODE_EXISTING)
2145 /* create new image w/o backing file */
2146 assert(format && drv);
2147 bdrv_img_create(target, format,
2148 NULL, NULL, NULL, size, flags, &local_err, false);
2149 } else {
2150 switch (mode) {
2151 case NEW_IMAGE_MODE_EXISTING:
2152 break;
2153 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2154 /* create new image with backing file */
2155 bdrv_img_create(target, format,
2156 source->filename,
2157 source->drv->format_name,
2158 NULL, size, flags, &local_err, false);
2159 break;
2160 default:
2161 abort();
2165 if (local_err) {
2166 error_propagate(errp, local_err);
2167 return;
2170 /* Mirroring takes care of copy-on-write using the source's backing
2171 * file.
2173 target_bs = NULL;
2174 ret = bdrv_open(&target_bs, target, NULL, NULL, flags | BDRV_O_NO_BACKING,
2175 drv, &local_err);
2176 if (ret < 0) {
2177 error_propagate(errp, local_err);
2178 return;
2181 mirror_start(bs, target_bs, speed, granularity, buf_size, sync,
2182 on_source_error, on_target_error,
2183 block_job_cb, bs, &local_err);
2184 if (local_err != NULL) {
2185 bdrv_unref(target_bs);
2186 error_propagate(errp, local_err);
2187 return;
2191 static BlockJob *find_block_job(const char *device)
2193 BlockDriverState *bs;
2195 bs = bdrv_find(device);
2196 if (!bs || !bs->job) {
2197 return NULL;
2199 return bs->job;
2202 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2204 BlockJob *job = find_block_job(device);
2206 if (!job) {
2207 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2208 return;
2211 block_job_set_speed(job, speed, errp);
2214 void qmp_block_job_cancel(const char *device,
2215 bool has_force, bool force, Error **errp)
2217 BlockJob *job = find_block_job(device);
2219 if (!has_force) {
2220 force = false;
2223 if (!job) {
2224 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2225 return;
2227 if (job->paused && !force) {
2228 error_set(errp, QERR_BLOCK_JOB_PAUSED, device);
2229 return;
2232 trace_qmp_block_job_cancel(job);
2233 block_job_cancel(job);
2236 void qmp_block_job_pause(const char *device, Error **errp)
2238 BlockJob *job = find_block_job(device);
2240 if (!job) {
2241 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2242 return;
2245 trace_qmp_block_job_pause(job);
2246 block_job_pause(job);
2249 void qmp_block_job_resume(const char *device, Error **errp)
2251 BlockJob *job = find_block_job(device);
2253 if (!job) {
2254 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2255 return;
2258 trace_qmp_block_job_resume(job);
2259 block_job_resume(job);
2262 void qmp_block_job_complete(const char *device, Error **errp)
2264 BlockJob *job = find_block_job(device);
2266 if (!job) {
2267 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2268 return;
2271 trace_qmp_block_job_complete(job);
2272 block_job_complete(job, errp);
2275 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2277 QmpOutputVisitor *ov = qmp_output_visitor_new();
2278 DriveInfo *dinfo;
2279 QObject *obj;
2280 QDict *qdict;
2281 Error *local_err = NULL;
2283 /* Require an ID in the top level */
2284 if (!options->has_id) {
2285 error_setg(errp, "Block device needs an ID");
2286 goto fail;
2289 /* TODO Sort it out in raw-posix and drive_init: Reject aio=native with
2290 * cache.direct=false instead of silently switching to aio=threads, except
2291 * if called from drive_init.
2293 * For now, simply forbidding the combination for all drivers will do. */
2294 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2295 bool direct = options->has_cache &&
2296 options->cache->has_direct &&
2297 options->cache->direct;
2298 if (!direct) {
2299 error_setg(errp, "aio=native requires cache.direct=true");
2300 goto fail;
2304 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2305 &options, NULL, &local_err);
2306 if (local_err) {
2307 error_propagate(errp, local_err);
2308 goto fail;
2311 obj = qmp_output_get_qobject(ov);
2312 qdict = qobject_to_qdict(obj);
2314 qdict_flatten(qdict);
2316 dinfo = blockdev_init(NULL, qdict, &local_err);
2317 if (local_err) {
2318 error_propagate(errp, local_err);
2319 goto fail;
2322 if (bdrv_key_required(dinfo->bdrv)) {
2323 drive_uninit(dinfo);
2324 error_setg(errp, "blockdev-add doesn't support encrypted devices");
2325 goto fail;
2328 fail:
2329 qmp_output_visitor_cleanup(ov);
2332 static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
2334 BlockJobInfoList **prev = opaque;
2335 BlockJob *job = bs->job;
2337 if (job) {
2338 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2339 elem->value = block_job_query(bs->job);
2340 (*prev)->next = elem;
2341 *prev = elem;
2345 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2347 /* Dummy is a fake list element for holding the head pointer */
2348 BlockJobInfoList dummy = {};
2349 BlockJobInfoList *prev = &dummy;
2350 bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
2351 return dummy.next;
2354 QemuOptsList qemu_common_drive_opts = {
2355 .name = "drive",
2356 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2357 .desc = {
2359 .name = "snapshot",
2360 .type = QEMU_OPT_BOOL,
2361 .help = "enable/disable snapshot mode",
2363 .name = "discard",
2364 .type = QEMU_OPT_STRING,
2365 .help = "discard operation (ignore/off, unmap/on)",
2367 .name = "cache.writeback",
2368 .type = QEMU_OPT_BOOL,
2369 .help = "enables writeback mode for any caches",
2371 .name = "cache.direct",
2372 .type = QEMU_OPT_BOOL,
2373 .help = "enables use of O_DIRECT (bypass the host page cache)",
2375 .name = "cache.no-flush",
2376 .type = QEMU_OPT_BOOL,
2377 .help = "ignore any flush requests for the device",
2379 .name = "aio",
2380 .type = QEMU_OPT_STRING,
2381 .help = "host AIO implementation (threads, native)",
2383 .name = "format",
2384 .type = QEMU_OPT_STRING,
2385 .help = "disk format (raw, qcow2, ...)",
2387 .name = "serial",
2388 .type = QEMU_OPT_STRING,
2389 .help = "disk serial number",
2391 .name = "rerror",
2392 .type = QEMU_OPT_STRING,
2393 .help = "read error action",
2395 .name = "werror",
2396 .type = QEMU_OPT_STRING,
2397 .help = "write error action",
2399 .name = "read-only",
2400 .type = QEMU_OPT_BOOL,
2401 .help = "open drive file as read-only",
2403 .name = "throttling.iops-total",
2404 .type = QEMU_OPT_NUMBER,
2405 .help = "limit total I/O operations per second",
2407 .name = "throttling.iops-read",
2408 .type = QEMU_OPT_NUMBER,
2409 .help = "limit read operations per second",
2411 .name = "throttling.iops-write",
2412 .type = QEMU_OPT_NUMBER,
2413 .help = "limit write operations per second",
2415 .name = "throttling.bps-total",
2416 .type = QEMU_OPT_NUMBER,
2417 .help = "limit total bytes per second",
2419 .name = "throttling.bps-read",
2420 .type = QEMU_OPT_NUMBER,
2421 .help = "limit read bytes per second",
2423 .name = "throttling.bps-write",
2424 .type = QEMU_OPT_NUMBER,
2425 .help = "limit write bytes per second",
2427 .name = "throttling.iops-total-max",
2428 .type = QEMU_OPT_NUMBER,
2429 .help = "I/O operations burst",
2431 .name = "throttling.iops-read-max",
2432 .type = QEMU_OPT_NUMBER,
2433 .help = "I/O operations read burst",
2435 .name = "throttling.iops-write-max",
2436 .type = QEMU_OPT_NUMBER,
2437 .help = "I/O operations write burst",
2439 .name = "throttling.bps-total-max",
2440 .type = QEMU_OPT_NUMBER,
2441 .help = "total bytes burst",
2443 .name = "throttling.bps-read-max",
2444 .type = QEMU_OPT_NUMBER,
2445 .help = "total bytes read burst",
2447 .name = "throttling.bps-write-max",
2448 .type = QEMU_OPT_NUMBER,
2449 .help = "total bytes write burst",
2451 .name = "throttling.iops-size",
2452 .type = QEMU_OPT_NUMBER,
2453 .help = "when limiting by iops max size of an I/O in bytes",
2455 .name = "copy-on-read",
2456 .type = QEMU_OPT_BOOL,
2457 .help = "copy read data from backing file into image file",
2459 { /* end of list */ }
2463 QemuOptsList qemu_drive_opts = {
2464 .name = "drive",
2465 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2466 .desc = {
2468 * no elements => accept any params
2469 * validation will happen later
2471 { /* end of list */ }