blockdev: Rename drive_init(), drive_uninit() to drive_new(), drive_del()
[qemu.git] / blockdev.c
blob0ed03b770fb4ebd8e3a3e169dbe6277e35cf15bd
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 "qemu/option.h"
38 #include "qemu/config-file.h"
39 #include "qapi/qmp/types.h"
40 #include "qapi-visit.h"
41 #include "qapi/qmp-output-visitor.h"
42 #include "sysemu/sysemu.h"
43 #include "block/block_int.h"
44 #include "qmp-commands.h"
45 #include "trace.h"
46 #include "sysemu/arch_init.h"
48 static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
50 static const char *const if_name[IF_COUNT] = {
51 [IF_NONE] = "none",
52 [IF_IDE] = "ide",
53 [IF_SCSI] = "scsi",
54 [IF_FLOPPY] = "floppy",
55 [IF_PFLASH] = "pflash",
56 [IF_MTD] = "mtd",
57 [IF_SD] = "sd",
58 [IF_VIRTIO] = "virtio",
59 [IF_XEN] = "xen",
62 static const int if_max_devs[IF_COUNT] = {
64 * Do not change these numbers! They govern how drive option
65 * index maps to unit and bus. That mapping is ABI.
67 * All controllers used to imlement if=T drives need to support
68 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
69 * Otherwise, some index values map to "impossible" bus, unit
70 * values.
72 * For instance, if you change [IF_SCSI] to 255, -drive
73 * if=scsi,index=12 no longer means bus=1,unit=5, but
74 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
75 * the drive can't be set up. Regression.
77 [IF_IDE] = 2,
78 [IF_SCSI] = 7,
82 * We automatically delete the drive when a device using it gets
83 * unplugged. Questionable feature, but we can't just drop it.
84 * Device models call blockdev_mark_auto_del() to schedule the
85 * automatic deletion, and generic qdev code calls blockdev_auto_del()
86 * when deletion is actually safe.
88 void blockdev_mark_auto_del(BlockDriverState *bs)
90 DriveInfo *dinfo = drive_get_by_blockdev(bs);
92 if (dinfo && !dinfo->enable_auto_del) {
93 return;
96 if (bs->job) {
97 block_job_cancel(bs->job);
99 if (dinfo) {
100 dinfo->auto_del = 1;
104 void blockdev_auto_del(BlockDriverState *bs)
106 DriveInfo *dinfo = drive_get_by_blockdev(bs);
108 if (dinfo && dinfo->auto_del) {
109 drive_put_ref(dinfo);
113 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
115 int max_devs = if_max_devs[type];
116 return max_devs ? index / max_devs : 0;
119 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
121 int max_devs = if_max_devs[type];
122 return max_devs ? index % max_devs : index;
125 QemuOpts *drive_def(const char *optstr)
127 return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
130 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
131 const char *optstr)
133 QemuOpts *opts;
134 char buf[32];
136 opts = drive_def(optstr);
137 if (!opts) {
138 return NULL;
140 if (type != IF_DEFAULT) {
141 qemu_opt_set(opts, "if", if_name[type]);
143 if (index >= 0) {
144 snprintf(buf, sizeof(buf), "%d", index);
145 qemu_opt_set(opts, "index", buf);
147 if (file)
148 qemu_opt_set(opts, "file", file);
149 return opts;
152 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
154 DriveInfo *dinfo;
156 /* seek interface, bus and unit */
158 QTAILQ_FOREACH(dinfo, &drives, next) {
159 if (dinfo->type == type &&
160 dinfo->bus == bus &&
161 dinfo->unit == unit)
162 return dinfo;
165 return NULL;
168 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
170 return drive_get(type,
171 drive_index_to_bus_id(type, index),
172 drive_index_to_unit_id(type, index));
175 int drive_get_max_bus(BlockInterfaceType type)
177 int max_bus;
178 DriveInfo *dinfo;
180 max_bus = -1;
181 QTAILQ_FOREACH(dinfo, &drives, next) {
182 if(dinfo->type == type &&
183 dinfo->bus > max_bus)
184 max_bus = dinfo->bus;
186 return max_bus;
189 /* Get a block device. This should only be used for single-drive devices
190 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
191 appropriate bus. */
192 DriveInfo *drive_get_next(BlockInterfaceType type)
194 static int next_block_unit[IF_COUNT];
196 return drive_get(type, 0, next_block_unit[type]++);
199 DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
201 DriveInfo *dinfo;
203 QTAILQ_FOREACH(dinfo, &drives, next) {
204 if (dinfo->bdrv == bs) {
205 return dinfo;
208 return NULL;
211 static void bdrv_format_print(void *opaque, const char *name)
213 error_printf(" %s", name);
216 static void drive_del(DriveInfo *dinfo)
218 if (dinfo->opts) {
219 qemu_opts_del(dinfo->opts);
222 bdrv_unref(dinfo->bdrv);
223 g_free(dinfo->id);
224 QTAILQ_REMOVE(&drives, dinfo, next);
225 g_free(dinfo->serial);
226 g_free(dinfo);
229 void drive_put_ref(DriveInfo *dinfo)
231 assert(dinfo->refcount);
232 if (--dinfo->refcount == 0) {
233 drive_del(dinfo);
237 void drive_get_ref(DriveInfo *dinfo)
239 dinfo->refcount++;
242 typedef struct {
243 QEMUBH *bh;
244 BlockDriverState *bs;
245 } BDRVPutRefBH;
247 static void bdrv_put_ref_bh(void *opaque)
249 BDRVPutRefBH *s = opaque;
251 bdrv_unref(s->bs);
252 qemu_bh_delete(s->bh);
253 g_free(s);
257 * Release a BDS reference in a BH
259 * It is not safe to use bdrv_unref() from a callback function when the callers
260 * still need the BlockDriverState. In such cases we schedule a BH to release
261 * the reference.
263 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
265 BDRVPutRefBH *s;
267 s = g_new(BDRVPutRefBH, 1);
268 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
269 s->bs = bs;
270 qemu_bh_schedule(s->bh);
273 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
275 if (!strcmp(buf, "ignore")) {
276 return BLOCKDEV_ON_ERROR_IGNORE;
277 } else if (!is_read && !strcmp(buf, "enospc")) {
278 return BLOCKDEV_ON_ERROR_ENOSPC;
279 } else if (!strcmp(buf, "stop")) {
280 return BLOCKDEV_ON_ERROR_STOP;
281 } else if (!strcmp(buf, "report")) {
282 return BLOCKDEV_ON_ERROR_REPORT;
283 } else {
284 error_setg(errp, "'%s' invalid %s error action",
285 buf, is_read ? "read" : "write");
286 return -1;
290 static inline int parse_enum_option(const char *lookup[], const char *buf,
291 int max, int def, Error **errp)
293 int i;
295 if (!buf) {
296 return def;
299 for (i = 0; i < max; i++) {
300 if (!strcmp(buf, lookup[i])) {
301 return i;
305 error_setg(errp, "invalid parameter value: %s", buf);
306 return def;
309 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
311 if (throttle_conflicting(cfg)) {
312 error_setg(errp, "bps/iops/max total values and read/write values"
313 " cannot be used at the same time");
314 return false;
317 if (!throttle_is_valid(cfg)) {
318 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
319 return false;
322 return true;
325 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
327 /* Takes the ownership of bs_opts */
328 static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
329 Error **errp)
331 const char *buf;
332 int ro = 0;
333 int bdrv_flags = 0;
334 int on_read_error, on_write_error;
335 DriveInfo *dinfo;
336 ThrottleConfig cfg;
337 int snapshot = 0;
338 bool copy_on_read;
339 int ret;
340 Error *error = NULL;
341 QemuOpts *opts;
342 const char *id;
343 bool has_driver_specific_opts;
344 BlockdevDetectZeroesOptions detect_zeroes;
345 BlockDriver *drv = NULL;
347 /* Check common options by copying from bs_opts to opts, all other options
348 * stay in bs_opts for processing by bdrv_open(). */
349 id = qdict_get_try_str(bs_opts, "id");
350 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
351 if (error) {
352 error_propagate(errp, error);
353 goto err_no_opts;
356 qemu_opts_absorb_qdict(opts, bs_opts, &error);
357 if (error) {
358 error_propagate(errp, error);
359 goto early_err;
362 if (id) {
363 qdict_del(bs_opts, "id");
366 has_driver_specific_opts = !!qdict_size(bs_opts);
368 /* extract parameters */
369 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
370 ro = qemu_opt_get_bool(opts, "read-only", 0);
371 copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
373 if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
374 if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
375 error_setg(errp, "invalid discard option");
376 goto early_err;
380 if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
381 bdrv_flags |= BDRV_O_CACHE_WB;
383 if (qemu_opt_get_bool(opts, "cache.direct", false)) {
384 bdrv_flags |= BDRV_O_NOCACHE;
386 if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
387 bdrv_flags |= BDRV_O_NO_FLUSH;
390 #ifdef CONFIG_LINUX_AIO
391 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
392 if (!strcmp(buf, "native")) {
393 bdrv_flags |= BDRV_O_NATIVE_AIO;
394 } else if (!strcmp(buf, "threads")) {
395 /* this is the default */
396 } else {
397 error_setg(errp, "invalid aio option");
398 goto early_err;
401 #endif
403 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
404 if (is_help_option(buf)) {
405 error_printf("Supported formats:");
406 bdrv_iterate_format(bdrv_format_print, NULL);
407 error_printf("\n");
408 goto early_err;
411 drv = bdrv_find_format(buf);
412 if (!drv) {
413 error_setg(errp, "'%s' invalid format", buf);
414 goto early_err;
418 /* disk I/O throttling */
419 memset(&cfg, 0, sizeof(cfg));
420 cfg.buckets[THROTTLE_BPS_TOTAL].avg =
421 qemu_opt_get_number(opts, "throttling.bps-total", 0);
422 cfg.buckets[THROTTLE_BPS_READ].avg =
423 qemu_opt_get_number(opts, "throttling.bps-read", 0);
424 cfg.buckets[THROTTLE_BPS_WRITE].avg =
425 qemu_opt_get_number(opts, "throttling.bps-write", 0);
426 cfg.buckets[THROTTLE_OPS_TOTAL].avg =
427 qemu_opt_get_number(opts, "throttling.iops-total", 0);
428 cfg.buckets[THROTTLE_OPS_READ].avg =
429 qemu_opt_get_number(opts, "throttling.iops-read", 0);
430 cfg.buckets[THROTTLE_OPS_WRITE].avg =
431 qemu_opt_get_number(opts, "throttling.iops-write", 0);
433 cfg.buckets[THROTTLE_BPS_TOTAL].max =
434 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
435 cfg.buckets[THROTTLE_BPS_READ].max =
436 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
437 cfg.buckets[THROTTLE_BPS_WRITE].max =
438 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
439 cfg.buckets[THROTTLE_OPS_TOTAL].max =
440 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
441 cfg.buckets[THROTTLE_OPS_READ].max =
442 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
443 cfg.buckets[THROTTLE_OPS_WRITE].max =
444 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
446 cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
448 if (!check_throttle_config(&cfg, &error)) {
449 error_propagate(errp, error);
450 goto early_err;
453 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
454 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
455 on_write_error = parse_block_error_action(buf, 0, &error);
456 if (error) {
457 error_propagate(errp, error);
458 goto early_err;
462 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
463 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
464 on_read_error = parse_block_error_action(buf, 1, &error);
465 if (error) {
466 error_propagate(errp, error);
467 goto early_err;
471 detect_zeroes =
472 parse_enum_option(BlockdevDetectZeroesOptions_lookup,
473 qemu_opt_get(opts, "detect-zeroes"),
474 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
475 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
476 &error);
477 if (error) {
478 error_propagate(errp, error);
479 goto early_err;
482 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
483 !(bdrv_flags & BDRV_O_UNMAP)) {
484 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
485 "without setting discard operation to unmap");
486 goto early_err;
489 /* init */
490 dinfo = g_malloc0(sizeof(*dinfo));
491 dinfo->id = g_strdup(qemu_opts_id(opts));
492 dinfo->bdrv = bdrv_new(dinfo->id, &error);
493 if (error) {
494 error_propagate(errp, error);
495 goto bdrv_new_err;
497 dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
498 dinfo->bdrv->read_only = ro;
499 dinfo->bdrv->detect_zeroes = detect_zeroes;
500 dinfo->refcount = 1;
501 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
503 bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);
505 /* disk I/O throttling */
506 if (throttle_enabled(&cfg)) {
507 bdrv_io_limits_enable(dinfo->bdrv);
508 bdrv_set_io_limits(dinfo->bdrv, &cfg);
511 if (!file || !*file) {
512 if (has_driver_specific_opts) {
513 file = NULL;
514 } else {
515 QDECREF(bs_opts);
516 qemu_opts_del(opts);
517 return dinfo;
520 if (snapshot) {
521 /* always use cache=unsafe with snapshot */
522 bdrv_flags &= ~BDRV_O_CACHE_MASK;
523 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
526 if (copy_on_read) {
527 bdrv_flags |= BDRV_O_COPY_ON_READ;
530 if (runstate_check(RUN_STATE_INMIGRATE)) {
531 bdrv_flags |= BDRV_O_INCOMING;
534 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
536 QINCREF(bs_opts);
537 ret = bdrv_open(&dinfo->bdrv, file, NULL, bs_opts, bdrv_flags, drv, &error);
539 if (ret < 0) {
540 error_setg(errp, "could not open disk image %s: %s",
541 file ?: dinfo->id, error_get_pretty(error));
542 error_free(error);
543 goto err;
546 if (bdrv_key_required(dinfo->bdrv))
547 autostart = 0;
549 QDECREF(bs_opts);
550 qemu_opts_del(opts);
552 return dinfo;
554 err:
555 bdrv_unref(dinfo->bdrv);
556 QTAILQ_REMOVE(&drives, dinfo, next);
557 bdrv_new_err:
558 g_free(dinfo->id);
559 g_free(dinfo);
560 early_err:
561 qemu_opts_del(opts);
562 err_no_opts:
563 QDECREF(bs_opts);
564 return NULL;
567 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to)
569 const char *value;
571 value = qemu_opt_get(opts, from);
572 if (value) {
573 qemu_opt_set(opts, to, value);
574 qemu_opt_unset(opts, from);
578 QemuOptsList qemu_legacy_drive_opts = {
579 .name = "drive",
580 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
581 .desc = {
583 .name = "bus",
584 .type = QEMU_OPT_NUMBER,
585 .help = "bus number",
587 .name = "unit",
588 .type = QEMU_OPT_NUMBER,
589 .help = "unit number (i.e. lun for scsi)",
591 .name = "index",
592 .type = QEMU_OPT_NUMBER,
593 .help = "index number",
595 .name = "media",
596 .type = QEMU_OPT_STRING,
597 .help = "media type (disk, cdrom)",
599 .name = "if",
600 .type = QEMU_OPT_STRING,
601 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
603 .name = "cyls",
604 .type = QEMU_OPT_NUMBER,
605 .help = "number of cylinders (ide disk geometry)",
607 .name = "heads",
608 .type = QEMU_OPT_NUMBER,
609 .help = "number of heads (ide disk geometry)",
611 .name = "secs",
612 .type = QEMU_OPT_NUMBER,
613 .help = "number of sectors (ide disk geometry)",
615 .name = "trans",
616 .type = QEMU_OPT_STRING,
617 .help = "chs translation (auto, lba, none)",
619 .name = "boot",
620 .type = QEMU_OPT_BOOL,
621 .help = "(deprecated, ignored)",
623 .name = "addr",
624 .type = QEMU_OPT_STRING,
625 .help = "pci address (virtio only)",
627 .name = "serial",
628 .type = QEMU_OPT_STRING,
629 .help = "disk serial number",
631 .name = "file",
632 .type = QEMU_OPT_STRING,
633 .help = "file name",
636 /* Options that are passed on, but have special semantics with -drive */
638 .name = "read-only",
639 .type = QEMU_OPT_BOOL,
640 .help = "open drive file as read-only",
642 .name = "rerror",
643 .type = QEMU_OPT_STRING,
644 .help = "read error action",
646 .name = "werror",
647 .type = QEMU_OPT_STRING,
648 .help = "write error action",
650 .name = "copy-on-read",
651 .type = QEMU_OPT_BOOL,
652 .help = "copy read data from backing file into image file",
655 { /* end of list */ }
659 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
661 const char *value;
662 DriveInfo *dinfo = NULL;
663 QDict *bs_opts;
664 QemuOpts *legacy_opts;
665 DriveMediaType media = MEDIA_DISK;
666 BlockInterfaceType type;
667 int cyls, heads, secs, translation;
668 int max_devs, bus_id, unit_id, index;
669 const char *devaddr;
670 const char *werror, *rerror;
671 bool read_only = false;
672 bool copy_on_read;
673 const char *serial;
674 const char *filename;
675 Error *local_err = NULL;
677 /* Change legacy command line options into QMP ones */
678 qemu_opt_rename(all_opts, "iops", "throttling.iops-total");
679 qemu_opt_rename(all_opts, "iops_rd", "throttling.iops-read");
680 qemu_opt_rename(all_opts, "iops_wr", "throttling.iops-write");
682 qemu_opt_rename(all_opts, "bps", "throttling.bps-total");
683 qemu_opt_rename(all_opts, "bps_rd", "throttling.bps-read");
684 qemu_opt_rename(all_opts, "bps_wr", "throttling.bps-write");
686 qemu_opt_rename(all_opts, "iops_max", "throttling.iops-total-max");
687 qemu_opt_rename(all_opts, "iops_rd_max", "throttling.iops-read-max");
688 qemu_opt_rename(all_opts, "iops_wr_max", "throttling.iops-write-max");
690 qemu_opt_rename(all_opts, "bps_max", "throttling.bps-total-max");
691 qemu_opt_rename(all_opts, "bps_rd_max", "throttling.bps-read-max");
692 qemu_opt_rename(all_opts, "bps_wr_max", "throttling.bps-write-max");
694 qemu_opt_rename(all_opts,
695 "iops_size", "throttling.iops-size");
697 qemu_opt_rename(all_opts, "readonly", "read-only");
699 value = qemu_opt_get(all_opts, "cache");
700 if (value) {
701 int flags = 0;
703 if (bdrv_parse_cache_flags(value, &flags) != 0) {
704 error_report("invalid cache option");
705 return NULL;
708 /* Specific options take precedence */
709 if (!qemu_opt_get(all_opts, "cache.writeback")) {
710 qemu_opt_set_bool(all_opts, "cache.writeback",
711 !!(flags & BDRV_O_CACHE_WB));
713 if (!qemu_opt_get(all_opts, "cache.direct")) {
714 qemu_opt_set_bool(all_opts, "cache.direct",
715 !!(flags & BDRV_O_NOCACHE));
717 if (!qemu_opt_get(all_opts, "cache.no-flush")) {
718 qemu_opt_set_bool(all_opts, "cache.no-flush",
719 !!(flags & BDRV_O_NO_FLUSH));
721 qemu_opt_unset(all_opts, "cache");
724 /* Get a QDict for processing the options */
725 bs_opts = qdict_new();
726 qemu_opts_to_qdict(all_opts, bs_opts);
728 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
729 &error_abort);
730 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
731 if (local_err) {
732 error_report("%s", error_get_pretty(local_err));
733 error_free(local_err);
734 goto fail;
737 /* Deprecated option boot=[on|off] */
738 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
739 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
740 "ignored. Future versions will reject this parameter. Please "
741 "update your scripts.\n");
744 /* Media type */
745 value = qemu_opt_get(legacy_opts, "media");
746 if (value) {
747 if (!strcmp(value, "disk")) {
748 media = MEDIA_DISK;
749 } else if (!strcmp(value, "cdrom")) {
750 media = MEDIA_CDROM;
751 read_only = true;
752 } else {
753 error_report("'%s' invalid media", value);
754 goto fail;
758 /* copy-on-read is disabled with a warning for read-only devices */
759 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
760 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
762 if (read_only && copy_on_read) {
763 error_report("warning: disabling copy-on-read on read-only drive");
764 copy_on_read = false;
767 qdict_put(bs_opts, "read-only",
768 qstring_from_str(read_only ? "on" : "off"));
769 qdict_put(bs_opts, "copy-on-read",
770 qstring_from_str(copy_on_read ? "on" :"off"));
772 /* Controller type */
773 value = qemu_opt_get(legacy_opts, "if");
774 if (value) {
775 for (type = 0;
776 type < IF_COUNT && strcmp(value, if_name[type]);
777 type++) {
779 if (type == IF_COUNT) {
780 error_report("unsupported bus type '%s'", value);
781 goto fail;
783 } else {
784 type = block_default_type;
787 /* Geometry */
788 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
789 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
790 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
792 if (cyls || heads || secs) {
793 if (cyls < 1) {
794 error_report("invalid physical cyls number");
795 goto fail;
797 if (heads < 1) {
798 error_report("invalid physical heads number");
799 goto fail;
801 if (secs < 1) {
802 error_report("invalid physical secs number");
803 goto fail;
807 translation = BIOS_ATA_TRANSLATION_AUTO;
808 value = qemu_opt_get(legacy_opts, "trans");
809 if (value != NULL) {
810 if (!cyls) {
811 error_report("'%s' trans must be used with cyls, heads and secs",
812 value);
813 goto fail;
815 if (!strcmp(value, "none")) {
816 translation = BIOS_ATA_TRANSLATION_NONE;
817 } else if (!strcmp(value, "lba")) {
818 translation = BIOS_ATA_TRANSLATION_LBA;
819 } else if (!strcmp(value, "large")) {
820 translation = BIOS_ATA_TRANSLATION_LARGE;
821 } else if (!strcmp(value, "rechs")) {
822 translation = BIOS_ATA_TRANSLATION_RECHS;
823 } else if (!strcmp(value, "auto")) {
824 translation = BIOS_ATA_TRANSLATION_AUTO;
825 } else {
826 error_report("'%s' invalid translation type", value);
827 goto fail;
831 if (media == MEDIA_CDROM) {
832 if (cyls || secs || heads) {
833 error_report("CHS can't be set with media=cdrom");
834 goto fail;
838 /* Device address specified by bus/unit or index.
839 * If none was specified, try to find the first free one. */
840 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
841 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
842 index = qemu_opt_get_number(legacy_opts, "index", -1);
844 max_devs = if_max_devs[type];
846 if (index != -1) {
847 if (bus_id != 0 || unit_id != -1) {
848 error_report("index cannot be used with bus and unit");
849 goto fail;
851 bus_id = drive_index_to_bus_id(type, index);
852 unit_id = drive_index_to_unit_id(type, index);
855 if (unit_id == -1) {
856 unit_id = 0;
857 while (drive_get(type, bus_id, unit_id) != NULL) {
858 unit_id++;
859 if (max_devs && unit_id >= max_devs) {
860 unit_id -= max_devs;
861 bus_id++;
866 if (max_devs && unit_id >= max_devs) {
867 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
868 goto fail;
871 if (drive_get(type, bus_id, unit_id) != NULL) {
872 error_report("drive with bus=%d, unit=%d (index=%d) exists",
873 bus_id, unit_id, index);
874 goto fail;
877 /* Serial number */
878 serial = qemu_opt_get(legacy_opts, "serial");
880 /* no id supplied -> create one */
881 if (qemu_opts_id(all_opts) == NULL) {
882 char *new_id;
883 const char *mediastr = "";
884 if (type == IF_IDE || type == IF_SCSI) {
885 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
887 if (max_devs) {
888 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
889 mediastr, unit_id);
890 } else {
891 new_id = g_strdup_printf("%s%s%i", if_name[type],
892 mediastr, unit_id);
894 qdict_put(bs_opts, "id", qstring_from_str(new_id));
895 g_free(new_id);
898 /* Add virtio block device */
899 devaddr = qemu_opt_get(legacy_opts, "addr");
900 if (devaddr && type != IF_VIRTIO) {
901 error_report("addr is not supported by this bus type");
902 goto fail;
905 if (type == IF_VIRTIO) {
906 QemuOpts *devopts;
907 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
908 &error_abort);
909 if (arch_type == QEMU_ARCH_S390X) {
910 qemu_opt_set(devopts, "driver", "virtio-blk-s390");
911 } else {
912 qemu_opt_set(devopts, "driver", "virtio-blk-pci");
914 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
915 if (devaddr) {
916 qemu_opt_set(devopts, "addr", devaddr);
920 filename = qemu_opt_get(legacy_opts, "file");
922 /* Check werror/rerror compatibility with if=... */
923 werror = qemu_opt_get(legacy_opts, "werror");
924 if (werror != NULL) {
925 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
926 type != IF_NONE) {
927 error_report("werror is not supported by this bus type");
928 goto fail;
930 qdict_put(bs_opts, "werror", qstring_from_str(werror));
933 rerror = qemu_opt_get(legacy_opts, "rerror");
934 if (rerror != NULL) {
935 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
936 type != IF_NONE) {
937 error_report("rerror is not supported by this bus type");
938 goto fail;
940 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
943 /* Actual block device init: Functionality shared with blockdev-add */
944 dinfo = blockdev_init(filename, bs_opts, &local_err);
945 bs_opts = NULL;
946 if (dinfo == NULL) {
947 if (local_err) {
948 error_report("%s", error_get_pretty(local_err));
949 error_free(local_err);
951 goto fail;
952 } else {
953 assert(!local_err);
956 /* Set legacy DriveInfo fields */
957 dinfo->enable_auto_del = true;
958 dinfo->opts = all_opts;
960 dinfo->cyls = cyls;
961 dinfo->heads = heads;
962 dinfo->secs = secs;
963 dinfo->trans = translation;
965 dinfo->type = type;
966 dinfo->bus = bus_id;
967 dinfo->unit = unit_id;
968 dinfo->devaddr = devaddr;
970 dinfo->serial = g_strdup(serial);
972 switch(type) {
973 case IF_IDE:
974 case IF_SCSI:
975 case IF_XEN:
976 case IF_NONE:
977 dinfo->media_cd = media == MEDIA_CDROM;
978 break;
979 default:
980 break;
983 fail:
984 qemu_opts_del(legacy_opts);
985 QDECREF(bs_opts);
986 return dinfo;
989 void do_commit(Monitor *mon, const QDict *qdict)
991 const char *device = qdict_get_str(qdict, "device");
992 BlockDriverState *bs;
993 int ret;
995 if (!strcmp(device, "all")) {
996 ret = bdrv_commit_all();
997 } else {
998 bs = bdrv_find(device);
999 if (!bs) {
1000 monitor_printf(mon, "Device '%s' not found\n", device);
1001 return;
1003 ret = bdrv_commit(bs);
1005 if (ret < 0) {
1006 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1007 strerror(-ret));
1011 static void blockdev_do_action(int kind, void *data, Error **errp)
1013 TransactionAction action;
1014 TransactionActionList list;
1016 action.kind = kind;
1017 action.data = data;
1018 list.value = &action;
1019 list.next = NULL;
1020 qmp_transaction(&list, errp);
1023 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1024 bool has_node_name, const char *node_name,
1025 const char *snapshot_file,
1026 bool has_snapshot_node_name,
1027 const char *snapshot_node_name,
1028 bool has_format, const char *format,
1029 bool has_mode, NewImageMode mode, Error **errp)
1031 BlockdevSnapshot snapshot = {
1032 .has_device = has_device,
1033 .device = (char *) device,
1034 .has_node_name = has_node_name,
1035 .node_name = (char *) node_name,
1036 .snapshot_file = (char *) snapshot_file,
1037 .has_snapshot_node_name = has_snapshot_node_name,
1038 .snapshot_node_name = (char *) snapshot_node_name,
1039 .has_format = has_format,
1040 .format = (char *) format,
1041 .has_mode = has_mode,
1042 .mode = mode,
1044 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1045 &snapshot, errp);
1048 void qmp_blockdev_snapshot_internal_sync(const char *device,
1049 const char *name,
1050 Error **errp)
1052 BlockdevSnapshotInternal snapshot = {
1053 .device = (char *) device,
1054 .name = (char *) name
1057 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1058 &snapshot, errp);
1061 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1062 bool has_id,
1063 const char *id,
1064 bool has_name,
1065 const char *name,
1066 Error **errp)
1068 BlockDriverState *bs = bdrv_find(device);
1069 QEMUSnapshotInfo sn;
1070 Error *local_err = NULL;
1071 SnapshotInfo *info = NULL;
1072 int ret;
1074 if (!bs) {
1075 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1076 return NULL;
1079 if (!has_id) {
1080 id = NULL;
1083 if (!has_name) {
1084 name = NULL;
1087 if (!id && !name) {
1088 error_setg(errp, "Name or id must be provided");
1089 return NULL;
1092 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1093 if (local_err) {
1094 error_propagate(errp, local_err);
1095 return NULL;
1097 if (!ret) {
1098 error_setg(errp,
1099 "Snapshot with id '%s' and name '%s' does not exist on "
1100 "device '%s'",
1101 STR_OR_NULL(id), STR_OR_NULL(name), device);
1102 return NULL;
1105 bdrv_snapshot_delete(bs, id, name, &local_err);
1106 if (local_err) {
1107 error_propagate(errp, local_err);
1108 return NULL;
1111 info = g_malloc0(sizeof(SnapshotInfo));
1112 info->id = g_strdup(sn.id_str);
1113 info->name = g_strdup(sn.name);
1114 info->date_nsec = sn.date_nsec;
1115 info->date_sec = sn.date_sec;
1116 info->vm_state_size = sn.vm_state_size;
1117 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1118 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1120 return info;
1123 /* New and old BlockDriverState structs for group snapshots */
1125 typedef struct BlkTransactionState BlkTransactionState;
1127 /* Only prepare() may fail. In a single transaction, only one of commit() or
1128 abort() will be called, clean() will always be called if it present. */
1129 typedef struct BdrvActionOps {
1130 /* Size of state struct, in bytes. */
1131 size_t instance_size;
1132 /* Prepare the work, must NOT be NULL. */
1133 void (*prepare)(BlkTransactionState *common, Error **errp);
1134 /* Commit the changes, can be NULL. */
1135 void (*commit)(BlkTransactionState *common);
1136 /* Abort the changes on fail, can be NULL. */
1137 void (*abort)(BlkTransactionState *common);
1138 /* Clean up resource in the end, can be NULL. */
1139 void (*clean)(BlkTransactionState *common);
1140 } BdrvActionOps;
1143 * This structure must be arranged as first member in child type, assuming
1144 * that compiler will also arrange it to the same address with parent instance.
1145 * Later it will be used in free().
1147 struct BlkTransactionState {
1148 TransactionAction *action;
1149 const BdrvActionOps *ops;
1150 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1153 /* internal snapshot private data */
1154 typedef struct InternalSnapshotState {
1155 BlkTransactionState common;
1156 BlockDriverState *bs;
1157 QEMUSnapshotInfo sn;
1158 } InternalSnapshotState;
1160 static void internal_snapshot_prepare(BlkTransactionState *common,
1161 Error **errp)
1163 Error *local_err = NULL;
1164 const char *device;
1165 const char *name;
1166 BlockDriverState *bs;
1167 QEMUSnapshotInfo old_sn, *sn;
1168 bool ret;
1169 qemu_timeval tv;
1170 BlockdevSnapshotInternal *internal;
1171 InternalSnapshotState *state;
1172 int ret1;
1174 g_assert(common->action->kind ==
1175 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1176 internal = common->action->blockdev_snapshot_internal_sync;
1177 state = DO_UPCAST(InternalSnapshotState, common, common);
1179 /* 1. parse input */
1180 device = internal->device;
1181 name = internal->name;
1183 /* 2. check for validation */
1184 bs = bdrv_find(device);
1185 if (!bs) {
1186 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1187 return;
1190 if (!bdrv_is_inserted(bs)) {
1191 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1192 return;
1195 if (bdrv_is_read_only(bs)) {
1196 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1197 return;
1200 if (!bdrv_can_snapshot(bs)) {
1201 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1202 bs->drv->format_name, device, "internal snapshot");
1203 return;
1206 if (!strlen(name)) {
1207 error_setg(errp, "Name is empty");
1208 return;
1211 /* check whether a snapshot with name exist */
1212 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1213 &local_err);
1214 if (local_err) {
1215 error_propagate(errp, local_err);
1216 return;
1217 } else if (ret) {
1218 error_setg(errp,
1219 "Snapshot with name '%s' already exists on device '%s'",
1220 name, device);
1221 return;
1224 /* 3. take the snapshot */
1225 sn = &state->sn;
1226 pstrcpy(sn->name, sizeof(sn->name), name);
1227 qemu_gettimeofday(&tv);
1228 sn->date_sec = tv.tv_sec;
1229 sn->date_nsec = tv.tv_usec * 1000;
1230 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1232 ret1 = bdrv_snapshot_create(bs, sn);
1233 if (ret1 < 0) {
1234 error_setg_errno(errp, -ret1,
1235 "Failed to create snapshot '%s' on device '%s'",
1236 name, device);
1237 return;
1240 /* 4. succeed, mark a snapshot is created */
1241 state->bs = bs;
1244 static void internal_snapshot_abort(BlkTransactionState *common)
1246 InternalSnapshotState *state =
1247 DO_UPCAST(InternalSnapshotState, common, common);
1248 BlockDriverState *bs = state->bs;
1249 QEMUSnapshotInfo *sn = &state->sn;
1250 Error *local_error = NULL;
1252 if (!bs) {
1253 return;
1256 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1257 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1258 "device '%s' in abort: %s",
1259 sn->id_str,
1260 sn->name,
1261 bdrv_get_device_name(bs),
1262 error_get_pretty(local_error));
1263 error_free(local_error);
1267 /* external snapshot private data */
1268 typedef struct ExternalSnapshotState {
1269 BlkTransactionState common;
1270 BlockDriverState *old_bs;
1271 BlockDriverState *new_bs;
1272 } ExternalSnapshotState;
1274 static void external_snapshot_prepare(BlkTransactionState *common,
1275 Error **errp)
1277 BlockDriver *drv;
1278 int flags, ret;
1279 QDict *options = NULL;
1280 Error *local_err = NULL;
1281 bool has_device = false;
1282 const char *device;
1283 bool has_node_name = false;
1284 const char *node_name;
1285 bool has_snapshot_node_name = false;
1286 const char *snapshot_node_name;
1287 const char *new_image_file;
1288 const char *format = "qcow2";
1289 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1290 ExternalSnapshotState *state =
1291 DO_UPCAST(ExternalSnapshotState, common, common);
1292 TransactionAction *action = common->action;
1294 /* get parameters */
1295 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1297 has_device = action->blockdev_snapshot_sync->has_device;
1298 device = action->blockdev_snapshot_sync->device;
1299 has_node_name = action->blockdev_snapshot_sync->has_node_name;
1300 node_name = action->blockdev_snapshot_sync->node_name;
1301 has_snapshot_node_name =
1302 action->blockdev_snapshot_sync->has_snapshot_node_name;
1303 snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1305 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1306 if (action->blockdev_snapshot_sync->has_format) {
1307 format = action->blockdev_snapshot_sync->format;
1309 if (action->blockdev_snapshot_sync->has_mode) {
1310 mode = action->blockdev_snapshot_sync->mode;
1313 /* start processing */
1314 drv = bdrv_find_format(format);
1315 if (!drv) {
1316 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1317 return;
1320 state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1321 has_node_name ? node_name : NULL,
1322 &local_err);
1323 if (local_err) {
1324 error_propagate(errp, local_err);
1325 return;
1328 if (has_node_name && !has_snapshot_node_name) {
1329 error_setg(errp, "New snapshot node name missing");
1330 return;
1333 if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1334 error_setg(errp, "New snapshot node name already existing");
1335 return;
1338 if (!bdrv_is_inserted(state->old_bs)) {
1339 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1340 return;
1343 if (bdrv_op_is_blocked(state->old_bs,
1344 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1345 return;
1348 if (!bdrv_is_read_only(state->old_bs)) {
1349 if (bdrv_flush(state->old_bs)) {
1350 error_set(errp, QERR_IO_ERROR);
1351 return;
1355 if (!bdrv_is_first_non_filter(state->old_bs)) {
1356 error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1357 return;
1360 flags = state->old_bs->open_flags;
1362 /* create new image w/backing file */
1363 if (mode != NEW_IMAGE_MODE_EXISTING) {
1364 bdrv_img_create(new_image_file, format,
1365 state->old_bs->filename,
1366 state->old_bs->drv->format_name,
1367 NULL, -1, flags, &local_err, false);
1368 if (local_err) {
1369 error_propagate(errp, local_err);
1370 return;
1374 if (has_snapshot_node_name) {
1375 options = qdict_new();
1376 qdict_put(options, "node-name",
1377 qstring_from_str(snapshot_node_name));
1380 /* TODO Inherit bs->options or only take explicit options with an
1381 * extended QMP command? */
1382 assert(state->new_bs == NULL);
1383 ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1384 flags | BDRV_O_NO_BACKING, drv, &local_err);
1385 /* We will manually add the backing_hd field to the bs later */
1386 if (ret != 0) {
1387 error_propagate(errp, local_err);
1391 static void external_snapshot_commit(BlkTransactionState *common)
1393 ExternalSnapshotState *state =
1394 DO_UPCAST(ExternalSnapshotState, common, common);
1396 /* This removes our old bs and adds the new bs */
1397 bdrv_append(state->new_bs, state->old_bs);
1398 /* We don't need (or want) to use the transactional
1399 * bdrv_reopen_multiple() across all the entries at once, because we
1400 * don't want to abort all of them if one of them fails the reopen */
1401 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1402 NULL);
1405 static void external_snapshot_abort(BlkTransactionState *common)
1407 ExternalSnapshotState *state =
1408 DO_UPCAST(ExternalSnapshotState, common, common);
1409 if (state->new_bs) {
1410 bdrv_unref(state->new_bs);
1414 typedef struct DriveBackupState {
1415 BlkTransactionState common;
1416 BlockDriverState *bs;
1417 BlockJob *job;
1418 } DriveBackupState;
1420 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1422 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1423 DriveBackup *backup;
1424 Error *local_err = NULL;
1426 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1427 backup = common->action->drive_backup;
1429 qmp_drive_backup(backup->device, backup->target,
1430 backup->has_format, backup->format,
1431 backup->sync,
1432 backup->has_mode, backup->mode,
1433 backup->has_speed, backup->speed,
1434 backup->has_on_source_error, backup->on_source_error,
1435 backup->has_on_target_error, backup->on_target_error,
1436 &local_err);
1437 if (local_err) {
1438 error_propagate(errp, local_err);
1439 state->bs = NULL;
1440 state->job = NULL;
1441 return;
1444 state->bs = bdrv_find(backup->device);
1445 state->job = state->bs->job;
1448 static void drive_backup_abort(BlkTransactionState *common)
1450 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1451 BlockDriverState *bs = state->bs;
1453 /* Only cancel if it's the job we started */
1454 if (bs && bs->job && bs->job == state->job) {
1455 block_job_cancel_sync(bs->job);
1459 static void abort_prepare(BlkTransactionState *common, Error **errp)
1461 error_setg(errp, "Transaction aborted using Abort action");
1464 static void abort_commit(BlkTransactionState *common)
1466 g_assert_not_reached(); /* this action never succeeds */
1469 static const BdrvActionOps actions[] = {
1470 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1471 .instance_size = sizeof(ExternalSnapshotState),
1472 .prepare = external_snapshot_prepare,
1473 .commit = external_snapshot_commit,
1474 .abort = external_snapshot_abort,
1476 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1477 .instance_size = sizeof(DriveBackupState),
1478 .prepare = drive_backup_prepare,
1479 .abort = drive_backup_abort,
1481 [TRANSACTION_ACTION_KIND_ABORT] = {
1482 .instance_size = sizeof(BlkTransactionState),
1483 .prepare = abort_prepare,
1484 .commit = abort_commit,
1486 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1487 .instance_size = sizeof(InternalSnapshotState),
1488 .prepare = internal_snapshot_prepare,
1489 .abort = internal_snapshot_abort,
1494 * 'Atomic' group snapshots. The snapshots are taken as a set, and if any fail
1495 * then we do not pivot any of the devices in the group, and abandon the
1496 * snapshots
1498 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1500 TransactionActionList *dev_entry = dev_list;
1501 BlkTransactionState *state, *next;
1502 Error *local_err = NULL;
1504 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1505 QSIMPLEQ_INIT(&snap_bdrv_states);
1507 /* drain all i/o before any snapshots */
1508 bdrv_drain_all();
1510 /* We don't do anything in this loop that commits us to the snapshot */
1511 while (NULL != dev_entry) {
1512 TransactionAction *dev_info = NULL;
1513 const BdrvActionOps *ops;
1515 dev_info = dev_entry->value;
1516 dev_entry = dev_entry->next;
1518 assert(dev_info->kind < ARRAY_SIZE(actions));
1520 ops = &actions[dev_info->kind];
1521 assert(ops->instance_size > 0);
1523 state = g_malloc0(ops->instance_size);
1524 state->ops = ops;
1525 state->action = dev_info;
1526 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1528 state->ops->prepare(state, &local_err);
1529 if (local_err) {
1530 error_propagate(errp, local_err);
1531 goto delete_and_fail;
1535 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1536 if (state->ops->commit) {
1537 state->ops->commit(state);
1541 /* success */
1542 goto exit;
1544 delete_and_fail:
1546 * failure, and it is all-or-none; abandon each new bs, and keep using
1547 * the original bs for all images
1549 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1550 if (state->ops->abort) {
1551 state->ops->abort(state);
1554 exit:
1555 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1556 if (state->ops->clean) {
1557 state->ops->clean(state);
1559 g_free(state);
1564 static void eject_device(BlockDriverState *bs, int force, Error **errp)
1566 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1567 return;
1569 if (!bdrv_dev_has_removable_media(bs)) {
1570 error_setg(errp, "Device '%s' is not removable",
1571 bdrv_get_device_name(bs));
1572 return;
1575 if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
1576 bdrv_dev_eject_request(bs, force);
1577 if (!force) {
1578 error_setg(errp, "Device '%s' is locked",
1579 bdrv_get_device_name(bs));
1580 return;
1584 bdrv_close(bs);
1587 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1589 BlockDriverState *bs;
1591 bs = bdrv_find(device);
1592 if (!bs) {
1593 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1594 return;
1597 eject_device(bs, force, errp);
1600 void qmp_block_passwd(bool has_device, const char *device,
1601 bool has_node_name, const char *node_name,
1602 const char *password, Error **errp)
1604 Error *local_err = NULL;
1605 BlockDriverState *bs;
1606 int err;
1608 bs = bdrv_lookup_bs(has_device ? device : NULL,
1609 has_node_name ? node_name : NULL,
1610 &local_err);
1611 if (local_err) {
1612 error_propagate(errp, local_err);
1613 return;
1616 err = bdrv_set_key(bs, password);
1617 if (err == -EINVAL) {
1618 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1619 return;
1620 } else if (err < 0) {
1621 error_set(errp, QERR_INVALID_PASSWORD);
1622 return;
1626 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1627 int bdrv_flags, BlockDriver *drv,
1628 const char *password, Error **errp)
1630 Error *local_err = NULL;
1631 int ret;
1633 ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1634 if (ret < 0) {
1635 error_propagate(errp, local_err);
1636 return;
1639 if (bdrv_key_required(bs)) {
1640 if (password) {
1641 if (bdrv_set_key(bs, password) < 0) {
1642 error_set(errp, QERR_INVALID_PASSWORD);
1644 } else {
1645 error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1646 bdrv_get_encrypted_filename(bs));
1648 } else if (password) {
1649 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1653 void qmp_change_blockdev(const char *device, const char *filename,
1654 const char *format, Error **errp)
1656 BlockDriverState *bs;
1657 BlockDriver *drv = NULL;
1658 int bdrv_flags;
1659 Error *err = NULL;
1661 bs = bdrv_find(device);
1662 if (!bs) {
1663 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1664 return;
1667 if (format) {
1668 drv = bdrv_find_whitelisted_format(format, bs->read_only);
1669 if (!drv) {
1670 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1671 return;
1675 eject_device(bs, 0, &err);
1676 if (err) {
1677 error_propagate(errp, err);
1678 return;
1681 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1682 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1684 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1687 /* throttling disk I/O limits */
1688 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1689 int64_t bps_wr,
1690 int64_t iops,
1691 int64_t iops_rd,
1692 int64_t iops_wr,
1693 bool has_bps_max,
1694 int64_t bps_max,
1695 bool has_bps_rd_max,
1696 int64_t bps_rd_max,
1697 bool has_bps_wr_max,
1698 int64_t bps_wr_max,
1699 bool has_iops_max,
1700 int64_t iops_max,
1701 bool has_iops_rd_max,
1702 int64_t iops_rd_max,
1703 bool has_iops_wr_max,
1704 int64_t iops_wr_max,
1705 bool has_iops_size,
1706 int64_t iops_size, Error **errp)
1708 ThrottleConfig cfg;
1709 BlockDriverState *bs;
1710 AioContext *aio_context;
1712 bs = bdrv_find(device);
1713 if (!bs) {
1714 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1715 return;
1718 memset(&cfg, 0, sizeof(cfg));
1719 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1720 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1721 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1723 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1724 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1725 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1727 if (has_bps_max) {
1728 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1730 if (has_bps_rd_max) {
1731 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1733 if (has_bps_wr_max) {
1734 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1736 if (has_iops_max) {
1737 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1739 if (has_iops_rd_max) {
1740 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1742 if (has_iops_wr_max) {
1743 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1746 if (has_iops_size) {
1747 cfg.op_size = iops_size;
1750 if (!check_throttle_config(&cfg, errp)) {
1751 return;
1754 aio_context = bdrv_get_aio_context(bs);
1755 aio_context_acquire(aio_context);
1757 if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
1758 bdrv_io_limits_enable(bs);
1759 } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
1760 bdrv_io_limits_disable(bs);
1763 if (bs->io_limits_enabled) {
1764 bdrv_set_io_limits(bs, &cfg);
1767 aio_context_release(aio_context);
1770 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1772 const char *id = qdict_get_str(qdict, "id");
1773 BlockDriverState *bs;
1774 Error *local_err = NULL;
1776 bs = bdrv_find(id);
1777 if (!bs) {
1778 error_report("Device '%s' not found", id);
1779 return -1;
1781 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
1782 error_report("%s", error_get_pretty(local_err));
1783 error_free(local_err);
1784 return -1;
1787 /* quiesce block driver; prevent further io */
1788 bdrv_drain_all();
1789 bdrv_flush(bs);
1790 bdrv_close(bs);
1792 /* if we have a device attached to this BlockDriverState
1793 * then we need to make the drive anonymous until the device
1794 * can be removed. If this is a drive with no device backing
1795 * then we can just get rid of the block driver state right here.
1797 if (bdrv_get_attached_dev(bs)) {
1798 bdrv_make_anon(bs);
1800 /* Further I/O must not pause the guest */
1801 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1802 BLOCKDEV_ON_ERROR_REPORT);
1803 } else {
1804 drive_del(drive_get_by_blockdev(bs));
1807 return 0;
1810 void qmp_block_resize(bool has_device, const char *device,
1811 bool has_node_name, const char *node_name,
1812 int64_t size, Error **errp)
1814 Error *local_err = NULL;
1815 BlockDriverState *bs;
1816 int ret;
1818 bs = bdrv_lookup_bs(has_device ? device : NULL,
1819 has_node_name ? node_name : NULL,
1820 &local_err);
1821 if (local_err) {
1822 error_propagate(errp, local_err);
1823 return;
1826 if (!bdrv_is_first_non_filter(bs)) {
1827 error_set(errp, QERR_FEATURE_DISABLED, "resize");
1828 return;
1831 if (size < 0) {
1832 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1833 return;
1836 /* complete all in-flight operations before resizing the device */
1837 bdrv_drain_all();
1839 ret = bdrv_truncate(bs, size);
1840 switch (ret) {
1841 case 0:
1842 break;
1843 case -ENOMEDIUM:
1844 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1845 break;
1846 case -ENOTSUP:
1847 error_set(errp, QERR_UNSUPPORTED);
1848 break;
1849 case -EACCES:
1850 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1851 break;
1852 case -EBUSY:
1853 error_set(errp, QERR_DEVICE_IN_USE, device);
1854 break;
1855 default:
1856 error_setg_errno(errp, -ret, "Could not resize");
1857 break;
1861 static void block_job_cb(void *opaque, int ret)
1863 BlockDriverState *bs = opaque;
1864 QObject *obj;
1866 trace_block_job_cb(bs, bs->job, ret);
1868 assert(bs->job);
1869 obj = qobject_from_block_job(bs->job);
1870 if (ret < 0) {
1871 QDict *dict = qobject_to_qdict(obj);
1872 qdict_put(dict, "error", qstring_from_str(strerror(-ret)));
1875 if (block_job_is_cancelled(bs->job)) {
1876 monitor_protocol_event(QEVENT_BLOCK_JOB_CANCELLED, obj);
1877 } else {
1878 monitor_protocol_event(QEVENT_BLOCK_JOB_COMPLETED, obj);
1880 qobject_decref(obj);
1882 bdrv_put_ref_bh_schedule(bs);
1885 void qmp_block_stream(const char *device, bool has_base,
1886 const char *base, bool has_speed, int64_t speed,
1887 bool has_on_error, BlockdevOnError on_error,
1888 Error **errp)
1890 BlockDriverState *bs;
1891 BlockDriverState *base_bs = NULL;
1892 Error *local_err = NULL;
1894 if (!has_on_error) {
1895 on_error = BLOCKDEV_ON_ERROR_REPORT;
1898 bs = bdrv_find(device);
1899 if (!bs) {
1900 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1901 return;
1904 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
1905 return;
1908 if (base) {
1909 base_bs = bdrv_find_backing_image(bs, base);
1910 if (base_bs == NULL) {
1911 error_set(errp, QERR_BASE_NOT_FOUND, base);
1912 return;
1916 stream_start(bs, base_bs, base, has_speed ? speed : 0,
1917 on_error, block_job_cb, bs, &local_err);
1918 if (local_err) {
1919 error_propagate(errp, local_err);
1920 return;
1923 trace_qmp_block_stream(bs, bs->job);
1926 void qmp_block_commit(const char *device,
1927 bool has_base, const char *base, const char *top,
1928 bool has_speed, int64_t speed,
1929 Error **errp)
1931 BlockDriverState *bs;
1932 BlockDriverState *base_bs, *top_bs;
1933 Error *local_err = NULL;
1934 /* This will be part of the QMP command, if/when the
1935 * BlockdevOnError change for blkmirror makes it in
1937 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
1939 if (!has_speed) {
1940 speed = 0;
1943 /* drain all i/o before commits */
1944 bdrv_drain_all();
1946 bs = bdrv_find(device);
1947 if (!bs) {
1948 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1949 return;
1952 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, errp)) {
1953 return;
1956 /* default top_bs is the active layer */
1957 top_bs = bs;
1959 if (top) {
1960 if (strcmp(bs->filename, top) != 0) {
1961 top_bs = bdrv_find_backing_image(bs, top);
1965 if (top_bs == NULL) {
1966 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
1967 return;
1970 if (has_base && base) {
1971 base_bs = bdrv_find_backing_image(top_bs, base);
1972 } else {
1973 base_bs = bdrv_find_base(top_bs);
1976 if (base_bs == NULL) {
1977 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
1978 return;
1981 if (top_bs == bs) {
1982 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
1983 bs, &local_err);
1984 } else {
1985 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
1986 &local_err);
1988 if (local_err != NULL) {
1989 error_propagate(errp, local_err);
1990 return;
1994 void qmp_drive_backup(const char *device, const char *target,
1995 bool has_format, const char *format,
1996 enum MirrorSyncMode sync,
1997 bool has_mode, enum NewImageMode mode,
1998 bool has_speed, int64_t speed,
1999 bool has_on_source_error, BlockdevOnError on_source_error,
2000 bool has_on_target_error, BlockdevOnError on_target_error,
2001 Error **errp)
2003 BlockDriverState *bs;
2004 BlockDriverState *target_bs;
2005 BlockDriverState *source = NULL;
2006 BlockDriver *drv = NULL;
2007 Error *local_err = NULL;
2008 int flags;
2009 int64_t size;
2010 int ret;
2012 if (!has_speed) {
2013 speed = 0;
2015 if (!has_on_source_error) {
2016 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2018 if (!has_on_target_error) {
2019 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2021 if (!has_mode) {
2022 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2025 bs = bdrv_find(device);
2026 if (!bs) {
2027 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2028 return;
2031 if (!bdrv_is_inserted(bs)) {
2032 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2033 return;
2036 if (!has_format) {
2037 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2039 if (format) {
2040 drv = bdrv_find_format(format);
2041 if (!drv) {
2042 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2043 return;
2047 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2048 return;
2051 flags = bs->open_flags | BDRV_O_RDWR;
2053 /* See if we have a backing HD we can use to create our new image
2054 * on top of. */
2055 if (sync == MIRROR_SYNC_MODE_TOP) {
2056 source = bs->backing_hd;
2057 if (!source) {
2058 sync = MIRROR_SYNC_MODE_FULL;
2061 if (sync == MIRROR_SYNC_MODE_NONE) {
2062 source = bs;
2065 size = bdrv_getlength(bs);
2066 if (size < 0) {
2067 error_setg_errno(errp, -size, "bdrv_getlength failed");
2068 return;
2071 if (mode != NEW_IMAGE_MODE_EXISTING) {
2072 assert(format && drv);
2073 if (source) {
2074 bdrv_img_create(target, format, source->filename,
2075 source->drv->format_name, NULL,
2076 size, flags, &local_err, false);
2077 } else {
2078 bdrv_img_create(target, format, NULL, NULL, NULL,
2079 size, flags, &local_err, false);
2083 if (local_err) {
2084 error_propagate(errp, local_err);
2085 return;
2088 target_bs = NULL;
2089 ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2090 if (ret < 0) {
2091 error_propagate(errp, local_err);
2092 return;
2095 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2096 block_job_cb, bs, &local_err);
2097 if (local_err != NULL) {
2098 bdrv_unref(target_bs);
2099 error_propagate(errp, local_err);
2100 return;
2104 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2106 return bdrv_named_nodes_list();
2109 #define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
2111 void qmp_drive_mirror(const char *device, const char *target,
2112 bool has_format, const char *format,
2113 enum MirrorSyncMode sync,
2114 bool has_mode, enum NewImageMode mode,
2115 bool has_speed, int64_t speed,
2116 bool has_granularity, uint32_t granularity,
2117 bool has_buf_size, int64_t buf_size,
2118 bool has_on_source_error, BlockdevOnError on_source_error,
2119 bool has_on_target_error, BlockdevOnError on_target_error,
2120 Error **errp)
2122 BlockDriverState *bs;
2123 BlockDriverState *source, *target_bs;
2124 BlockDriver *drv = NULL;
2125 Error *local_err = NULL;
2126 int flags;
2127 int64_t size;
2128 int ret;
2130 if (!has_speed) {
2131 speed = 0;
2133 if (!has_on_source_error) {
2134 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2136 if (!has_on_target_error) {
2137 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2139 if (!has_mode) {
2140 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2142 if (!has_granularity) {
2143 granularity = 0;
2145 if (!has_buf_size) {
2146 buf_size = DEFAULT_MIRROR_BUF_SIZE;
2149 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2150 error_set(errp, QERR_INVALID_PARAMETER, device);
2151 return;
2153 if (granularity & (granularity - 1)) {
2154 error_set(errp, QERR_INVALID_PARAMETER, device);
2155 return;
2158 bs = bdrv_find(device);
2159 if (!bs) {
2160 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2161 return;
2164 if (!bdrv_is_inserted(bs)) {
2165 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2166 return;
2169 if (!has_format) {
2170 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2172 if (format) {
2173 drv = bdrv_find_format(format);
2174 if (!drv) {
2175 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2176 return;
2180 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2181 return;
2184 flags = bs->open_flags | BDRV_O_RDWR;
2185 source = bs->backing_hd;
2186 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2187 sync = MIRROR_SYNC_MODE_FULL;
2189 if (sync == MIRROR_SYNC_MODE_NONE) {
2190 source = bs;
2193 size = bdrv_getlength(bs);
2194 if (size < 0) {
2195 error_setg_errno(errp, -size, "bdrv_getlength failed");
2196 return;
2199 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2200 && mode != NEW_IMAGE_MODE_EXISTING)
2202 /* create new image w/o backing file */
2203 assert(format && drv);
2204 bdrv_img_create(target, format,
2205 NULL, NULL, NULL, size, flags, &local_err, false);
2206 } else {
2207 switch (mode) {
2208 case NEW_IMAGE_MODE_EXISTING:
2209 break;
2210 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2211 /* create new image with backing file */
2212 bdrv_img_create(target, format,
2213 source->filename,
2214 source->drv->format_name,
2215 NULL, size, flags, &local_err, false);
2216 break;
2217 default:
2218 abort();
2222 if (local_err) {
2223 error_propagate(errp, local_err);
2224 return;
2227 /* Mirroring takes care of copy-on-write using the source's backing
2228 * file.
2230 target_bs = NULL;
2231 ret = bdrv_open(&target_bs, target, NULL, NULL, flags | BDRV_O_NO_BACKING,
2232 drv, &local_err);
2233 if (ret < 0) {
2234 error_propagate(errp, local_err);
2235 return;
2238 mirror_start(bs, target_bs, speed, granularity, buf_size, sync,
2239 on_source_error, on_target_error,
2240 block_job_cb, bs, &local_err);
2241 if (local_err != NULL) {
2242 bdrv_unref(target_bs);
2243 error_propagate(errp, local_err);
2244 return;
2248 static BlockJob *find_block_job(const char *device)
2250 BlockDriverState *bs;
2252 bs = bdrv_find(device);
2253 if (!bs || !bs->job) {
2254 return NULL;
2256 return bs->job;
2259 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2261 BlockJob *job = find_block_job(device);
2263 if (!job) {
2264 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2265 return;
2268 block_job_set_speed(job, speed, errp);
2271 void qmp_block_job_cancel(const char *device,
2272 bool has_force, bool force, Error **errp)
2274 BlockJob *job = find_block_job(device);
2276 if (!has_force) {
2277 force = false;
2280 if (!job) {
2281 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2282 return;
2284 if (job->paused && !force) {
2285 error_setg(errp, "The block job for device '%s' is currently paused",
2286 device);
2287 return;
2290 trace_qmp_block_job_cancel(job);
2291 block_job_cancel(job);
2294 void qmp_block_job_pause(const char *device, Error **errp)
2296 BlockJob *job = find_block_job(device);
2298 if (!job) {
2299 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2300 return;
2303 trace_qmp_block_job_pause(job);
2304 block_job_pause(job);
2307 void qmp_block_job_resume(const char *device, Error **errp)
2309 BlockJob *job = find_block_job(device);
2311 if (!job) {
2312 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2313 return;
2316 trace_qmp_block_job_resume(job);
2317 block_job_resume(job);
2320 void qmp_block_job_complete(const char *device, Error **errp)
2322 BlockJob *job = find_block_job(device);
2324 if (!job) {
2325 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2326 return;
2329 trace_qmp_block_job_complete(job);
2330 block_job_complete(job, errp);
2333 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2335 QmpOutputVisitor *ov = qmp_output_visitor_new();
2336 DriveInfo *dinfo;
2337 QObject *obj;
2338 QDict *qdict;
2339 Error *local_err = NULL;
2341 /* Require an ID in the top level */
2342 if (!options->has_id) {
2343 error_setg(errp, "Block device needs an ID");
2344 goto fail;
2347 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
2348 * cache.direct=false instead of silently switching to aio=threads, except
2349 * when called from drive_new().
2351 * For now, simply forbidding the combination for all drivers will do. */
2352 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2353 bool direct = options->has_cache &&
2354 options->cache->has_direct &&
2355 options->cache->direct;
2356 if (!direct) {
2357 error_setg(errp, "aio=native requires cache.direct=true");
2358 goto fail;
2362 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2363 &options, NULL, &local_err);
2364 if (local_err) {
2365 error_propagate(errp, local_err);
2366 goto fail;
2369 obj = qmp_output_get_qobject(ov);
2370 qdict = qobject_to_qdict(obj);
2372 qdict_flatten(qdict);
2374 dinfo = blockdev_init(NULL, qdict, &local_err);
2375 if (local_err) {
2376 error_propagate(errp, local_err);
2377 goto fail;
2380 if (bdrv_key_required(dinfo->bdrv)) {
2381 drive_del(dinfo);
2382 error_setg(errp, "blockdev-add doesn't support encrypted devices");
2383 goto fail;
2386 fail:
2387 qmp_output_visitor_cleanup(ov);
2390 static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
2392 BlockJobInfoList **prev = opaque;
2393 BlockJob *job = bs->job;
2395 if (job) {
2396 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2397 elem->value = block_job_query(bs->job);
2398 (*prev)->next = elem;
2399 *prev = elem;
2403 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2405 /* Dummy is a fake list element for holding the head pointer */
2406 BlockJobInfoList dummy = {};
2407 BlockJobInfoList *prev = &dummy;
2408 bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
2409 return dummy.next;
2412 QemuOptsList qemu_common_drive_opts = {
2413 .name = "drive",
2414 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2415 .desc = {
2417 .name = "snapshot",
2418 .type = QEMU_OPT_BOOL,
2419 .help = "enable/disable snapshot mode",
2421 .name = "discard",
2422 .type = QEMU_OPT_STRING,
2423 .help = "discard operation (ignore/off, unmap/on)",
2425 .name = "cache.writeback",
2426 .type = QEMU_OPT_BOOL,
2427 .help = "enables writeback mode for any caches",
2429 .name = "cache.direct",
2430 .type = QEMU_OPT_BOOL,
2431 .help = "enables use of O_DIRECT (bypass the host page cache)",
2433 .name = "cache.no-flush",
2434 .type = QEMU_OPT_BOOL,
2435 .help = "ignore any flush requests for the device",
2437 .name = "aio",
2438 .type = QEMU_OPT_STRING,
2439 .help = "host AIO implementation (threads, native)",
2441 .name = "format",
2442 .type = QEMU_OPT_STRING,
2443 .help = "disk format (raw, qcow2, ...)",
2445 .name = "rerror",
2446 .type = QEMU_OPT_STRING,
2447 .help = "read error action",
2449 .name = "werror",
2450 .type = QEMU_OPT_STRING,
2451 .help = "write error action",
2453 .name = "read-only",
2454 .type = QEMU_OPT_BOOL,
2455 .help = "open drive file as read-only",
2457 .name = "throttling.iops-total",
2458 .type = QEMU_OPT_NUMBER,
2459 .help = "limit total I/O operations per second",
2461 .name = "throttling.iops-read",
2462 .type = QEMU_OPT_NUMBER,
2463 .help = "limit read operations per second",
2465 .name = "throttling.iops-write",
2466 .type = QEMU_OPT_NUMBER,
2467 .help = "limit write operations per second",
2469 .name = "throttling.bps-total",
2470 .type = QEMU_OPT_NUMBER,
2471 .help = "limit total bytes per second",
2473 .name = "throttling.bps-read",
2474 .type = QEMU_OPT_NUMBER,
2475 .help = "limit read bytes per second",
2477 .name = "throttling.bps-write",
2478 .type = QEMU_OPT_NUMBER,
2479 .help = "limit write bytes per second",
2481 .name = "throttling.iops-total-max",
2482 .type = QEMU_OPT_NUMBER,
2483 .help = "I/O operations burst",
2485 .name = "throttling.iops-read-max",
2486 .type = QEMU_OPT_NUMBER,
2487 .help = "I/O operations read burst",
2489 .name = "throttling.iops-write-max",
2490 .type = QEMU_OPT_NUMBER,
2491 .help = "I/O operations write burst",
2493 .name = "throttling.bps-total-max",
2494 .type = QEMU_OPT_NUMBER,
2495 .help = "total bytes burst",
2497 .name = "throttling.bps-read-max",
2498 .type = QEMU_OPT_NUMBER,
2499 .help = "total bytes read burst",
2501 .name = "throttling.bps-write-max",
2502 .type = QEMU_OPT_NUMBER,
2503 .help = "total bytes write burst",
2505 .name = "throttling.iops-size",
2506 .type = QEMU_OPT_NUMBER,
2507 .help = "when limiting by iops max size of an I/O in bytes",
2509 .name = "copy-on-read",
2510 .type = QEMU_OPT_BOOL,
2511 .help = "copy read data from backing file into image file",
2513 .name = "detect-zeroes",
2514 .type = QEMU_OPT_STRING,
2515 .help = "try to optimize zero writes (off, on, unmap)",
2517 { /* end of list */ }
2521 QemuOptsList qemu_drive_opts = {
2522 .name = "drive",
2523 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2524 .desc = {
2526 * no elements => accept any params
2527 * validation will happen later
2529 { /* end of list */ }