target-arm: Push legacy wildcard TLB ops back into v6
[qemu-kvm.git] / blockdev.c
blobe919566c16daab004a4526e0e356a3024b99f58c
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 AioContext *aio_context;
1743 Error *local_err = NULL;
1745 bs = bdrv_find(id);
1746 if (!bs) {
1747 error_report("Device '%s' not found", id);
1748 return -1;
1751 aio_context = bdrv_get_aio_context(bs);
1752 aio_context_acquire(aio_context);
1754 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
1755 error_report("%s", error_get_pretty(local_err));
1756 error_free(local_err);
1757 aio_context_release(aio_context);
1758 return -1;
1761 /* quiesce block driver; prevent further io */
1762 bdrv_drain_all();
1763 bdrv_flush(bs);
1764 bdrv_close(bs);
1766 /* if we have a device attached to this BlockDriverState
1767 * then we need to make the drive anonymous until the device
1768 * can be removed. If this is a drive with no device backing
1769 * then we can just get rid of the block driver state right here.
1771 if (bdrv_get_attached_dev(bs)) {
1772 bdrv_make_anon(bs);
1774 /* Further I/O must not pause the guest */
1775 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1776 BLOCKDEV_ON_ERROR_REPORT);
1777 } else {
1778 drive_del(drive_get_by_blockdev(bs));
1781 aio_context_release(aio_context);
1782 return 0;
1785 void qmp_block_resize(bool has_device, const char *device,
1786 bool has_node_name, const char *node_name,
1787 int64_t size, Error **errp)
1789 Error *local_err = NULL;
1790 BlockDriverState *bs;
1791 AioContext *aio_context;
1792 int ret;
1794 bs = bdrv_lookup_bs(has_device ? device : NULL,
1795 has_node_name ? node_name : NULL,
1796 &local_err);
1797 if (local_err) {
1798 error_propagate(errp, local_err);
1799 return;
1802 aio_context = bdrv_get_aio_context(bs);
1803 aio_context_acquire(aio_context);
1805 if (!bdrv_is_first_non_filter(bs)) {
1806 error_set(errp, QERR_FEATURE_DISABLED, "resize");
1807 goto out;
1810 if (size < 0) {
1811 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1812 goto out;
1815 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
1816 error_set(errp, QERR_DEVICE_IN_USE, device);
1817 goto out;
1820 /* complete all in-flight operations before resizing the device */
1821 bdrv_drain_all();
1823 ret = bdrv_truncate(bs, size);
1824 switch (ret) {
1825 case 0:
1826 break;
1827 case -ENOMEDIUM:
1828 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1829 break;
1830 case -ENOTSUP:
1831 error_set(errp, QERR_UNSUPPORTED);
1832 break;
1833 case -EACCES:
1834 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1835 break;
1836 case -EBUSY:
1837 error_set(errp, QERR_DEVICE_IN_USE, device);
1838 break;
1839 default:
1840 error_setg_errno(errp, -ret, "Could not resize");
1841 break;
1844 out:
1845 aio_context_release(aio_context);
1848 static void block_job_cb(void *opaque, int ret)
1850 BlockDriverState *bs = opaque;
1851 const char *msg = NULL;
1853 trace_block_job_cb(bs, bs->job, ret);
1855 assert(bs->job);
1857 if (ret < 0) {
1858 msg = strerror(-ret);
1861 if (block_job_is_cancelled(bs->job)) {
1862 block_job_event_cancelled(bs->job);
1863 } else {
1864 block_job_event_completed(bs->job, msg);
1867 bdrv_put_ref_bh_schedule(bs);
1870 void qmp_block_stream(const char *device,
1871 bool has_base, const char *base,
1872 bool has_backing_file, const char *backing_file,
1873 bool has_speed, int64_t speed,
1874 bool has_on_error, BlockdevOnError on_error,
1875 Error **errp)
1877 BlockDriverState *bs;
1878 BlockDriverState *base_bs = NULL;
1879 Error *local_err = NULL;
1880 const char *base_name = NULL;
1882 if (!has_on_error) {
1883 on_error = BLOCKDEV_ON_ERROR_REPORT;
1886 bs = bdrv_find(device);
1887 if (!bs) {
1888 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1889 return;
1892 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
1893 return;
1896 if (has_base) {
1897 base_bs = bdrv_find_backing_image(bs, base);
1898 if (base_bs == NULL) {
1899 error_set(errp, QERR_BASE_NOT_FOUND, base);
1900 return;
1902 base_name = base;
1905 /* if we are streaming the entire chain, the result will have no backing
1906 * file, and specifying one is therefore an error */
1907 if (base_bs == NULL && has_backing_file) {
1908 error_setg(errp, "backing file specified, but streaming the "
1909 "entire chain");
1910 return;
1913 /* backing_file string overrides base bs filename */
1914 base_name = has_backing_file ? backing_file : base_name;
1916 stream_start(bs, base_bs, base_name, 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,
1928 bool has_top, const char *top,
1929 bool has_backing_file, const char *backing_file,
1930 bool has_speed, int64_t speed,
1931 Error **errp)
1933 BlockDriverState *bs;
1934 BlockDriverState *base_bs, *top_bs;
1935 Error *local_err = NULL;
1936 /* This will be part of the QMP command, if/when the
1937 * BlockdevOnError change for blkmirror makes it in
1939 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
1941 if (!has_speed) {
1942 speed = 0;
1945 /* drain all i/o before commits */
1946 bdrv_drain_all();
1948 /* Important Note:
1949 * libvirt relies on the DeviceNotFound error class in order to probe for
1950 * live commit feature versions; for this to work, we must make sure to
1951 * perform the device lookup before any generic errors that may occur in a
1952 * scenario in which all optional arguments are omitted. */
1953 bs = bdrv_find(device);
1954 if (!bs) {
1955 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1956 return;
1959 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, errp)) {
1960 return;
1963 /* default top_bs is the active layer */
1964 top_bs = bs;
1966 if (has_top && top) {
1967 if (strcmp(bs->filename, top) != 0) {
1968 top_bs = bdrv_find_backing_image(bs, top);
1972 if (top_bs == NULL) {
1973 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
1974 return;
1977 if (has_base && base) {
1978 base_bs = bdrv_find_backing_image(top_bs, base);
1979 } else {
1980 base_bs = bdrv_find_base(top_bs);
1983 if (base_bs == NULL) {
1984 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
1985 return;
1988 /* Do not allow attempts to commit an image into itself */
1989 if (top_bs == base_bs) {
1990 error_setg(errp, "cannot commit an image into itself");
1991 return;
1994 if (top_bs == bs) {
1995 if (has_backing_file) {
1996 error_setg(errp, "'backing-file' specified,"
1997 " but 'top' is the active layer");
1998 return;
2000 commit_active_start(bs, base_bs, speed, on_error, block_job_cb,
2001 bs, &local_err);
2002 } else {
2003 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
2004 has_backing_file ? backing_file : NULL, &local_err);
2006 if (local_err != NULL) {
2007 error_propagate(errp, local_err);
2008 return;
2012 void qmp_drive_backup(const char *device, const char *target,
2013 bool has_format, const char *format,
2014 enum MirrorSyncMode sync,
2015 bool has_mode, enum NewImageMode mode,
2016 bool has_speed, int64_t speed,
2017 bool has_on_source_error, BlockdevOnError on_source_error,
2018 bool has_on_target_error, BlockdevOnError on_target_error,
2019 Error **errp)
2021 BlockDriverState *bs;
2022 BlockDriverState *target_bs;
2023 BlockDriverState *source = NULL;
2024 BlockDriver *drv = NULL;
2025 Error *local_err = NULL;
2026 int flags;
2027 int64_t size;
2028 int ret;
2030 if (!has_speed) {
2031 speed = 0;
2033 if (!has_on_source_error) {
2034 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2036 if (!has_on_target_error) {
2037 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2039 if (!has_mode) {
2040 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2043 bs = bdrv_find(device);
2044 if (!bs) {
2045 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2046 return;
2049 if (!bdrv_is_inserted(bs)) {
2050 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2051 return;
2054 if (!has_format) {
2055 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2057 if (format) {
2058 drv = bdrv_find_format(format);
2059 if (!drv) {
2060 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2061 return;
2065 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
2066 return;
2069 flags = bs->open_flags | BDRV_O_RDWR;
2071 /* See if we have a backing HD we can use to create our new image
2072 * on top of. */
2073 if (sync == MIRROR_SYNC_MODE_TOP) {
2074 source = bs->backing_hd;
2075 if (!source) {
2076 sync = MIRROR_SYNC_MODE_FULL;
2079 if (sync == MIRROR_SYNC_MODE_NONE) {
2080 source = bs;
2083 size = bdrv_getlength(bs);
2084 if (size < 0) {
2085 error_setg_errno(errp, -size, "bdrv_getlength failed");
2086 return;
2089 if (mode != NEW_IMAGE_MODE_EXISTING) {
2090 assert(format && drv);
2091 if (source) {
2092 bdrv_img_create(target, format, source->filename,
2093 source->drv->format_name, NULL,
2094 size, flags, &local_err, false);
2095 } else {
2096 bdrv_img_create(target, format, NULL, NULL, NULL,
2097 size, flags, &local_err, false);
2101 if (local_err) {
2102 error_propagate(errp, local_err);
2103 return;
2106 target_bs = NULL;
2107 ret = bdrv_open(&target_bs, target, NULL, NULL, flags, drv, &local_err);
2108 if (ret < 0) {
2109 error_propagate(errp, local_err);
2110 return;
2113 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
2114 block_job_cb, bs, &local_err);
2115 if (local_err != NULL) {
2116 bdrv_unref(target_bs);
2117 error_propagate(errp, local_err);
2118 return;
2122 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
2124 return bdrv_named_nodes_list();
2127 #define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
2129 void qmp_drive_mirror(const char *device, const char *target,
2130 bool has_format, const char *format,
2131 bool has_node_name, const char *node_name,
2132 bool has_replaces, const char *replaces,
2133 enum MirrorSyncMode sync,
2134 bool has_mode, enum NewImageMode mode,
2135 bool has_speed, int64_t speed,
2136 bool has_granularity, uint32_t granularity,
2137 bool has_buf_size, int64_t buf_size,
2138 bool has_on_source_error, BlockdevOnError on_source_error,
2139 bool has_on_target_error, BlockdevOnError on_target_error,
2140 Error **errp)
2142 BlockDriverState *bs;
2143 BlockDriverState *source, *target_bs;
2144 BlockDriver *drv = NULL;
2145 Error *local_err = NULL;
2146 QDict *options = NULL;
2147 int flags;
2148 int64_t size;
2149 int ret;
2151 if (!has_speed) {
2152 speed = 0;
2154 if (!has_on_source_error) {
2155 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
2157 if (!has_on_target_error) {
2158 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
2160 if (!has_mode) {
2161 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
2163 if (!has_granularity) {
2164 granularity = 0;
2166 if (!has_buf_size) {
2167 buf_size = DEFAULT_MIRROR_BUF_SIZE;
2170 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
2171 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
2172 "a value in range [512B, 64MB]");
2173 return;
2175 if (granularity & (granularity - 1)) {
2176 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "granularity", "power of 2");
2177 return;
2180 bs = bdrv_find(device);
2181 if (!bs) {
2182 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2183 return;
2186 if (!bdrv_is_inserted(bs)) {
2187 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
2188 return;
2191 if (!has_format) {
2192 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2194 if (format) {
2195 drv = bdrv_find_format(format);
2196 if (!drv) {
2197 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2198 return;
2202 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR, errp)) {
2203 return;
2206 flags = bs->open_flags | BDRV_O_RDWR;
2207 source = bs->backing_hd;
2208 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2209 sync = MIRROR_SYNC_MODE_FULL;
2211 if (sync == MIRROR_SYNC_MODE_NONE) {
2212 source = bs;
2215 size = bdrv_getlength(bs);
2216 if (size < 0) {
2217 error_setg_errno(errp, -size, "bdrv_getlength failed");
2218 return;
2221 if (has_replaces) {
2222 BlockDriverState *to_replace_bs;
2224 if (!has_node_name) {
2225 error_setg(errp, "a node-name must be provided when replacing a"
2226 " named node of the graph");
2227 return;
2230 to_replace_bs = check_to_replace_node(replaces, &local_err);
2232 if (!to_replace_bs) {
2233 error_propagate(errp, local_err);
2234 return;
2237 if (size != bdrv_getlength(to_replace_bs)) {
2238 error_setg(errp, "cannot replace image with a mirror image of "
2239 "different size");
2240 return;
2244 if ((sync == MIRROR_SYNC_MODE_FULL || !source)
2245 && mode != NEW_IMAGE_MODE_EXISTING)
2247 /* create new image w/o backing file */
2248 assert(format && drv);
2249 bdrv_img_create(target, format,
2250 NULL, NULL, NULL, size, flags, &local_err, false);
2251 } else {
2252 switch (mode) {
2253 case NEW_IMAGE_MODE_EXISTING:
2254 break;
2255 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2256 /* create new image with backing file */
2257 bdrv_img_create(target, format,
2258 source->filename,
2259 source->drv->format_name,
2260 NULL, size, flags, &local_err, false);
2261 break;
2262 default:
2263 abort();
2267 if (local_err) {
2268 error_propagate(errp, local_err);
2269 return;
2272 if (has_node_name) {
2273 options = qdict_new();
2274 qdict_put(options, "node-name", qstring_from_str(node_name));
2277 /* Mirroring takes care of copy-on-write using the source's backing
2278 * file.
2280 target_bs = NULL;
2281 ret = bdrv_open(&target_bs, target, NULL, options,
2282 flags | BDRV_O_NO_BACKING, drv, &local_err);
2283 if (ret < 0) {
2284 error_propagate(errp, local_err);
2285 return;
2288 /* pass the node name to replace to mirror start since it's loose coupling
2289 * and will allow to check whether the node still exist at mirror completion
2291 mirror_start(bs, target_bs,
2292 has_replaces ? replaces : NULL,
2293 speed, granularity, buf_size, sync,
2294 on_source_error, on_target_error,
2295 block_job_cb, bs, &local_err);
2296 if (local_err != NULL) {
2297 bdrv_unref(target_bs);
2298 error_propagate(errp, local_err);
2299 return;
2303 static BlockJob *find_block_job(const char *device)
2305 BlockDriverState *bs;
2307 bs = bdrv_find(device);
2308 if (!bs || !bs->job) {
2309 return NULL;
2311 return bs->job;
2314 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2316 BlockJob *job = find_block_job(device);
2318 if (!job) {
2319 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2320 return;
2323 block_job_set_speed(job, speed, errp);
2326 void qmp_block_job_cancel(const char *device,
2327 bool has_force, bool force, Error **errp)
2329 BlockJob *job = find_block_job(device);
2331 if (!has_force) {
2332 force = false;
2335 if (!job) {
2336 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2337 return;
2339 if (job->paused && !force) {
2340 error_setg(errp, "The block job for device '%s' is currently paused",
2341 device);
2342 return;
2345 trace_qmp_block_job_cancel(job);
2346 block_job_cancel(job);
2349 void qmp_block_job_pause(const char *device, Error **errp)
2351 BlockJob *job = find_block_job(device);
2353 if (!job) {
2354 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2355 return;
2358 trace_qmp_block_job_pause(job);
2359 block_job_pause(job);
2362 void qmp_block_job_resume(const char *device, Error **errp)
2364 BlockJob *job = find_block_job(device);
2366 if (!job) {
2367 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2368 return;
2371 trace_qmp_block_job_resume(job);
2372 block_job_resume(job);
2375 void qmp_block_job_complete(const char *device, Error **errp)
2377 BlockJob *job = find_block_job(device);
2379 if (!job) {
2380 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2381 return;
2384 trace_qmp_block_job_complete(job);
2385 block_job_complete(job, errp);
2388 void qmp_change_backing_file(const char *device,
2389 const char *image_node_name,
2390 const char *backing_file,
2391 Error **errp)
2393 BlockDriverState *bs = NULL;
2394 BlockDriverState *image_bs = NULL;
2395 Error *local_err = NULL;
2396 bool ro;
2397 int open_flags;
2398 int ret;
2400 /* find the top layer BDS of the chain */
2401 bs = bdrv_find(device);
2402 if (!bs) {
2403 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
2404 return;
2407 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
2408 if (local_err) {
2409 error_propagate(errp, local_err);
2410 return;
2413 if (!image_bs) {
2414 error_setg(errp, "image file not found");
2415 return;
2418 if (bdrv_find_base(image_bs) == image_bs) {
2419 error_setg(errp, "not allowing backing file change on an image "
2420 "without a backing file");
2421 return;
2424 /* even though we are not necessarily operating on bs, we need it to
2425 * determine if block ops are currently prohibited on the chain */
2426 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
2427 return;
2430 /* final sanity check */
2431 if (!bdrv_chain_contains(bs, image_bs)) {
2432 error_setg(errp, "'%s' and image file are not in the same chain",
2433 device);
2434 return;
2437 /* if not r/w, reopen to make r/w */
2438 open_flags = image_bs->open_flags;
2439 ro = bdrv_is_read_only(image_bs);
2441 if (ro) {
2442 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
2443 if (local_err) {
2444 error_propagate(errp, local_err);
2445 return;
2449 ret = bdrv_change_backing_file(image_bs, backing_file,
2450 image_bs->drv ? image_bs->drv->format_name : "");
2452 if (ret < 0) {
2453 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
2454 backing_file);
2455 /* don't exit here, so we can try to restore open flags if
2456 * appropriate */
2459 if (ro) {
2460 bdrv_reopen(image_bs, open_flags, &local_err);
2461 if (local_err) {
2462 error_propagate(errp, local_err); /* will preserve prior errp */
2467 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2469 QmpOutputVisitor *ov = qmp_output_visitor_new();
2470 DriveInfo *dinfo;
2471 QObject *obj;
2472 QDict *qdict;
2473 Error *local_err = NULL;
2475 /* Require an ID in the top level */
2476 if (!options->has_id) {
2477 error_setg(errp, "Block device needs an ID");
2478 goto fail;
2481 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
2482 * cache.direct=false instead of silently switching to aio=threads, except
2483 * when called from drive_new().
2485 * For now, simply forbidding the combination for all drivers will do. */
2486 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2487 bool direct = options->has_cache &&
2488 options->cache->has_direct &&
2489 options->cache->direct;
2490 if (!direct) {
2491 error_setg(errp, "aio=native requires cache.direct=true");
2492 goto fail;
2496 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2497 &options, NULL, &local_err);
2498 if (local_err) {
2499 error_propagate(errp, local_err);
2500 goto fail;
2503 obj = qmp_output_get_qobject(ov);
2504 qdict = qobject_to_qdict(obj);
2506 qdict_flatten(qdict);
2508 dinfo = blockdev_init(NULL, qdict, &local_err);
2509 if (local_err) {
2510 error_propagate(errp, local_err);
2511 goto fail;
2514 if (bdrv_key_required(dinfo->bdrv)) {
2515 drive_del(dinfo);
2516 error_setg(errp, "blockdev-add doesn't support encrypted devices");
2517 goto fail;
2520 fail:
2521 qmp_output_visitor_cleanup(ov);
2524 static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
2526 BlockJobInfoList **prev = opaque;
2527 BlockJob *job = bs->job;
2529 if (job) {
2530 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2531 elem->value = block_job_query(bs->job);
2532 (*prev)->next = elem;
2533 *prev = elem;
2537 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2539 /* Dummy is a fake list element for holding the head pointer */
2540 BlockJobInfoList dummy = {};
2541 BlockJobInfoList *prev = &dummy;
2542 bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
2543 return dummy.next;
2546 QemuOptsList qemu_common_drive_opts = {
2547 .name = "drive",
2548 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
2549 .desc = {
2551 .name = "snapshot",
2552 .type = QEMU_OPT_BOOL,
2553 .help = "enable/disable snapshot mode",
2555 .name = "discard",
2556 .type = QEMU_OPT_STRING,
2557 .help = "discard operation (ignore/off, unmap/on)",
2559 .name = "cache.writeback",
2560 .type = QEMU_OPT_BOOL,
2561 .help = "enables writeback mode for any caches",
2563 .name = "cache.direct",
2564 .type = QEMU_OPT_BOOL,
2565 .help = "enables use of O_DIRECT (bypass the host page cache)",
2567 .name = "cache.no-flush",
2568 .type = QEMU_OPT_BOOL,
2569 .help = "ignore any flush requests for the device",
2571 .name = "aio",
2572 .type = QEMU_OPT_STRING,
2573 .help = "host AIO implementation (threads, native)",
2575 .name = "format",
2576 .type = QEMU_OPT_STRING,
2577 .help = "disk format (raw, qcow2, ...)",
2579 .name = "rerror",
2580 .type = QEMU_OPT_STRING,
2581 .help = "read error action",
2583 .name = "werror",
2584 .type = QEMU_OPT_STRING,
2585 .help = "write error action",
2587 .name = "read-only",
2588 .type = QEMU_OPT_BOOL,
2589 .help = "open drive file as read-only",
2591 .name = "throttling.iops-total",
2592 .type = QEMU_OPT_NUMBER,
2593 .help = "limit total I/O operations per second",
2595 .name = "throttling.iops-read",
2596 .type = QEMU_OPT_NUMBER,
2597 .help = "limit read operations per second",
2599 .name = "throttling.iops-write",
2600 .type = QEMU_OPT_NUMBER,
2601 .help = "limit write operations per second",
2603 .name = "throttling.bps-total",
2604 .type = QEMU_OPT_NUMBER,
2605 .help = "limit total bytes per second",
2607 .name = "throttling.bps-read",
2608 .type = QEMU_OPT_NUMBER,
2609 .help = "limit read bytes per second",
2611 .name = "throttling.bps-write",
2612 .type = QEMU_OPT_NUMBER,
2613 .help = "limit write bytes per second",
2615 .name = "throttling.iops-total-max",
2616 .type = QEMU_OPT_NUMBER,
2617 .help = "I/O operations burst",
2619 .name = "throttling.iops-read-max",
2620 .type = QEMU_OPT_NUMBER,
2621 .help = "I/O operations read burst",
2623 .name = "throttling.iops-write-max",
2624 .type = QEMU_OPT_NUMBER,
2625 .help = "I/O operations write burst",
2627 .name = "throttling.bps-total-max",
2628 .type = QEMU_OPT_NUMBER,
2629 .help = "total bytes burst",
2631 .name = "throttling.bps-read-max",
2632 .type = QEMU_OPT_NUMBER,
2633 .help = "total bytes read burst",
2635 .name = "throttling.bps-write-max",
2636 .type = QEMU_OPT_NUMBER,
2637 .help = "total bytes write burst",
2639 .name = "throttling.iops-size",
2640 .type = QEMU_OPT_NUMBER,
2641 .help = "when limiting by iops max size of an I/O in bytes",
2643 .name = "copy-on-read",
2644 .type = QEMU_OPT_BOOL,
2645 .help = "copy read data from backing file into image file",
2647 .name = "detect-zeroes",
2648 .type = QEMU_OPT_STRING,
2649 .help = "try to optimize zero writes (off, on, unmap)",
2651 { /* end of list */ }
2655 QemuOptsList qemu_drive_opts = {
2656 .name = "drive",
2657 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2658 .desc = {
2660 * no elements => accept any params
2661 * validation will happen later
2663 { /* end of list */ }