usb-storage: fix possible memory leak and missing error message
[qemu/ar7.git] / blockdev.c
blobb361fbb964dc84996cbec98cb0a462d98ea4f3e9
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 "qapi/util.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_del(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 void drive_del(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 typedef struct {
231 QEMUBH *bh;
232 BlockDriverState *bs;
233 } BDRVPutRefBH;
235 static void bdrv_put_ref_bh(void *opaque)
237 BDRVPutRefBH *s = opaque;
239 bdrv_unref(s->bs);
240 qemu_bh_delete(s->bh);
241 g_free(s);
245 * Release a BDS reference in a BH
247 * It is not safe to use bdrv_unref() from a callback function when the callers
248 * still need the BlockDriverState. In such cases we schedule a BH to release
249 * the reference.
251 static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
253 BDRVPutRefBH *s;
255 s = g_new(BDRVPutRefBH, 1);
256 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
257 s->bs = bs;
258 qemu_bh_schedule(s->bh);
261 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
263 if (!strcmp(buf, "ignore")) {
264 return BLOCKDEV_ON_ERROR_IGNORE;
265 } else if (!is_read && !strcmp(buf, "enospc")) {
266 return BLOCKDEV_ON_ERROR_ENOSPC;
267 } else if (!strcmp(buf, "stop")) {
268 return BLOCKDEV_ON_ERROR_STOP;
269 } else if (!strcmp(buf, "report")) {
270 return BLOCKDEV_ON_ERROR_REPORT;
271 } else {
272 error_setg(errp, "'%s' invalid %s error action",
273 buf, is_read ? "read" : "write");
274 return -1;
278 static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
280 if (throttle_conflicting(cfg)) {
281 error_setg(errp, "bps/iops/max total values and read/write values"
282 " cannot be used at the same time");
283 return false;
286 if (!throttle_is_valid(cfg)) {
287 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
288 return false;
291 return true;
294 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
296 /* Takes the ownership of bs_opts */
297 static DriveInfo *blockdev_init(const char *file, QDict *bs_opts,
298 Error **errp)
300 const char *buf;
301 int ro = 0;
302 int bdrv_flags = 0;
303 int on_read_error, on_write_error;
304 DriveInfo *dinfo;
305 ThrottleConfig cfg;
306 int snapshot = 0;
307 bool copy_on_read;
308 int ret;
309 Error *error = NULL;
310 QemuOpts *opts;
311 const char *id;
312 bool has_driver_specific_opts;
313 BlockdevDetectZeroesOptions detect_zeroes;
314 BlockDriver *drv = NULL;
316 /* Check common options by copying from bs_opts to opts, all other options
317 * stay in bs_opts for processing by bdrv_open(). */
318 id = qdict_get_try_str(bs_opts, "id");
319 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
320 if (error) {
321 error_propagate(errp, error);
322 goto err_no_opts;
325 qemu_opts_absorb_qdict(opts, bs_opts, &error);
326 if (error) {
327 error_propagate(errp, error);
328 goto early_err;
331 if (id) {
332 qdict_del(bs_opts, "id");
335 has_driver_specific_opts = !!qdict_size(bs_opts);
337 /* extract parameters */
338 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
339 ro = qemu_opt_get_bool(opts, "read-only", 0);
340 copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
342 if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
343 if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
344 error_setg(errp, "invalid discard option");
345 goto early_err;
349 if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
350 bdrv_flags |= BDRV_O_CACHE_WB;
352 if (qemu_opt_get_bool(opts, "cache.direct", false)) {
353 bdrv_flags |= BDRV_O_NOCACHE;
355 if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
356 bdrv_flags |= BDRV_O_NO_FLUSH;
359 #ifdef CONFIG_LINUX_AIO
360 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
361 if (!strcmp(buf, "native")) {
362 bdrv_flags |= BDRV_O_NATIVE_AIO;
363 } else if (!strcmp(buf, "threads")) {
364 /* this is the default */
365 } else {
366 error_setg(errp, "invalid aio option");
367 goto early_err;
370 #endif
372 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
373 if (is_help_option(buf)) {
374 error_printf("Supported formats:");
375 bdrv_iterate_format(bdrv_format_print, NULL);
376 error_printf("\n");
377 goto early_err;
380 drv = bdrv_find_format(buf);
381 if (!drv) {
382 error_setg(errp, "'%s' invalid format", buf);
383 goto early_err;
387 /* disk I/O throttling */
388 memset(&cfg, 0, sizeof(cfg));
389 cfg.buckets[THROTTLE_BPS_TOTAL].avg =
390 qemu_opt_get_number(opts, "throttling.bps-total", 0);
391 cfg.buckets[THROTTLE_BPS_READ].avg =
392 qemu_opt_get_number(opts, "throttling.bps-read", 0);
393 cfg.buckets[THROTTLE_BPS_WRITE].avg =
394 qemu_opt_get_number(opts, "throttling.bps-write", 0);
395 cfg.buckets[THROTTLE_OPS_TOTAL].avg =
396 qemu_opt_get_number(opts, "throttling.iops-total", 0);
397 cfg.buckets[THROTTLE_OPS_READ].avg =
398 qemu_opt_get_number(opts, "throttling.iops-read", 0);
399 cfg.buckets[THROTTLE_OPS_WRITE].avg =
400 qemu_opt_get_number(opts, "throttling.iops-write", 0);
402 cfg.buckets[THROTTLE_BPS_TOTAL].max =
403 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
404 cfg.buckets[THROTTLE_BPS_READ].max =
405 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
406 cfg.buckets[THROTTLE_BPS_WRITE].max =
407 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
408 cfg.buckets[THROTTLE_OPS_TOTAL].max =
409 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
410 cfg.buckets[THROTTLE_OPS_READ].max =
411 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
412 cfg.buckets[THROTTLE_OPS_WRITE].max =
413 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
415 cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
417 if (!check_throttle_config(&cfg, &error)) {
418 error_propagate(errp, error);
419 goto early_err;
422 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
423 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
424 on_write_error = parse_block_error_action(buf, 0, &error);
425 if (error) {
426 error_propagate(errp, error);
427 goto early_err;
431 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
432 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
433 on_read_error = parse_block_error_action(buf, 1, &error);
434 if (error) {
435 error_propagate(errp, error);
436 goto early_err;
440 detect_zeroes =
441 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
442 qemu_opt_get(opts, "detect-zeroes"),
443 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
444 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
445 &error);
446 if (error) {
447 error_propagate(errp, error);
448 goto early_err;
451 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
452 !(bdrv_flags & BDRV_O_UNMAP)) {
453 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
454 "without setting discard operation to unmap");
455 goto early_err;
458 /* init */
459 dinfo = g_malloc0(sizeof(*dinfo));
460 dinfo->id = g_strdup(qemu_opts_id(opts));
461 dinfo->bdrv = bdrv_new(dinfo->id, &error);
462 if (error) {
463 error_propagate(errp, error);
464 goto bdrv_new_err;
466 dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
467 dinfo->bdrv->read_only = ro;
468 dinfo->bdrv->detect_zeroes = detect_zeroes;
469 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
471 bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);
473 /* disk I/O throttling */
474 if (throttle_enabled(&cfg)) {
475 bdrv_io_limits_enable(dinfo->bdrv);
476 bdrv_set_io_limits(dinfo->bdrv, &cfg);
479 if (!file || !*file) {
480 if (has_driver_specific_opts) {
481 file = NULL;
482 } else {
483 QDECREF(bs_opts);
484 qemu_opts_del(opts);
485 return dinfo;
488 if (snapshot) {
489 /* always use cache=unsafe with snapshot */
490 bdrv_flags &= ~BDRV_O_CACHE_MASK;
491 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
494 if (copy_on_read) {
495 bdrv_flags |= BDRV_O_COPY_ON_READ;
498 if (runstate_check(RUN_STATE_INMIGRATE)) {
499 bdrv_flags |= BDRV_O_INCOMING;
502 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
504 QINCREF(bs_opts);
505 ret = bdrv_open(&dinfo->bdrv, file, NULL, bs_opts, bdrv_flags, drv, &error);
507 if (ret < 0) {
508 error_setg(errp, "could not open disk image %s: %s",
509 file ?: dinfo->id, error_get_pretty(error));
510 error_free(error);
511 goto err;
514 if (bdrv_key_required(dinfo->bdrv))
515 autostart = 0;
517 QDECREF(bs_opts);
518 qemu_opts_del(opts);
520 return dinfo;
522 err:
523 bdrv_unref(dinfo->bdrv);
524 QTAILQ_REMOVE(&drives, dinfo, next);
525 bdrv_new_err:
526 g_free(dinfo->id);
527 g_free(dinfo);
528 early_err:
529 qemu_opts_del(opts);
530 err_no_opts:
531 QDECREF(bs_opts);
532 return NULL;
535 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to)
537 const char *value;
539 value = qemu_opt_get(opts, from);
540 if (value) {
541 qemu_opt_set(opts, to, value);
542 qemu_opt_unset(opts, from);
546 QemuOptsList qemu_legacy_drive_opts = {
547 .name = "drive",
548 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
549 .desc = {
551 .name = "bus",
552 .type = QEMU_OPT_NUMBER,
553 .help = "bus number",
555 .name = "unit",
556 .type = QEMU_OPT_NUMBER,
557 .help = "unit number (i.e. lun for scsi)",
559 .name = "index",
560 .type = QEMU_OPT_NUMBER,
561 .help = "index number",
563 .name = "media",
564 .type = QEMU_OPT_STRING,
565 .help = "media type (disk, cdrom)",
567 .name = "if",
568 .type = QEMU_OPT_STRING,
569 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
571 .name = "cyls",
572 .type = QEMU_OPT_NUMBER,
573 .help = "number of cylinders (ide disk geometry)",
575 .name = "heads",
576 .type = QEMU_OPT_NUMBER,
577 .help = "number of heads (ide disk geometry)",
579 .name = "secs",
580 .type = QEMU_OPT_NUMBER,
581 .help = "number of sectors (ide disk geometry)",
583 .name = "trans",
584 .type = QEMU_OPT_STRING,
585 .help = "chs translation (auto, lba, none)",
587 .name = "boot",
588 .type = QEMU_OPT_BOOL,
589 .help = "(deprecated, ignored)",
591 .name = "addr",
592 .type = QEMU_OPT_STRING,
593 .help = "pci address (virtio only)",
595 .name = "serial",
596 .type = QEMU_OPT_STRING,
597 .help = "disk serial number",
599 .name = "file",
600 .type = QEMU_OPT_STRING,
601 .help = "file name",
604 /* Options that are passed on, but have special semantics with -drive */
606 .name = "read-only",
607 .type = QEMU_OPT_BOOL,
608 .help = "open drive file as read-only",
610 .name = "rerror",
611 .type = QEMU_OPT_STRING,
612 .help = "read error action",
614 .name = "werror",
615 .type = QEMU_OPT_STRING,
616 .help = "write error action",
618 .name = "copy-on-read",
619 .type = QEMU_OPT_BOOL,
620 .help = "copy read data from backing file into image file",
623 { /* end of list */ }
627 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
629 const char *value;
630 DriveInfo *dinfo = NULL;
631 QDict *bs_opts;
632 QemuOpts *legacy_opts;
633 DriveMediaType media = MEDIA_DISK;
634 BlockInterfaceType type;
635 int cyls, heads, secs, translation;
636 int max_devs, bus_id, unit_id, index;
637 const char *devaddr;
638 const char *werror, *rerror;
639 bool read_only = false;
640 bool copy_on_read;
641 const char *serial;
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 error_report("%s", error_get_pretty(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 /* Serial number */
846 serial = qemu_opt_get(legacy_opts, "serial");
848 /* no id supplied -> create one */
849 if (qemu_opts_id(all_opts) == NULL) {
850 char *new_id;
851 const char *mediastr = "";
852 if (type == IF_IDE || type == IF_SCSI) {
853 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
855 if (max_devs) {
856 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
857 mediastr, unit_id);
858 } else {
859 new_id = g_strdup_printf("%s%s%i", if_name[type],
860 mediastr, unit_id);
862 qdict_put(bs_opts, "id", qstring_from_str(new_id));
863 g_free(new_id);
866 /* Add virtio block device */
867 devaddr = qemu_opt_get(legacy_opts, "addr");
868 if (devaddr && type != IF_VIRTIO) {
869 error_report("addr is not supported by this bus type");
870 goto fail;
873 if (type == IF_VIRTIO) {
874 QemuOpts *devopts;
875 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
876 &error_abort);
877 if (arch_type == QEMU_ARCH_S390X) {
878 qemu_opt_set(devopts, "driver", "virtio-blk-s390");
879 } else {
880 qemu_opt_set(devopts, "driver", "virtio-blk-pci");
882 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
883 if (devaddr) {
884 qemu_opt_set(devopts, "addr", devaddr);
888 filename = qemu_opt_get(legacy_opts, "file");
890 /* Check werror/rerror compatibility with if=... */
891 werror = qemu_opt_get(legacy_opts, "werror");
892 if (werror != NULL) {
893 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
894 type != IF_NONE) {
895 error_report("werror is not supported by this bus type");
896 goto fail;
898 qdict_put(bs_opts, "werror", qstring_from_str(werror));
901 rerror = qemu_opt_get(legacy_opts, "rerror");
902 if (rerror != NULL) {
903 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
904 type != IF_NONE) {
905 error_report("rerror is not supported by this bus type");
906 goto fail;
908 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
911 /* Actual block device init: Functionality shared with blockdev-add */
912 dinfo = blockdev_init(filename, bs_opts, &local_err);
913 bs_opts = NULL;
914 if (dinfo == NULL) {
915 if (local_err) {
916 error_report("%s", error_get_pretty(local_err));
917 error_free(local_err);
919 goto fail;
920 } else {
921 assert(!local_err);
924 /* Set legacy DriveInfo fields */
925 dinfo->enable_auto_del = true;
926 dinfo->opts = all_opts;
928 dinfo->cyls = cyls;
929 dinfo->heads = heads;
930 dinfo->secs = secs;
931 dinfo->trans = translation;
933 dinfo->type = type;
934 dinfo->bus = bus_id;
935 dinfo->unit = unit_id;
936 dinfo->devaddr = devaddr;
938 dinfo->serial = g_strdup(serial);
940 switch(type) {
941 case IF_IDE:
942 case IF_SCSI:
943 case IF_XEN:
944 case IF_NONE:
945 dinfo->media_cd = media == MEDIA_CDROM;
946 break;
947 default:
948 break;
951 fail:
952 qemu_opts_del(legacy_opts);
953 QDECREF(bs_opts);
954 return dinfo;
957 void do_commit(Monitor *mon, const QDict *qdict)
959 const char *device = qdict_get_str(qdict, "device");
960 BlockDriverState *bs;
961 int ret;
963 if (!strcmp(device, "all")) {
964 ret = bdrv_commit_all();
965 } else {
966 bs = bdrv_find(device);
967 if (!bs) {
968 monitor_printf(mon, "Device '%s' not found\n", device);
969 return;
971 ret = bdrv_commit(bs);
973 if (ret < 0) {
974 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
975 strerror(-ret));
979 static void blockdev_do_action(int kind, void *data, Error **errp)
981 TransactionAction action;
982 TransactionActionList list;
984 action.kind = kind;
985 action.data = data;
986 list.value = &action;
987 list.next = NULL;
988 qmp_transaction(&list, errp);
991 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
992 bool has_node_name, const char *node_name,
993 const char *snapshot_file,
994 bool has_snapshot_node_name,
995 const char *snapshot_node_name,
996 bool has_format, const char *format,
997 bool has_mode, NewImageMode mode, Error **errp)
999 BlockdevSnapshot snapshot = {
1000 .has_device = has_device,
1001 .device = (char *) device,
1002 .has_node_name = has_node_name,
1003 .node_name = (char *) node_name,
1004 .snapshot_file = (char *) snapshot_file,
1005 .has_snapshot_node_name = has_snapshot_node_name,
1006 .snapshot_node_name = (char *) snapshot_node_name,
1007 .has_format = has_format,
1008 .format = (char *) format,
1009 .has_mode = has_mode,
1010 .mode = mode,
1012 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1013 &snapshot, errp);
1016 void qmp_blockdev_snapshot_internal_sync(const char *device,
1017 const char *name,
1018 Error **errp)
1020 BlockdevSnapshotInternal snapshot = {
1021 .device = (char *) device,
1022 .name = (char *) name
1025 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1026 &snapshot, errp);
1029 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1030 bool has_id,
1031 const char *id,
1032 bool has_name,
1033 const char *name,
1034 Error **errp)
1036 BlockDriverState *bs = bdrv_find(device);
1037 QEMUSnapshotInfo sn;
1038 Error *local_err = NULL;
1039 SnapshotInfo *info = NULL;
1040 int ret;
1042 if (!bs) {
1043 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1044 return NULL;
1047 if (!has_id) {
1048 id = NULL;
1051 if (!has_name) {
1052 name = NULL;
1055 if (!id && !name) {
1056 error_setg(errp, "Name or id must be provided");
1057 return NULL;
1060 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1061 if (local_err) {
1062 error_propagate(errp, local_err);
1063 return NULL;
1065 if (!ret) {
1066 error_setg(errp,
1067 "Snapshot with id '%s' and name '%s' does not exist on "
1068 "device '%s'",
1069 STR_OR_NULL(id), STR_OR_NULL(name), device);
1070 return NULL;
1073 bdrv_snapshot_delete(bs, id, name, &local_err);
1074 if (local_err) {
1075 error_propagate(errp, local_err);
1076 return NULL;
1079 info = g_new0(SnapshotInfo, 1);
1080 info->id = g_strdup(sn.id_str);
1081 info->name = g_strdup(sn.name);
1082 info->date_nsec = sn.date_nsec;
1083 info->date_sec = sn.date_sec;
1084 info->vm_state_size = sn.vm_state_size;
1085 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1086 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1088 return info;
1091 /* New and old BlockDriverState structs for group snapshots */
1093 typedef struct BlkTransactionState BlkTransactionState;
1095 /* Only prepare() may fail. In a single transaction, only one of commit() or
1096 abort() will be called, clean() will always be called if it present. */
1097 typedef struct BdrvActionOps {
1098 /* Size of state struct, in bytes. */
1099 size_t instance_size;
1100 /* Prepare the work, must NOT be NULL. */
1101 void (*prepare)(BlkTransactionState *common, Error **errp);
1102 /* Commit the changes, can be NULL. */
1103 void (*commit)(BlkTransactionState *common);
1104 /* Abort the changes on fail, can be NULL. */
1105 void (*abort)(BlkTransactionState *common);
1106 /* Clean up resource in the end, can be NULL. */
1107 void (*clean)(BlkTransactionState *common);
1108 } BdrvActionOps;
1111 * This structure must be arranged as first member in child type, assuming
1112 * that compiler will also arrange it to the same address with parent instance.
1113 * Later it will be used in free().
1115 struct BlkTransactionState {
1116 TransactionAction *action;
1117 const BdrvActionOps *ops;
1118 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
1121 /* internal snapshot private data */
1122 typedef struct InternalSnapshotState {
1123 BlkTransactionState common;
1124 BlockDriverState *bs;
1125 QEMUSnapshotInfo sn;
1126 } InternalSnapshotState;
1128 static void internal_snapshot_prepare(BlkTransactionState *common,
1129 Error **errp)
1131 Error *local_err = NULL;
1132 const char *device;
1133 const char *name;
1134 BlockDriverState *bs;
1135 QEMUSnapshotInfo old_sn, *sn;
1136 bool ret;
1137 qemu_timeval tv;
1138 BlockdevSnapshotInternal *internal;
1139 InternalSnapshotState *state;
1140 int ret1;
1142 g_assert(common->action->kind ==
1143 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1144 internal = common->action->blockdev_snapshot_internal_sync;
1145 state = DO_UPCAST(InternalSnapshotState, common, common);
1147 /* 1. parse input */
1148 device = internal->device;
1149 name = internal->name;
1151 /* 2. check for validation */
1152 bs = bdrv_find(device);
1153 if (!bs) {
1154 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1155 return;
1158 if (!bdrv_is_inserted(bs)) {
1159 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1160 return;
1163 if (bdrv_is_read_only(bs)) {
1164 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1165 return;
1168 if (!bdrv_can_snapshot(bs)) {
1169 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1170 bs->drv->format_name, device, "internal snapshot");
1171 return;
1174 if (!strlen(name)) {
1175 error_setg(errp, "Name is empty");
1176 return;
1179 /* check whether a snapshot with name exist */
1180 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1181 &local_err);
1182 if (local_err) {
1183 error_propagate(errp, local_err);
1184 return;
1185 } else if (ret) {
1186 error_setg(errp,
1187 "Snapshot with name '%s' already exists on device '%s'",
1188 name, device);
1189 return;
1192 /* 3. take the snapshot */
1193 sn = &state->sn;
1194 pstrcpy(sn->name, sizeof(sn->name), name);
1195 qemu_gettimeofday(&tv);
1196 sn->date_sec = tv.tv_sec;
1197 sn->date_nsec = tv.tv_usec * 1000;
1198 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1200 ret1 = bdrv_snapshot_create(bs, sn);
1201 if (ret1 < 0) {
1202 error_setg_errno(errp, -ret1,
1203 "Failed to create snapshot '%s' on device '%s'",
1204 name, device);
1205 return;
1208 /* 4. succeed, mark a snapshot is created */
1209 state->bs = bs;
1212 static void internal_snapshot_abort(BlkTransactionState *common)
1214 InternalSnapshotState *state =
1215 DO_UPCAST(InternalSnapshotState, common, common);
1216 BlockDriverState *bs = state->bs;
1217 QEMUSnapshotInfo *sn = &state->sn;
1218 Error *local_error = NULL;
1220 if (!bs) {
1221 return;
1224 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1225 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1226 "device '%s' in abort: %s",
1227 sn->id_str,
1228 sn->name,
1229 bdrv_get_device_name(bs),
1230 error_get_pretty(local_error));
1231 error_free(local_error);
1235 /* external snapshot private data */
1236 typedef struct ExternalSnapshotState {
1237 BlkTransactionState common;
1238 BlockDriverState *old_bs;
1239 BlockDriverState *new_bs;
1240 } ExternalSnapshotState;
1242 static void external_snapshot_prepare(BlkTransactionState *common,
1243 Error **errp)
1245 BlockDriver *drv;
1246 int flags, ret;
1247 QDict *options = NULL;
1248 Error *local_err = NULL;
1249 bool has_device = false;
1250 const char *device;
1251 bool has_node_name = false;
1252 const char *node_name;
1253 bool has_snapshot_node_name = false;
1254 const char *snapshot_node_name;
1255 const char *new_image_file;
1256 const char *format = "qcow2";
1257 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1258 ExternalSnapshotState *state =
1259 DO_UPCAST(ExternalSnapshotState, common, common);
1260 TransactionAction *action = common->action;
1262 /* get parameters */
1263 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
1265 has_device = action->blockdev_snapshot_sync->has_device;
1266 device = action->blockdev_snapshot_sync->device;
1267 has_node_name = action->blockdev_snapshot_sync->has_node_name;
1268 node_name = action->blockdev_snapshot_sync->node_name;
1269 has_snapshot_node_name =
1270 action->blockdev_snapshot_sync->has_snapshot_node_name;
1271 snapshot_node_name = action->blockdev_snapshot_sync->snapshot_node_name;
1273 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1274 if (action->blockdev_snapshot_sync->has_format) {
1275 format = action->blockdev_snapshot_sync->format;
1277 if (action->blockdev_snapshot_sync->has_mode) {
1278 mode = action->blockdev_snapshot_sync->mode;
1281 /* start processing */
1282 drv = bdrv_find_format(format);
1283 if (!drv) {
1284 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1285 return;
1288 state->old_bs = bdrv_lookup_bs(has_device ? device : NULL,
1289 has_node_name ? node_name : NULL,
1290 &local_err);
1291 if (local_err) {
1292 error_propagate(errp, local_err);
1293 return;
1296 if (has_node_name && !has_snapshot_node_name) {
1297 error_setg(errp, "New snapshot node name missing");
1298 return;
1301 if (has_snapshot_node_name && bdrv_find_node(snapshot_node_name)) {
1302 error_setg(errp, "New snapshot node name already existing");
1303 return;
1306 if (!bdrv_is_inserted(state->old_bs)) {
1307 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1308 return;
1311 if (bdrv_op_is_blocked(state->old_bs,
1312 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1313 return;
1316 if (!bdrv_is_read_only(state->old_bs)) {
1317 if (bdrv_flush(state->old_bs)) {
1318 error_set(errp, QERR_IO_ERROR);
1319 return;
1323 if (!bdrv_is_first_non_filter(state->old_bs)) {
1324 error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1325 return;
1328 flags = state->old_bs->open_flags;
1330 /* create new image w/backing file */
1331 if (mode != NEW_IMAGE_MODE_EXISTING) {
1332 bdrv_img_create(new_image_file, format,
1333 state->old_bs->filename,
1334 state->old_bs->drv->format_name,
1335 NULL, -1, flags, &local_err, false);
1336 if (local_err) {
1337 error_propagate(errp, local_err);
1338 return;
1342 if (has_snapshot_node_name) {
1343 options = qdict_new();
1344 qdict_put(options, "node-name",
1345 qstring_from_str(snapshot_node_name));
1348 /* TODO Inherit bs->options or only take explicit options with an
1349 * extended QMP command? */
1350 assert(state->new_bs == NULL);
1351 ret = bdrv_open(&state->new_bs, new_image_file, NULL, options,
1352 flags | BDRV_O_NO_BACKING, drv, &local_err);
1353 /* We will manually add the backing_hd field to the bs later */
1354 if (ret != 0) {
1355 error_propagate(errp, local_err);
1359 static void external_snapshot_commit(BlkTransactionState *common)
1361 ExternalSnapshotState *state =
1362 DO_UPCAST(ExternalSnapshotState, common, common);
1364 /* This removes our old bs and adds the new bs */
1365 bdrv_append(state->new_bs, state->old_bs);
1366 /* We don't need (or want) to use the transactional
1367 * bdrv_reopen_multiple() across all the entries at once, because we
1368 * don't want to abort all of them if one of them fails the reopen */
1369 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
1370 NULL);
1373 static void external_snapshot_abort(BlkTransactionState *common)
1375 ExternalSnapshotState *state =
1376 DO_UPCAST(ExternalSnapshotState, common, common);
1377 if (state->new_bs) {
1378 bdrv_unref(state->new_bs);
1382 typedef struct DriveBackupState {
1383 BlkTransactionState common;
1384 BlockDriverState *bs;
1385 BlockJob *job;
1386 } DriveBackupState;
1388 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1390 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1391 DriveBackup *backup;
1392 Error *local_err = NULL;
1394 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1395 backup = common->action->drive_backup;
1397 qmp_drive_backup(backup->device, backup->target,
1398 backup->has_format, backup->format,
1399 backup->sync,
1400 backup->has_mode, backup->mode,
1401 backup->has_speed, backup->speed,
1402 backup->has_on_source_error, backup->on_source_error,
1403 backup->has_on_target_error, backup->on_target_error,
1404 &local_err);
1405 if (local_err) {
1406 error_propagate(errp, local_err);
1407 state->bs = NULL;
1408 state->job = NULL;
1409 return;
1412 state->bs = bdrv_find(backup->device);
1413 state->job = state->bs->job;
1416 static void drive_backup_abort(BlkTransactionState *common)
1418 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1419 BlockDriverState *bs = state->bs;
1421 /* Only cancel if it's the job we started */
1422 if (bs && bs->job && bs->job == state->job) {
1423 block_job_cancel_sync(bs->job);
1427 static void abort_prepare(BlkTransactionState *common, Error **errp)
1429 error_setg(errp, "Transaction aborted using Abort action");
1432 static void abort_commit(BlkTransactionState *common)
1434 g_assert_not_reached(); /* this action never succeeds */
1437 static const BdrvActionOps actions[] = {
1438 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
1439 .instance_size = sizeof(ExternalSnapshotState),
1440 .prepare = external_snapshot_prepare,
1441 .commit = external_snapshot_commit,
1442 .abort = external_snapshot_abort,
1444 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1445 .instance_size = sizeof(DriveBackupState),
1446 .prepare = drive_backup_prepare,
1447 .abort = drive_backup_abort,
1449 [TRANSACTION_ACTION_KIND_ABORT] = {
1450 .instance_size = sizeof(BlkTransactionState),
1451 .prepare = abort_prepare,
1452 .commit = abort_commit,
1454 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1455 .instance_size = sizeof(InternalSnapshotState),
1456 .prepare = internal_snapshot_prepare,
1457 .abort = internal_snapshot_abort,
1462 * 'Atomic' group snapshots. The snapshots are taken as a set, and if any fail
1463 * then we do not pivot any of the devices in the group, and abandon the
1464 * snapshots
1466 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1468 TransactionActionList *dev_entry = dev_list;
1469 BlkTransactionState *state, *next;
1470 Error *local_err = NULL;
1472 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1473 QSIMPLEQ_INIT(&snap_bdrv_states);
1475 /* drain all i/o before any snapshots */
1476 bdrv_drain_all();
1478 /* We don't do anything in this loop that commits us to the snapshot */
1479 while (NULL != dev_entry) {
1480 TransactionAction *dev_info = NULL;
1481 const BdrvActionOps *ops;
1483 dev_info = dev_entry->value;
1484 dev_entry = dev_entry->next;
1486 assert(dev_info->kind < ARRAY_SIZE(actions));
1488 ops = &actions[dev_info->kind];
1489 assert(ops->instance_size > 0);
1491 state = g_malloc0(ops->instance_size);
1492 state->ops = ops;
1493 state->action = dev_info;
1494 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1496 state->ops->prepare(state, &local_err);
1497 if (local_err) {
1498 error_propagate(errp, local_err);
1499 goto delete_and_fail;
1503 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1504 if (state->ops->commit) {
1505 state->ops->commit(state);
1509 /* success */
1510 goto exit;
1512 delete_and_fail:
1514 * failure, and it is all-or-none; abandon each new bs, and keep using
1515 * the original bs for all images
1517 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1518 if (state->ops->abort) {
1519 state->ops->abort(state);
1522 exit:
1523 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1524 if (state->ops->clean) {
1525 state->ops->clean(state);
1527 g_free(state);
1532 static void eject_device(BlockDriverState *bs, int force, Error **errp)
1534 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
1535 return;
1537 if (!bdrv_dev_has_removable_media(bs)) {
1538 error_setg(errp, "Device '%s' is not removable",
1539 bdrv_get_device_name(bs));
1540 return;
1543 if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
1544 bdrv_dev_eject_request(bs, force);
1545 if (!force) {
1546 error_setg(errp, "Device '%s' is locked",
1547 bdrv_get_device_name(bs));
1548 return;
1552 bdrv_close(bs);
1555 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1557 BlockDriverState *bs;
1559 bs = bdrv_find(device);
1560 if (!bs) {
1561 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1562 return;
1565 eject_device(bs, force, errp);
1568 void qmp_block_passwd(bool has_device, const char *device,
1569 bool has_node_name, const char *node_name,
1570 const char *password, Error **errp)
1572 Error *local_err = NULL;
1573 BlockDriverState *bs;
1574 int err;
1576 bs = bdrv_lookup_bs(has_device ? device : NULL,
1577 has_node_name ? node_name : NULL,
1578 &local_err);
1579 if (local_err) {
1580 error_propagate(errp, local_err);
1581 return;
1584 err = bdrv_set_key(bs, password);
1585 if (err == -EINVAL) {
1586 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1587 return;
1588 } else if (err < 0) {
1589 error_set(errp, QERR_INVALID_PASSWORD);
1590 return;
1594 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1595 int bdrv_flags, BlockDriver *drv,
1596 const char *password, Error **errp)
1598 Error *local_err = NULL;
1599 int ret;
1601 ret = bdrv_open(&bs, filename, NULL, NULL, bdrv_flags, drv, &local_err);
1602 if (ret < 0) {
1603 error_propagate(errp, local_err);
1604 return;
1607 if (bdrv_key_required(bs)) {
1608 if (password) {
1609 if (bdrv_set_key(bs, password) < 0) {
1610 error_set(errp, QERR_INVALID_PASSWORD);
1612 } else {
1613 error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1614 bdrv_get_encrypted_filename(bs));
1616 } else if (password) {
1617 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1621 void qmp_change_blockdev(const char *device, const char *filename,
1622 const char *format, Error **errp)
1624 BlockDriverState *bs;
1625 BlockDriver *drv = NULL;
1626 int bdrv_flags;
1627 Error *err = NULL;
1629 bs = bdrv_find(device);
1630 if (!bs) {
1631 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1632 return;
1635 if (format) {
1636 drv = bdrv_find_whitelisted_format(format, bs->read_only);
1637 if (!drv) {
1638 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1639 return;
1643 eject_device(bs, 0, &err);
1644 if (err) {
1645 error_propagate(errp, err);
1646 return;
1649 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1650 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1652 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1655 /* throttling disk I/O limits */
1656 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1657 int64_t bps_wr,
1658 int64_t iops,
1659 int64_t iops_rd,
1660 int64_t iops_wr,
1661 bool has_bps_max,
1662 int64_t bps_max,
1663 bool has_bps_rd_max,
1664 int64_t bps_rd_max,
1665 bool has_bps_wr_max,
1666 int64_t bps_wr_max,
1667 bool has_iops_max,
1668 int64_t iops_max,
1669 bool has_iops_rd_max,
1670 int64_t iops_rd_max,
1671 bool has_iops_wr_max,
1672 int64_t iops_wr_max,
1673 bool has_iops_size,
1674 int64_t iops_size, Error **errp)
1676 ThrottleConfig cfg;
1677 BlockDriverState *bs;
1678 AioContext *aio_context;
1680 bs = bdrv_find(device);
1681 if (!bs) {
1682 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1683 return;
1686 memset(&cfg, 0, sizeof(cfg));
1687 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1688 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1689 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1691 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1692 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1693 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1695 if (has_bps_max) {
1696 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1698 if (has_bps_rd_max) {
1699 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1701 if (has_bps_wr_max) {
1702 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1704 if (has_iops_max) {
1705 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1707 if (has_iops_rd_max) {
1708 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1710 if (has_iops_wr_max) {
1711 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1714 if (has_iops_size) {
1715 cfg.op_size = iops_size;
1718 if (!check_throttle_config(&cfg, errp)) {
1719 return;
1722 aio_context = bdrv_get_aio_context(bs);
1723 aio_context_acquire(aio_context);
1725 if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
1726 bdrv_io_limits_enable(bs);
1727 } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
1728 bdrv_io_limits_disable(bs);
1731 if (bs->io_limits_enabled) {
1732 bdrv_set_io_limits(bs, &cfg);
1735 aio_context_release(aio_context);
1738 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1740 const char *id = qdict_get_str(qdict, "id");
1741 BlockDriverState *bs;
1742 DriveInfo *dinfo;
1743 AioContext *aio_context;
1744 Error *local_err = NULL;
1746 bs = bdrv_find(id);
1747 if (!bs) {
1748 error_report("Device '%s' not found", id);
1749 return -1;
1752 dinfo = drive_get_by_blockdev(bs);
1753 if (dinfo && !dinfo->enable_auto_del) {
1754 error_report("Deleting device added with blockdev-add"
1755 " is not supported");
1756 return -1;
1759 aio_context = bdrv_get_aio_context(bs);
1760 aio_context_acquire(aio_context);
1762 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
1763 error_report("%s", error_get_pretty(local_err));
1764 error_free(local_err);
1765 aio_context_release(aio_context);
1766 return -1;
1769 /* quiesce block driver; prevent further io */
1770 bdrv_drain_all();
1771 bdrv_flush(bs);
1772 bdrv_close(bs);
1774 /* if we have a device attached to this BlockDriverState
1775 * then we need to make the drive anonymous until the device
1776 * can be removed. If this is a drive with no device backing
1777 * then we can just get rid of the block driver state right here.
1779 if (bdrv_get_attached_dev(bs)) {
1780 bdrv_make_anon(bs);
1782 /* Further I/O must not pause the guest */
1783 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1784 BLOCKDEV_ON_ERROR_REPORT);
1785 } else {
1786 drive_del(dinfo);
1789 aio_context_release(aio_context);
1790 return 0;
1793 void qmp_block_resize(bool has_device, const char *device,
1794 bool has_node_name, const char *node_name,
1795 int64_t size, Error **errp)
1797 Error *local_err = NULL;
1798 BlockDriverState *bs;
1799 AioContext *aio_context;
1800 int ret;
1802 bs = bdrv_lookup_bs(has_device ? device : NULL,
1803 has_node_name ? node_name : NULL,
1804 &local_err);
1805 if (local_err) {
1806 error_propagate(errp, local_err);
1807 return;
1810 aio_context = bdrv_get_aio_context(bs);
1811 aio_context_acquire(aio_context);
1813 if (!bdrv_is_first_non_filter(bs)) {
1814 error_set(errp, QERR_FEATURE_DISABLED, "resize");
1815 goto out;
1818 if (size < 0) {
1819 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1820 goto out;
1823 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
1824 error_set(errp, QERR_DEVICE_IN_USE, device);
1825 goto out;
1828 /* complete all in-flight operations before resizing the device */
1829 bdrv_drain_all();
1831 ret = bdrv_truncate(bs, size);
1832 switch (ret) {
1833 case 0:
1834 break;
1835 case -ENOMEDIUM:
1836 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1837 break;
1838 case -ENOTSUP:
1839 error_set(errp, QERR_UNSUPPORTED);
1840 break;
1841 case -EACCES:
1842 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1843 break;
1844 case -EBUSY:
1845 error_set(errp, QERR_DEVICE_IN_USE, device);
1846 break;
1847 default:
1848 error_setg_errno(errp, -ret, "Could not resize");
1849 break;
1852 out:
1853 aio_context_release(aio_context);
1856 static void block_job_cb(void *opaque, int ret)
1858 BlockDriverState *bs = opaque;
1859 const char *msg = NULL;
1861 trace_block_job_cb(bs, bs->job, ret);
1863 assert(bs->job);
1865 if (ret < 0) {
1866 msg = strerror(-ret);
1869 if (block_job_is_cancelled(bs->job)) {
1870 block_job_event_cancelled(bs->job);
1871 } else {
1872 block_job_event_completed(bs->job, msg);
1875 bdrv_put_ref_bh_schedule(bs);
1878 void qmp_block_stream(const char *device,
1879 bool has_base, const char *base,
1880 bool has_backing_file, const char *backing_file,
1881 bool has_speed, int64_t speed,
1882 bool has_on_error, BlockdevOnError on_error,
1883 Error **errp)
1885 BlockDriverState *bs;
1886 BlockDriverState *base_bs = NULL;
1887 Error *local_err = NULL;
1888 const char *base_name = NULL;
1890 if (!has_on_error) {
1891 on_error = BLOCKDEV_ON_ERROR_REPORT;
1894 bs = bdrv_find(device);
1895 if (!bs) {
1896 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1897 return;
1900 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
1901 return;
1904 if (has_base) {
1905 base_bs = bdrv_find_backing_image(bs, base);
1906 if (base_bs == NULL) {
1907 error_set(errp, QERR_BASE_NOT_FOUND, base);
1908 return;
1910 base_name = base;
1913 /* if we are streaming the entire chain, the result will have no backing
1914 * file, and specifying one is therefore an error */
1915 if (base_bs == NULL && has_backing_file) {
1916 error_setg(errp, "backing file specified, but streaming the "
1917 "entire chain");
1918 return;
1921 /* backing_file string overrides base bs filename */
1922 base_name = has_backing_file ? backing_file : base_name;
1924 stream_start(bs, base_bs, base_name, has_speed ? speed : 0,
1925 on_error, block_job_cb, bs, &local_err);
1926 if (local_err) {
1927 error_propagate(errp, local_err);
1928 return;
1931 trace_qmp_block_stream(bs, bs->job);
1934 void qmp_block_commit(const char *device,
1935 bool has_base, const char *base,
1936 bool has_top, const char *top,
1937 bool has_backing_file, const char *backing_file,
1938 bool has_speed, int64_t speed,
1939 Error **errp)
1941 BlockDriverState *bs;
1942 BlockDriverState *base_bs, *top_bs;
1943 Error *local_err = NULL;
1944 /* This will be part of the QMP command, if/when the
1945 * BlockdevOnError change for blkmirror makes it in
1947 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
1949 if (!has_speed) {
1950 speed = 0;
1953 /* drain all i/o before commits */
1954 bdrv_drain_all();
1956 /* Important Note:
1957 * libvirt relies on the DeviceNotFound error class in order to probe for
1958 * live commit feature versions; for this to work, we must make sure to
1959 * perform the device lookup before any generic errors that may occur in a
1960 * scenario in which all optional arguments are omitted. */
1961 bs = bdrv_find(device);
1962 if (!bs) {
1963 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1964 return;
1967 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, errp)) {
1968 return;
1971 /* default top_bs is the active layer */
1972 top_bs = bs;
1974 if (has_top && top) {
1975 if (strcmp(bs->filename, top) != 0) {
1976 top_bs = bdrv_find_backing_image(bs, top);
1980 if (top_bs == NULL) {
1981 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
1982 return;
1985 if (has_base && base) {
1986 base_bs = bdrv_find_backing_image(top_bs, base);
1987 } else {
1988 base_bs = bdrv_find_base(top_bs);
1991 if (base_bs == NULL) {
1992 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
1993 return;
1996 /* Do not allow attempts to commit an image into itself */
1997 if (top_bs == base_bs) {
1998 error_setg(errp, "cannot commit an image into itself");
1999 return;
2002 if (top_bs == bs) {
2003 if (has_backing_file) {
2004 error_setg(errp, "'backing-file' specified,"
2005 " but 'top' is the active layer");
2006 return;
2008 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2009 bs, &local_err);
2010 } else {
2011 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2012 has_backing_file ? backing_file : NULL, &local_err);
2014 if (local_err != NULL) {
2015 error_propagate(errp, local_err);
2016 return;
2020 void qmp_drive_backup(const char *device, const char *target,
2021 bool has_format, const char *format,
2022 enum MirrorSyncMode sync,
2023 bool has_mode, enum NewImageMode mode,
2024 bool has_speed, int64_t speed,
2025 bool has_on_source_error, BlockdevOnError on_source_error,
2026 bool has_on_target_error, BlockdevOnError on_target_error,
2027 Error **errp)
2029 BlockDriverState *bs;
2030 BlockDriverState *target_bs;
2031 BlockDriverState *source = NULL;
2032 BlockDriver *drv = NULL;
2033 Error *local_err = NULL;
2034 int flags;
2035 int64_t size;
2036 int ret;
2038 if (!has_speed) {
2039 speed = 0;
2041 if (!has_on_source_error) {
2042 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2044 if (!has_on_target_error) {
2045 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2047 if (!has_mode) {
2048 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2051 bs = bdrv_find(device);
2052 if (!bs) {
2053 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2054 return;
2057 if (!bdrv_is_inserted(bs)) {
2058 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2059 return;
2062 if (!has_format) {
2063 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2065 if (format) {
2066 drv = bdrv_find_format(format);
2067 if (!drv) {
2068 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2069 return;
2073 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2074 return;
2077 flags = bs->open_flags | BDRV_O_RDWR;
2079 /* See if we have a backing HD we can use to create our new image
2080 * on top of. */
2081 if (sync == MIRROR_SYNC_MODE_TOP) {
2082 source = bs->backing_hd;
2083 if (!source) {
2084 sync = MIRROR_SYNC_MODE_FULL;
2087 if (sync == MIRROR_SYNC_MODE_NONE) {
2088 source = bs;
2091 size = bdrv_getlength(bs);
2092 if (size < 0) {
2093 error_setg_errno(errp, -size, "bdrv_getlength failed");
2094 return;
2097 if (mode != NEW_IMAGE_MODE_EXISTING) {
2098 assert(format && drv);
2099 if (source) {
2100 bdrv_img_create(target, format, source->filename,
2101 source->drv->format_name, NULL,
2102 size, flags, &local_err, false);
2103 } else {
2104 bdrv_img_create(target, format, NULL, NULL, NULL,
2105 size, flags, &local_err, false);
2109 if (local_err) {
2110 error_propagate(errp, local_err);
2111 return;
2114 target_bs = NULL;
2115 ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2116 if (ret < 0) {
2117 error_propagate(errp, local_err);
2118 return;
2121 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2122 block_job_cb, bs, &local_err);
2123 if (local_err != NULL) {
2124 bdrv_unref(target_bs);
2125 error_propagate(errp, local_err);
2126 return;
2130 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2132 return bdrv_named_nodes_list();
2135 #define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
2137 void qmp_drive_mirror(const char *device, const char *target,
2138 bool has_format, const char *format,
2139 bool has_node_name, const char *node_name,
2140 bool has_replaces, const char *replaces,
2141 enum MirrorSyncMode sync,
2142 bool has_mode, enum NewImageMode mode,
2143 bool has_speed, int64_t speed,
2144 bool has_granularity, uint32_t granularity,
2145 bool has_buf_size, int64_t buf_size,
2146 bool has_on_source_error, BlockdevOnError on_source_error,
2147 bool has_on_target_error, BlockdevOnError on_target_error,
2148 Error **errp)
2150 BlockDriverState *bs;
2151 BlockDriverState *source, *target_bs;
2152 BlockDriver *drv = NULL;
2153 Error *local_err = NULL;
2154 QDict *options = NULL;
2155 int flags;
2156 int64_t size;
2157 int ret;
2159 if (!has_speed) {
2160 speed = 0;
2162 if (!has_on_source_error) {
2163 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2165 if (!has_on_target_error) {
2166 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2168 if (!has_mode) {
2169 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2171 if (!has_granularity) {
2172 granularity = 0;
2174 if (!has_buf_size) {
2175 buf_size = DEFAULT_MIRROR_BUF_SIZE;
2178 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2179 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2180 "a value in range [512B, 64MB]");
2181 return;
2183 if (granularity & (granularity - 1)) {
2184 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity", "power of 2");
2185 return;
2188 bs = bdrv_find(device);
2189 if (!bs) {
2190 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2191 return;
2194 if (!bdrv_is_inserted(bs)) {
2195 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2196 return;
2199 if (!has_format) {
2200 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2202 if (format) {
2203 drv = bdrv_find_format(format);
2204 if (!drv) {
2205 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2206 return;
2210 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2211 return;
2214 flags = bs->open_flags | BDRV_O_RDWR;
2215 source = bs->backing_hd;
2216 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2217 sync = MIRROR_SYNC_MODE_FULL;
2219 if (sync == MIRROR_SYNC_MODE_NONE) {
2220 source = bs;
2223 size = bdrv_getlength(bs);
2224 if (size < 0) {
2225 error_setg_errno(errp, -size, "bdrv_getlength failed");
2226 return;
2229 if (has_replaces) {
2230 BlockDriverState *to_replace_bs;
2232 if (!has_node_name) {
2233 error_setg(errp, "a node-name must be provided when replacing a"
2234 " named node of the graph");
2235 return;
2238 to_replace_bs = check_to_replace_node(replaces, &local_err);
2240 if (!to_replace_bs) {
2241 error_propagate(errp, local_err);
2242 return;
2245 if (size != bdrv_getlength(to_replace_bs)) {
2246 error_setg(errp, "cannot replace image with a mirror image of "
2247 "different size");
2248 return;
2252 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2253 && mode != NEW_IMAGE_MODE_EXISTING)
2255 /* create new image w/o backing file */
2256 assert(format && drv);
2257 bdrv_img_create(target, format,
2258 NULL, NULL, NULL, size, flags, &local_err, false);
2259 } else {
2260 switch (mode) {
2261 case NEW_IMAGE_MODE_EXISTING:
2262 break;
2263 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2264 /* create new image with backing file */
2265 bdrv_img_create(target, format,
2266 source->filename,
2267 source->drv->format_name,
2268 NULL, size, flags, &local_err, false);
2269 break;
2270 default:
2271 abort();
2275 if (local_err) {
2276 error_propagate(errp, local_err);
2277 return;
2280 if (has_node_name) {
2281 options = qdict_new();
2282 qdict_put(options, "node-name", qstring_from_str(node_name));
2285 /* Mirroring takes care of copy-on-write using the source's backing
2286 * file.
2288 target_bs = NULL;
2289 ret = bdrv_open(&target_bs, target, NULL, options,
2290 flags | BDRV_O_NO_BACKING, drv, &local_err);
2291 if (ret < 0) {
2292 error_propagate(errp, local_err);
2293 return;
2296 /* pass the node name to replace to mirror start since it's loose coupling
2297 * and will allow to check whether the node still exist at mirror completion
2299 mirror_start(bs, target_bs,
2300 has_replaces ? replaces : NULL,
2301 speed, granularity, buf_size, sync,
2302 on_source_error, on_target_error,
2303 block_job_cb, bs, &local_err);
2304 if (local_err != NULL) {
2305 bdrv_unref(target_bs);
2306 error_propagate(errp, local_err);
2307 return;
2311 static BlockJob *find_block_job(const char *device)
2313 BlockDriverState *bs;
2315 bs = bdrv_find(device);
2316 if (!bs || !bs->job) {
2317 return NULL;
2319 return bs->job;
2322 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2324 BlockJob *job = find_block_job(device);
2326 if (!job) {
2327 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2328 return;
2331 block_job_set_speed(job, speed, errp);
2334 void qmp_block_job_cancel(const char *device,
2335 bool has_force, bool force, Error **errp)
2337 BlockJob *job = find_block_job(device);
2339 if (!has_force) {
2340 force = false;
2343 if (!job) {
2344 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2345 return;
2347 if (job->paused && !force) {
2348 error_setg(errp, "The block job for device '%s' is currently paused",
2349 device);
2350 return;
2353 trace_qmp_block_job_cancel(job);
2354 block_job_cancel(job);
2357 void qmp_block_job_pause(const char *device, Error **errp)
2359 BlockJob *job = find_block_job(device);
2361 if (!job) {
2362 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2363 return;
2366 trace_qmp_block_job_pause(job);
2367 block_job_pause(job);
2370 void qmp_block_job_resume(const char *device, Error **errp)
2372 BlockJob *job = find_block_job(device);
2374 if (!job) {
2375 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2376 return;
2379 trace_qmp_block_job_resume(job);
2380 block_job_resume(job);
2383 void qmp_block_job_complete(const char *device, Error **errp)
2385 BlockJob *job = find_block_job(device);
2387 if (!job) {
2388 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2389 return;
2392 trace_qmp_block_job_complete(job);
2393 block_job_complete(job, errp);
2396 void qmp_change_backing_file(const char *device,
2397 const char *image_node_name,
2398 const char *backing_file,
2399 Error **errp)
2401 BlockDriverState *bs = NULL;
2402 BlockDriverState *image_bs = NULL;
2403 Error *local_err = NULL;
2404 bool ro;
2405 int open_flags;
2406 int ret;
2408 /* find the top layer BDS of the chain */
2409 bs = bdrv_find(device);
2410 if (!bs) {
2411 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2412 return;
2415 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
2416 if (local_err) {
2417 error_propagate(errp, local_err);
2418 return;
2421 if (!image_bs) {
2422 error_setg(errp, "image file not found");
2423 return;
2426 if (bdrv_find_base(image_bs) == image_bs) {
2427 error_setg(errp, "not allowing backing file change on an image "
2428 "without a backing file");
2429 return;
2432 /* even though we are not necessarily operating on bs, we need it to
2433 * determine if block ops are currently prohibited on the chain */
2434 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
2435 return;
2438 /* final sanity check */
2439 if (!bdrv_chain_contains(bs, image_bs)) {
2440 error_setg(errp, "'%s' and image file are not in the same chain",
2441 device);
2442 return;
2445 /* if not r/w, reopen to make r/w */
2446 open_flags = image_bs->open_flags;
2447 ro = bdrv_is_read_only(image_bs);
2449 if (ro) {
2450 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
2451 if (local_err) {
2452 error_propagate(errp, local_err);
2453 return;
2457 ret = bdrv_change_backing_file(image_bs, backing_file,
2458 image_bs->drv ? image_bs->drv->format_name : "");
2460 if (ret < 0) {
2461 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
2462 backing_file);
2463 /* don't exit here, so we can try to restore open flags if
2464 * appropriate */
2467 if (ro) {
2468 bdrv_reopen(image_bs, open_flags, &local_err);
2469 if (local_err) {
2470 error_propagate(errp, local_err); /* will preserve prior errp */
2475 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2477 QmpOutputVisitor *ov = qmp_output_visitor_new();
2478 DriveInfo *dinfo;
2479 QObject *obj;
2480 QDict *qdict;
2481 Error *local_err = NULL;
2483 /* Require an ID in the top level */
2484 if (!options->has_id) {
2485 error_setg(errp, "Block device needs an ID");
2486 goto fail;
2489 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
2490 * cache.direct=false instead of silently switching to aio=threads, except
2491 * when called from drive_new().
2493 * For now, simply forbidding the combination for all drivers will do. */
2494 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2495 bool direct = options->has_cache &&
2496 options->cache->has_direct &&
2497 options->cache->direct;
2498 if (!direct) {
2499 error_setg(errp, "aio=native requires cache.direct=true");
2500 goto fail;
2504 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2505 &options, NULL, &local_err);
2506 if (local_err) {
2507 error_propagate(errp, local_err);
2508 goto fail;
2511 obj = qmp_output_get_qobject(ov);
2512 qdict = qobject_to_qdict(obj);
2514 qdict_flatten(qdict);
2516 dinfo = blockdev_init(NULL, qdict, &local_err);
2517 if (local_err) {
2518 error_propagate(errp, local_err);
2519 goto fail;
2522 if (bdrv_key_required(dinfo->bdrv)) {
2523 drive_del(dinfo);
2524 error_setg(errp, "blockdev-add doesn't support encrypted devices");
2525 goto fail;
2528 fail:
2529 qmp_output_visitor_cleanup(ov);
2532 static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
2534 BlockJobInfoList **prev = opaque;
2535 BlockJob *job = bs->job;
2537 if (job) {
2538 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2539 elem->value = block_job_query(bs->job);
2540 (*prev)->next = elem;
2541 *prev = elem;
2545 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2547 /* Dummy is a fake list element for holding the head pointer */
2548 BlockJobInfoList dummy = {};
2549 BlockJobInfoList *prev = &dummy;
2550 bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
2551 return dummy.next;
2554 QemuOptsList qemu_common_drive_opts = {
2555 .name = "drive",
2556 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2557 .desc = {
2559 .name = "snapshot",
2560 .type = QEMU_OPT_BOOL,
2561 .help = "enable/disable snapshot mode",
2563 .name = "discard",
2564 .type = QEMU_OPT_STRING,
2565 .help = "discard operation (ignore/off, unmap/on)",
2567 .name = "cache.writeback",
2568 .type = QEMU_OPT_BOOL,
2569 .help = "enables writeback mode for any caches",
2571 .name = "cache.direct",
2572 .type = QEMU_OPT_BOOL,
2573 .help = "enables use of O_DIRECT (bypass the host page cache)",
2575 .name = "cache.no-flush",
2576 .type = QEMU_OPT_BOOL,
2577 .help = "ignore any flush requests for the device",
2579 .name = "aio",
2580 .type = QEMU_OPT_STRING,
2581 .help = "host AIO implementation (threads, native)",
2583 .name = "format",
2584 .type = QEMU_OPT_STRING,
2585 .help = "disk format (raw, qcow2, ...)",
2587 .name = "rerror",
2588 .type = QEMU_OPT_STRING,
2589 .help = "read error action",
2591 .name = "werror",
2592 .type = QEMU_OPT_STRING,
2593 .help = "write error action",
2595 .name = "read-only",
2596 .type = QEMU_OPT_BOOL,
2597 .help = "open drive file as read-only",
2599 .name = "throttling.iops-total",
2600 .type = QEMU_OPT_NUMBER,
2601 .help = "limit total I/O operations per second",
2603 .name = "throttling.iops-read",
2604 .type = QEMU_OPT_NUMBER,
2605 .help = "limit read operations per second",
2607 .name = "throttling.iops-write",
2608 .type = QEMU_OPT_NUMBER,
2609 .help = "limit write operations per second",
2611 .name = "throttling.bps-total",
2612 .type = QEMU_OPT_NUMBER,
2613 .help = "limit total bytes per second",
2615 .name = "throttling.bps-read",
2616 .type = QEMU_OPT_NUMBER,
2617 .help = "limit read bytes per second",
2619 .name = "throttling.bps-write",
2620 .type = QEMU_OPT_NUMBER,
2621 .help = "limit write bytes per second",
2623 .name = "throttling.iops-total-max",
2624 .type = QEMU_OPT_NUMBER,
2625 .help = "I/O operations burst",
2627 .name = "throttling.iops-read-max",
2628 .type = QEMU_OPT_NUMBER,
2629 .help = "I/O operations read burst",
2631 .name = "throttling.iops-write-max",
2632 .type = QEMU_OPT_NUMBER,
2633 .help = "I/O operations write burst",
2635 .name = "throttling.bps-total-max",
2636 .type = QEMU_OPT_NUMBER,
2637 .help = "total bytes burst",
2639 .name = "throttling.bps-read-max",
2640 .type = QEMU_OPT_NUMBER,
2641 .help = "total bytes read burst",
2643 .name = "throttling.bps-write-max",
2644 .type = QEMU_OPT_NUMBER,
2645 .help = "total bytes write burst",
2647 .name = "throttling.iops-size",
2648 .type = QEMU_OPT_NUMBER,
2649 .help = "when limiting by iops max size of an I/O in bytes",
2651 .name = "copy-on-read",
2652 .type = QEMU_OPT_BOOL,
2653 .help = "copy read data from backing file into image file",
2655 .name = "detect-zeroes",
2656 .type = QEMU_OPT_STRING,
2657 .help = "try to optimize zero writes (off, on, unmap)",
2659 { /* end of list */ }
2663 QemuOptsList qemu_drive_opts = {
2664 .name = "drive",
2665 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2666 .desc = {
2668 * no elements => accept any params
2669 * validation will happen later
2671 { /* end of list */ }