block: Allow "driver" option on the top level
[qemu/kevin.git] / blockdev.c
blob8ff8ed325ae14b157bc1c2083137f88e190c7105
1 /*
2 * QEMU host block devices
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * This work is licensed under the terms of the GNU GPL, version 2 or
7 * later. See the COPYING file in the top-level directory.
9 * This file incorporates work covered by the following copyright and
10 * permission notice:
12 * Copyright (c) 2003-2008 Fabrice Bellard
14 * Permission is hereby granted, free of charge, to any person obtaining a copy
15 * of this software and associated documentation files (the "Software"), to deal
16 * in the Software without restriction, including without limitation the rights
17 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 * copies of the Software, and to permit persons to whom the Software is
19 * furnished to do so, subject to the following conditions:
21 * The above copyright notice and this permission notice shall be included in
22 * all copies or substantial portions of the Software.
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 * THE SOFTWARE.
33 #include "sysemu/blockdev.h"
34 #include "hw/block/block.h"
35 #include "block/blockjob.h"
36 #include "monitor/monitor.h"
37 #include "qapi/qmp/qerror.h"
38 #include "qemu/option.h"
39 #include "qemu/config-file.h"
40 #include "qapi/qmp/types.h"
41 #include "sysemu/sysemu.h"
42 #include "block/block_int.h"
43 #include "qmp-commands.h"
44 #include "trace.h"
45 #include "sysemu/arch_init.h"
47 static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
48 extern QemuOptsList qemu_common_drive_opts;
50 static const char *const if_name[IF_COUNT] = {
51 [IF_NONE] = "none",
52 [IF_IDE] = "ide",
53 [IF_SCSI] = "scsi",
54 [IF_FLOPPY] = "floppy",
55 [IF_PFLASH] = "pflash",
56 [IF_MTD] = "mtd",
57 [IF_SD] = "sd",
58 [IF_VIRTIO] = "virtio",
59 [IF_XEN] = "xen",
62 static const int if_max_devs[IF_COUNT] = {
64 * Do not change these numbers! They govern how drive option
65 * index maps to unit and bus. That mapping is ABI.
67 * All controllers used to imlement if=T drives need to support
68 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
69 * Otherwise, some index values map to "impossible" bus, unit
70 * values.
72 * For instance, if you change [IF_SCSI] to 255, -drive
73 * if=scsi,index=12 no longer means bus=1,unit=5, but
74 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
75 * the drive can't be set up. Regression.
77 [IF_IDE] = 2,
78 [IF_SCSI] = 7,
82 * We automatically delete the drive when a device using it gets
83 * unplugged. Questionable feature, but we can't just drop it.
84 * Device models call blockdev_mark_auto_del() to schedule the
85 * automatic deletion, and generic qdev code calls blockdev_auto_del()
86 * when deletion is actually safe.
88 void blockdev_mark_auto_del(BlockDriverState *bs)
90 DriveInfo *dinfo = drive_get_by_blockdev(bs);
92 if (bs->job) {
93 block_job_cancel(bs->job);
95 if (dinfo) {
96 dinfo->auto_del = 1;
100 void blockdev_auto_del(BlockDriverState *bs)
102 DriveInfo *dinfo = drive_get_by_blockdev(bs);
104 if (dinfo && dinfo->auto_del) {
105 drive_put_ref(dinfo);
109 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
111 int max_devs = if_max_devs[type];
112 return max_devs ? index / max_devs : 0;
115 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
117 int max_devs = if_max_devs[type];
118 return max_devs ? index % max_devs : index;
121 QemuOpts *drive_def(const char *optstr)
123 return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
126 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
127 const char *optstr)
129 QemuOpts *opts;
130 char buf[32];
132 opts = drive_def(optstr);
133 if (!opts) {
134 return NULL;
136 if (type != IF_DEFAULT) {
137 qemu_opt_set(opts, "if", if_name[type]);
139 if (index >= 0) {
140 snprintf(buf, sizeof(buf), "%d", index);
141 qemu_opt_set(opts, "index", buf);
143 if (file)
144 qemu_opt_set(opts, "file", file);
145 return opts;
148 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
150 DriveInfo *dinfo;
152 /* seek interface, bus and unit */
154 QTAILQ_FOREACH(dinfo, &drives, next) {
155 if (dinfo->type == type &&
156 dinfo->bus == bus &&
157 dinfo->unit == unit)
158 return dinfo;
161 return NULL;
164 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
166 return drive_get(type,
167 drive_index_to_bus_id(type, index),
168 drive_index_to_unit_id(type, index));
171 int drive_get_max_bus(BlockInterfaceType type)
173 int max_bus;
174 DriveInfo *dinfo;
176 max_bus = -1;
177 QTAILQ_FOREACH(dinfo, &drives, next) {
178 if(dinfo->type == type &&
179 dinfo->bus > max_bus)
180 max_bus = dinfo->bus;
182 return max_bus;
185 /* Get a block device. This should only be used for single-drive devices
186 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
187 appropriate bus. */
188 DriveInfo *drive_get_next(BlockInterfaceType type)
190 static int next_block_unit[IF_COUNT];
192 return drive_get(type, 0, next_block_unit[type]++);
195 DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
197 DriveInfo *dinfo;
199 QTAILQ_FOREACH(dinfo, &drives, next) {
200 if (dinfo->bdrv == bs) {
201 return dinfo;
204 return NULL;
207 static void bdrv_format_print(void *opaque, const char *name)
209 error_printf(" %s", name);
212 static void drive_uninit(DriveInfo *dinfo)
214 qemu_opts_del(dinfo->opts);
215 bdrv_delete(dinfo->bdrv);
216 g_free(dinfo->id);
217 QTAILQ_REMOVE(&drives, dinfo, next);
218 g_free(dinfo->serial);
219 g_free(dinfo);
222 void drive_put_ref(DriveInfo *dinfo)
224 assert(dinfo->refcount);
225 if (--dinfo->refcount == 0) {
226 drive_uninit(dinfo);
230 void drive_get_ref(DriveInfo *dinfo)
232 dinfo->refcount++;
235 typedef struct {
236 QEMUBH *bh;
237 DriveInfo *dinfo;
238 } DrivePutRefBH;
240 static void drive_put_ref_bh(void *opaque)
242 DrivePutRefBH *s = opaque;
244 drive_put_ref(s->dinfo);
245 qemu_bh_delete(s->bh);
246 g_free(s);
250 * Release a drive reference in a BH
252 * It is not possible to use drive_put_ref() from a callback function when the
253 * callers still need the drive. In such cases we schedule a BH to release the
254 * reference.
256 static void drive_put_ref_bh_schedule(DriveInfo *dinfo)
258 DrivePutRefBH *s;
260 s = g_new(DrivePutRefBH, 1);
261 s->bh = qemu_bh_new(drive_put_ref_bh, s);
262 s->dinfo = dinfo;
263 qemu_bh_schedule(s->bh);
266 static int parse_block_error_action(const char *buf, bool is_read)
268 if (!strcmp(buf, "ignore")) {
269 return BLOCKDEV_ON_ERROR_IGNORE;
270 } else if (!is_read && !strcmp(buf, "enospc")) {
271 return BLOCKDEV_ON_ERROR_ENOSPC;
272 } else if (!strcmp(buf, "stop")) {
273 return BLOCKDEV_ON_ERROR_STOP;
274 } else if (!strcmp(buf, "report")) {
275 return BLOCKDEV_ON_ERROR_REPORT;
276 } else {
277 error_report("'%s' invalid %s error action",
278 buf, is_read ? "read" : "write");
279 return -1;
283 static bool do_check_io_limits(BlockIOLimit *io_limits, Error **errp)
285 bool bps_flag;
286 bool iops_flag;
288 assert(io_limits);
290 bps_flag = (io_limits->bps[BLOCK_IO_LIMIT_TOTAL] != 0)
291 && ((io_limits->bps[BLOCK_IO_LIMIT_READ] != 0)
292 || (io_limits->bps[BLOCK_IO_LIMIT_WRITE] != 0));
293 iops_flag = (io_limits->iops[BLOCK_IO_LIMIT_TOTAL] != 0)
294 && ((io_limits->iops[BLOCK_IO_LIMIT_READ] != 0)
295 || (io_limits->iops[BLOCK_IO_LIMIT_WRITE] != 0));
296 if (bps_flag || iops_flag) {
297 error_setg(errp, "bps(iops) and bps_rd/bps_wr(iops_rd/iops_wr) "
298 "cannot be used at the same time");
299 return false;
302 if (io_limits->bps[BLOCK_IO_LIMIT_TOTAL] < 0 ||
303 io_limits->bps[BLOCK_IO_LIMIT_WRITE] < 0 ||
304 io_limits->bps[BLOCK_IO_LIMIT_READ] < 0 ||
305 io_limits->iops[BLOCK_IO_LIMIT_TOTAL] < 0 ||
306 io_limits->iops[BLOCK_IO_LIMIT_WRITE] < 0 ||
307 io_limits->iops[BLOCK_IO_LIMIT_READ] < 0) {
308 error_setg(errp, "bps and iops values must be 0 or greater");
309 return false;
312 return true;
315 DriveInfo *drive_init(QemuOpts *all_opts, BlockInterfaceType block_default_type)
317 const char *buf;
318 const char *file = NULL;
319 const char *serial;
320 const char *mediastr = "";
321 BlockInterfaceType type;
322 enum { MEDIA_DISK, MEDIA_CDROM } media;
323 int bus_id, unit_id;
324 int cyls, heads, secs, translation;
325 int max_devs;
326 int index;
327 int ro = 0;
328 int bdrv_flags = 0;
329 int on_read_error, on_write_error;
330 const char *devaddr;
331 DriveInfo *dinfo;
332 BlockIOLimit io_limits;
333 int snapshot = 0;
334 bool copy_on_read;
335 int ret;
336 Error *error = NULL;
337 QemuOpts *opts;
338 QDict *bs_opts;
339 const char *id;
340 bool has_driver_specific_opts;
342 translation = BIOS_ATA_TRANSLATION_AUTO;
343 media = MEDIA_DISK;
345 /* Check common options by copying from all_opts to opts, all other options
346 * are stored in bs_opts. */
347 id = qemu_opts_id(all_opts);
348 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
349 if (error_is_set(&error)) {
350 qerror_report_err(error);
351 error_free(error);
352 return NULL;
355 bs_opts = qdict_new();
356 qemu_opts_to_qdict(all_opts, bs_opts);
357 qemu_opts_absorb_qdict(opts, bs_opts, &error);
358 if (error_is_set(&error)) {
359 qerror_report_err(error);
360 error_free(error);
361 return NULL;
364 if (id) {
365 qdict_del(bs_opts, "id");
368 has_driver_specific_opts = !!qdict_size(bs_opts);
370 /* extract parameters */
371 bus_id = qemu_opt_get_number(opts, "bus", 0);
372 unit_id = qemu_opt_get_number(opts, "unit", -1);
373 index = qemu_opt_get_number(opts, "index", -1);
375 cyls = qemu_opt_get_number(opts, "cyls", 0);
376 heads = qemu_opt_get_number(opts, "heads", 0);
377 secs = qemu_opt_get_number(opts, "secs", 0);
379 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
380 ro = qemu_opt_get_bool(opts, "readonly", 0);
381 copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
383 file = qemu_opt_get(opts, "file");
384 serial = qemu_opt_get(opts, "serial");
386 if ((buf = qemu_opt_get(opts, "if")) != NULL) {
387 for (type = 0; type < IF_COUNT && strcmp(buf, if_name[type]); type++)
389 if (type == IF_COUNT) {
390 error_report("unsupported bus type '%s'", buf);
391 return NULL;
393 } else {
394 type = block_default_type;
397 max_devs = if_max_devs[type];
399 if (cyls || heads || secs) {
400 if (cyls < 1) {
401 error_report("invalid physical cyls number");
402 return NULL;
404 if (heads < 1) {
405 error_report("invalid physical heads number");
406 return NULL;
408 if (secs < 1) {
409 error_report("invalid physical secs number");
410 return NULL;
414 if ((buf = qemu_opt_get(opts, "trans")) != NULL) {
415 if (!cyls) {
416 error_report("'%s' trans must be used with cyls, heads and secs",
417 buf);
418 return NULL;
420 if (!strcmp(buf, "none"))
421 translation = BIOS_ATA_TRANSLATION_NONE;
422 else if (!strcmp(buf, "lba"))
423 translation = BIOS_ATA_TRANSLATION_LBA;
424 else if (!strcmp(buf, "auto"))
425 translation = BIOS_ATA_TRANSLATION_AUTO;
426 else {
427 error_report("'%s' invalid translation type", buf);
428 return NULL;
432 if ((buf = qemu_opt_get(opts, "media")) != NULL) {
433 if (!strcmp(buf, "disk")) {
434 media = MEDIA_DISK;
435 } else if (!strcmp(buf, "cdrom")) {
436 if (cyls || secs || heads) {
437 error_report("CHS can't be set with media=%s", buf);
438 return NULL;
440 media = MEDIA_CDROM;
441 } else {
442 error_report("'%s' invalid media", buf);
443 return NULL;
447 if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
448 if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
449 error_report("invalid discard option");
450 return NULL;
454 bdrv_flags |= BDRV_O_CACHE_WB;
455 if ((buf = qemu_opt_get(opts, "cache")) != NULL) {
456 if (bdrv_parse_cache_flags(buf, &bdrv_flags) != 0) {
457 error_report("invalid cache option");
458 return NULL;
462 #ifdef CONFIG_LINUX_AIO
463 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
464 if (!strcmp(buf, "native")) {
465 bdrv_flags |= BDRV_O_NATIVE_AIO;
466 } else if (!strcmp(buf, "threads")) {
467 /* this is the default */
468 } else {
469 error_report("invalid aio option");
470 return NULL;
473 #endif
475 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
476 if (is_help_option(buf)) {
477 error_printf("Supported formats:");
478 bdrv_iterate_format(bdrv_format_print, NULL);
479 error_printf("\n");
480 return NULL;
483 qdict_put(bs_opts, "driver", qstring_from_str(buf));
486 /* disk I/O throttling */
487 io_limits.bps[BLOCK_IO_LIMIT_TOTAL] =
488 qemu_opt_get_number(opts, "bps", 0);
489 io_limits.bps[BLOCK_IO_LIMIT_READ] =
490 qemu_opt_get_number(opts, "bps_rd", 0);
491 io_limits.bps[BLOCK_IO_LIMIT_WRITE] =
492 qemu_opt_get_number(opts, "bps_wr", 0);
493 io_limits.iops[BLOCK_IO_LIMIT_TOTAL] =
494 qemu_opt_get_number(opts, "iops", 0);
495 io_limits.iops[BLOCK_IO_LIMIT_READ] =
496 qemu_opt_get_number(opts, "iops_rd", 0);
497 io_limits.iops[BLOCK_IO_LIMIT_WRITE] =
498 qemu_opt_get_number(opts, "iops_wr", 0);
500 if (!do_check_io_limits(&io_limits, &error)) {
501 error_report("%s", error_get_pretty(error));
502 error_free(error);
503 return NULL;
506 if (qemu_opt_get(opts, "boot") != NULL) {
507 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
508 "ignored. Future versions will reject this parameter. Please "
509 "update your scripts.\n");
512 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
513 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
514 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) {
515 error_report("werror is not supported by this bus type");
516 return NULL;
519 on_write_error = parse_block_error_action(buf, 0);
520 if (on_write_error < 0) {
521 return NULL;
525 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
526 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
527 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI && type != IF_NONE) {
528 error_report("rerror is not supported by this bus type");
529 return NULL;
532 on_read_error = parse_block_error_action(buf, 1);
533 if (on_read_error < 0) {
534 return NULL;
538 if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {
539 if (type != IF_VIRTIO) {
540 error_report("addr is not supported by this bus type");
541 return NULL;
545 /* compute bus and unit according index */
547 if (index != -1) {
548 if (bus_id != 0 || unit_id != -1) {
549 error_report("index cannot be used with bus and unit");
550 return NULL;
552 bus_id = drive_index_to_bus_id(type, index);
553 unit_id = drive_index_to_unit_id(type, index);
556 /* if user doesn't specify a unit_id,
557 * try to find the first free
560 if (unit_id == -1) {
561 unit_id = 0;
562 while (drive_get(type, bus_id, unit_id) != NULL) {
563 unit_id++;
564 if (max_devs && unit_id >= max_devs) {
565 unit_id -= max_devs;
566 bus_id++;
571 /* check unit id */
573 if (max_devs && unit_id >= max_devs) {
574 error_report("unit %d too big (max is %d)",
575 unit_id, max_devs - 1);
576 return NULL;
580 * catch multiple definitions
583 if (drive_get(type, bus_id, unit_id) != NULL) {
584 error_report("drive with bus=%d, unit=%d (index=%d) exists",
585 bus_id, unit_id, index);
586 return NULL;
589 /* init */
591 dinfo = g_malloc0(sizeof(*dinfo));
592 if ((buf = qemu_opts_id(opts)) != NULL) {
593 dinfo->id = g_strdup(buf);
594 } else {
595 /* no id supplied -> create one */
596 dinfo->id = g_malloc0(32);
597 if (type == IF_IDE || type == IF_SCSI)
598 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
599 if (max_devs)
600 snprintf(dinfo->id, 32, "%s%i%s%i",
601 if_name[type], bus_id, mediastr, unit_id);
602 else
603 snprintf(dinfo->id, 32, "%s%s%i",
604 if_name[type], mediastr, unit_id);
606 dinfo->bdrv = bdrv_new(dinfo->id);
607 dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
608 dinfo->bdrv->read_only = ro;
609 dinfo->devaddr = devaddr;
610 dinfo->type = type;
611 dinfo->bus = bus_id;
612 dinfo->unit = unit_id;
613 dinfo->cyls = cyls;
614 dinfo->heads = heads;
615 dinfo->secs = secs;
616 dinfo->trans = translation;
617 dinfo->opts = all_opts;
618 dinfo->refcount = 1;
619 if (serial != NULL) {
620 dinfo->serial = g_strdup(serial);
622 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
624 bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);
626 /* disk I/O throttling */
627 bdrv_set_io_limits(dinfo->bdrv, &io_limits);
629 switch(type) {
630 case IF_IDE:
631 case IF_SCSI:
632 case IF_XEN:
633 case IF_NONE:
634 dinfo->media_cd = media == MEDIA_CDROM;
635 break;
636 case IF_SD:
637 case IF_FLOPPY:
638 case IF_PFLASH:
639 case IF_MTD:
640 break;
641 case IF_VIRTIO:
643 /* add virtio block device */
644 QemuOpts *devopts;
645 devopts = qemu_opts_create_nofail(qemu_find_opts("device"));
646 if (arch_type == QEMU_ARCH_S390X) {
647 qemu_opt_set(devopts, "driver", "virtio-blk-s390");
648 } else {
649 qemu_opt_set(devopts, "driver", "virtio-blk-pci");
651 qemu_opt_set(devopts, "drive", dinfo->id);
652 if (devaddr)
653 qemu_opt_set(devopts, "addr", devaddr);
654 break;
656 default:
657 abort();
659 if (!file || !*file) {
660 if (has_driver_specific_opts) {
661 file = NULL;
662 } else {
663 return dinfo;
666 if (snapshot) {
667 /* always use cache=unsafe with snapshot */
668 bdrv_flags &= ~BDRV_O_CACHE_MASK;
669 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
672 if (copy_on_read) {
673 bdrv_flags |= BDRV_O_COPY_ON_READ;
676 if (runstate_check(RUN_STATE_INMIGRATE)) {
677 bdrv_flags |= BDRV_O_INCOMING;
680 if (media == MEDIA_CDROM) {
681 /* CDROM is fine for any interface, don't check. */
682 ro = 1;
683 } else if (ro == 1) {
684 if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY &&
685 type != IF_NONE && type != IF_PFLASH) {
686 error_report("readonly not supported by this bus type");
687 goto err;
691 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
693 if (ro && copy_on_read) {
694 error_report("warning: disabling copy_on_read on readonly drive");
697 QINCREF(bs_opts);
698 ret = bdrv_open(dinfo->bdrv, file, bs_opts, bdrv_flags, NULL);
700 if (ret < 0) {
701 if (ret == -EMEDIUMTYPE) {
702 error_report("could not open disk image %s: not in %s format",
703 file ?: dinfo->id, qdict_get_str(bs_opts, "driver"));
704 } else {
705 error_report("could not open disk image %s: %s",
706 file ?: dinfo->id, strerror(-ret));
708 goto err;
711 if (bdrv_key_required(dinfo->bdrv))
712 autostart = 0;
714 QDECREF(bs_opts);
715 qemu_opts_del(opts);
717 return dinfo;
719 err:
720 qemu_opts_del(opts);
721 QDECREF(bs_opts);
722 bdrv_delete(dinfo->bdrv);
723 g_free(dinfo->id);
724 QTAILQ_REMOVE(&drives, dinfo, next);
725 g_free(dinfo);
726 return NULL;
729 void do_commit(Monitor *mon, const QDict *qdict)
731 const char *device = qdict_get_str(qdict, "device");
732 BlockDriverState *bs;
733 int ret;
735 if (!strcmp(device, "all")) {
736 ret = bdrv_commit_all();
737 } else {
738 bs = bdrv_find(device);
739 if (!bs) {
740 monitor_printf(mon, "Device '%s' not found\n", device);
741 return;
743 ret = bdrv_commit(bs);
745 if (ret < 0) {
746 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
747 strerror(-ret));
751 static void blockdev_do_action(int kind, void *data, Error **errp)
753 TransactionAction action;
754 TransactionActionList list;
756 action.kind = kind;
757 action.data = data;
758 list.value = &action;
759 list.next = NULL;
760 qmp_transaction(&list, errp);
763 void qmp_blockdev_snapshot_sync(const char *device, const char *snapshot_file,
764 bool has_format, const char *format,
765 bool has_mode, enum NewImageMode mode,
766 Error **errp)
768 BlockdevSnapshot snapshot = {
769 .device = (char *) device,
770 .snapshot_file = (char *) snapshot_file,
771 .has_format = has_format,
772 .format = (char *) format,
773 .has_mode = has_mode,
774 .mode = mode,
776 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
777 &snapshot, errp);
781 /* New and old BlockDriverState structs for group snapshots */
783 typedef struct BlkTransactionState BlkTransactionState;
785 /* Only prepare() may fail. In a single transaction, only one of commit() or
786 abort() will be called, clean() will always be called if it present. */
787 typedef struct BdrvActionOps {
788 /* Size of state struct, in bytes. */
789 size_t instance_size;
790 /* Prepare the work, must NOT be NULL. */
791 void (*prepare)(BlkTransactionState *common, Error **errp);
792 /* Commit the changes, can be NULL. */
793 void (*commit)(BlkTransactionState *common);
794 /* Abort the changes on fail, can be NULL. */
795 void (*abort)(BlkTransactionState *common);
796 /* Clean up resource in the end, can be NULL. */
797 void (*clean)(BlkTransactionState *common);
798 } BdrvActionOps;
801 * This structure must be arranged as first member in child type, assuming
802 * that compiler will also arrange it to the same address with parent instance.
803 * Later it will be used in free().
805 struct BlkTransactionState {
806 TransactionAction *action;
807 const BdrvActionOps *ops;
808 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
811 /* external snapshot private data */
812 typedef struct ExternalSnapshotState {
813 BlkTransactionState common;
814 BlockDriverState *old_bs;
815 BlockDriverState *new_bs;
816 } ExternalSnapshotState;
818 static void external_snapshot_prepare(BlkTransactionState *common,
819 Error **errp)
821 BlockDriver *drv;
822 int flags, ret;
823 Error *local_err = NULL;
824 const char *device;
825 const char *new_image_file;
826 const char *format = "qcow2";
827 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
828 ExternalSnapshotState *state =
829 DO_UPCAST(ExternalSnapshotState, common, common);
830 TransactionAction *action = common->action;
832 /* get parameters */
833 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
835 device = action->blockdev_snapshot_sync->device;
836 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
837 if (action->blockdev_snapshot_sync->has_format) {
838 format = action->blockdev_snapshot_sync->format;
840 if (action->blockdev_snapshot_sync->has_mode) {
841 mode = action->blockdev_snapshot_sync->mode;
844 /* start processing */
845 drv = bdrv_find_format(format);
846 if (!drv) {
847 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
848 return;
851 state->old_bs = bdrv_find(device);
852 if (!state->old_bs) {
853 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
854 return;
857 if (!bdrv_is_inserted(state->old_bs)) {
858 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
859 return;
862 if (bdrv_in_use(state->old_bs)) {
863 error_set(errp, QERR_DEVICE_IN_USE, device);
864 return;
867 if (!bdrv_is_read_only(state->old_bs)) {
868 if (bdrv_flush(state->old_bs)) {
869 error_set(errp, QERR_IO_ERROR);
870 return;
874 flags = state->old_bs->open_flags;
876 /* create new image w/backing file */
877 if (mode != NEW_IMAGE_MODE_EXISTING) {
878 bdrv_img_create(new_image_file, format,
879 state->old_bs->filename,
880 state->old_bs->drv->format_name,
881 NULL, -1, flags, &local_err, false);
882 if (error_is_set(&local_err)) {
883 error_propagate(errp, local_err);
884 return;
888 /* We will manually add the backing_hd field to the bs later */
889 state->new_bs = bdrv_new("");
890 /* TODO Inherit bs->options or only take explicit options with an
891 * extended QMP command? */
892 ret = bdrv_open(state->new_bs, new_image_file, NULL,
893 flags | BDRV_O_NO_BACKING, drv);
894 if (ret != 0) {
895 error_setg_file_open(errp, -ret, new_image_file);
899 static void external_snapshot_commit(BlkTransactionState *common)
901 ExternalSnapshotState *state =
902 DO_UPCAST(ExternalSnapshotState, common, common);
904 /* This removes our old bs and adds the new bs */
905 bdrv_append(state->new_bs, state->old_bs);
906 /* We don't need (or want) to use the transactional
907 * bdrv_reopen_multiple() across all the entries at once, because we
908 * don't want to abort all of them if one of them fails the reopen */
909 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
910 NULL);
913 static void external_snapshot_abort(BlkTransactionState *common)
915 ExternalSnapshotState *state =
916 DO_UPCAST(ExternalSnapshotState, common, common);
917 if (state->new_bs) {
918 bdrv_delete(state->new_bs);
922 typedef struct DriveBackupState {
923 BlkTransactionState common;
924 BlockDriverState *bs;
925 BlockJob *job;
926 } DriveBackupState;
928 static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
930 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
931 DriveBackup *backup;
932 Error *local_err = NULL;
934 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
935 backup = common->action->drive_backup;
937 qmp_drive_backup(backup->device, backup->target,
938 backup->has_format, backup->format,
939 backup->sync,
940 backup->has_mode, backup->mode,
941 backup->has_speed, backup->speed,
942 backup->has_on_source_error, backup->on_source_error,
943 backup->has_on_target_error, backup->on_target_error,
944 &local_err);
945 if (error_is_set(&local_err)) {
946 error_propagate(errp, local_err);
947 state->bs = NULL;
948 state->job = NULL;
949 return;
952 state->bs = bdrv_find(backup->device);
953 state->job = state->bs->job;
956 static void drive_backup_abort(BlkTransactionState *common)
958 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
959 BlockDriverState *bs = state->bs;
961 /* Only cancel if it's the job we started */
962 if (bs && bs->job && bs->job == state->job) {
963 block_job_cancel_sync(bs->job);
967 static void abort_prepare(BlkTransactionState *common, Error **errp)
969 error_setg(errp, "Transaction aborted using Abort action");
972 static void abort_commit(BlkTransactionState *common)
974 assert(false); /* this action never succeeds */
977 static const BdrvActionOps actions[] = {
978 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
979 .instance_size = sizeof(ExternalSnapshotState),
980 .prepare = external_snapshot_prepare,
981 .commit = external_snapshot_commit,
982 .abort = external_snapshot_abort,
984 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
985 .instance_size = sizeof(DriveBackupState),
986 .prepare = drive_backup_prepare,
987 .abort = drive_backup_abort,
989 [TRANSACTION_ACTION_KIND_ABORT] = {
990 .instance_size = sizeof(BlkTransactionState),
991 .prepare = abort_prepare,
992 .commit = abort_commit,
997 * 'Atomic' group snapshots. The snapshots are taken as a set, and if any fail
998 * then we do not pivot any of the devices in the group, and abandon the
999 * snapshots
1001 void qmp_transaction(TransactionActionList *dev_list, Error **errp)
1003 TransactionActionList *dev_entry = dev_list;
1004 BlkTransactionState *state, *next;
1005 Error *local_err = NULL;
1007 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
1008 QSIMPLEQ_INIT(&snap_bdrv_states);
1010 /* drain all i/o before any snapshots */
1011 bdrv_drain_all();
1013 /* We don't do anything in this loop that commits us to the snapshot */
1014 while (NULL != dev_entry) {
1015 TransactionAction *dev_info = NULL;
1016 const BdrvActionOps *ops;
1018 dev_info = dev_entry->value;
1019 dev_entry = dev_entry->next;
1021 assert(dev_info->kind < ARRAY_SIZE(actions));
1023 ops = &actions[dev_info->kind];
1024 state = g_malloc0(ops->instance_size);
1025 state->ops = ops;
1026 state->action = dev_info;
1027 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
1029 state->ops->prepare(state, &local_err);
1030 if (error_is_set(&local_err)) {
1031 error_propagate(errp, local_err);
1032 goto delete_and_fail;
1036 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1037 if (state->ops->commit) {
1038 state->ops->commit(state);
1042 /* success */
1043 goto exit;
1045 delete_and_fail:
1047 * failure, and it is all-or-none; abandon each new bs, and keep using
1048 * the original bs for all images
1050 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1051 if (state->ops->abort) {
1052 state->ops->abort(state);
1055 exit:
1056 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1057 if (state->ops->clean) {
1058 state->ops->clean(state);
1060 g_free(state);
1065 static void eject_device(BlockDriverState *bs, int force, Error **errp)
1067 if (bdrv_in_use(bs)) {
1068 error_set(errp, QERR_DEVICE_IN_USE, bdrv_get_device_name(bs));
1069 return;
1071 if (!bdrv_dev_has_removable_media(bs)) {
1072 error_set(errp, QERR_DEVICE_NOT_REMOVABLE, bdrv_get_device_name(bs));
1073 return;
1076 if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
1077 bdrv_dev_eject_request(bs, force);
1078 if (!force) {
1079 error_set(errp, QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
1080 return;
1084 bdrv_close(bs);
1087 void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
1089 BlockDriverState *bs;
1091 bs = bdrv_find(device);
1092 if (!bs) {
1093 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1094 return;
1097 eject_device(bs, force, errp);
1100 void qmp_block_passwd(const char *device, const char *password, Error **errp)
1102 BlockDriverState *bs;
1103 int err;
1105 bs = bdrv_find(device);
1106 if (!bs) {
1107 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1108 return;
1111 err = bdrv_set_key(bs, password);
1112 if (err == -EINVAL) {
1113 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1114 return;
1115 } else if (err < 0) {
1116 error_set(errp, QERR_INVALID_PASSWORD);
1117 return;
1121 static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1122 int bdrv_flags, BlockDriver *drv,
1123 const char *password, Error **errp)
1125 int ret;
1127 ret = bdrv_open(bs, filename, NULL, bdrv_flags, drv);
1128 if (ret < 0) {
1129 error_setg_file_open(errp, -ret, filename);
1130 return;
1133 if (bdrv_key_required(bs)) {
1134 if (password) {
1135 if (bdrv_set_key(bs, password) < 0) {
1136 error_set(errp, QERR_INVALID_PASSWORD);
1138 } else {
1139 error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1140 bdrv_get_encrypted_filename(bs));
1142 } else if (password) {
1143 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1147 void qmp_change_blockdev(const char *device, const char *filename,
1148 bool has_format, const char *format, Error **errp)
1150 BlockDriverState *bs;
1151 BlockDriver *drv = NULL;
1152 int bdrv_flags;
1153 Error *err = NULL;
1155 bs = bdrv_find(device);
1156 if (!bs) {
1157 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1158 return;
1161 if (format) {
1162 drv = bdrv_find_whitelisted_format(format, bs->read_only);
1163 if (!drv) {
1164 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1165 return;
1169 eject_device(bs, 0, &err);
1170 if (error_is_set(&err)) {
1171 error_propagate(errp, err);
1172 return;
1175 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
1176 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
1178 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
1181 /* throttling disk I/O limits */
1182 void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
1183 int64_t bps_wr, int64_t iops, int64_t iops_rd,
1184 int64_t iops_wr, Error **errp)
1186 BlockIOLimit io_limits;
1187 BlockDriverState *bs;
1189 bs = bdrv_find(device);
1190 if (!bs) {
1191 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1192 return;
1195 io_limits.bps[BLOCK_IO_LIMIT_TOTAL] = bps;
1196 io_limits.bps[BLOCK_IO_LIMIT_READ] = bps_rd;
1197 io_limits.bps[BLOCK_IO_LIMIT_WRITE] = bps_wr;
1198 io_limits.iops[BLOCK_IO_LIMIT_TOTAL]= iops;
1199 io_limits.iops[BLOCK_IO_LIMIT_READ] = iops_rd;
1200 io_limits.iops[BLOCK_IO_LIMIT_WRITE]= iops_wr;
1202 if (!do_check_io_limits(&io_limits, errp)) {
1203 return;
1206 bs->io_limits = io_limits;
1208 if (!bs->io_limits_enabled && bdrv_io_limits_enabled(bs)) {
1209 bdrv_io_limits_enable(bs);
1210 } else if (bs->io_limits_enabled && !bdrv_io_limits_enabled(bs)) {
1211 bdrv_io_limits_disable(bs);
1212 } else {
1213 if (bs->block_timer) {
1214 qemu_mod_timer(bs->block_timer, qemu_get_clock_ns(vm_clock));
1219 int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1221 const char *id = qdict_get_str(qdict, "id");
1222 BlockDriverState *bs;
1224 bs = bdrv_find(id);
1225 if (!bs) {
1226 qerror_report(QERR_DEVICE_NOT_FOUND, id);
1227 return -1;
1229 if (bdrv_in_use(bs)) {
1230 qerror_report(QERR_DEVICE_IN_USE, id);
1231 return -1;
1234 /* quiesce block driver; prevent further io */
1235 bdrv_drain_all();
1236 bdrv_flush(bs);
1237 bdrv_close(bs);
1239 /* if we have a device attached to this BlockDriverState
1240 * then we need to make the drive anonymous until the device
1241 * can be removed. If this is a drive with no device backing
1242 * then we can just get rid of the block driver state right here.
1244 if (bdrv_get_attached_dev(bs)) {
1245 bdrv_make_anon(bs);
1247 /* Further I/O must not pause the guest */
1248 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1249 BLOCKDEV_ON_ERROR_REPORT);
1250 } else {
1251 drive_uninit(drive_get_by_blockdev(bs));
1254 return 0;
1257 void qmp_block_resize(const char *device, int64_t size, Error **errp)
1259 BlockDriverState *bs;
1260 int ret;
1262 bs = bdrv_find(device);
1263 if (!bs) {
1264 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1265 return;
1268 if (size < 0) {
1269 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
1270 return;
1273 /* complete all in-flight operations before resizing the device */
1274 bdrv_drain_all();
1276 ret = bdrv_truncate(bs, size);
1277 switch (ret) {
1278 case 0:
1279 break;
1280 case -ENOMEDIUM:
1281 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1282 break;
1283 case -ENOTSUP:
1284 error_set(errp, QERR_UNSUPPORTED);
1285 break;
1286 case -EACCES:
1287 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1288 break;
1289 case -EBUSY:
1290 error_set(errp, QERR_DEVICE_IN_USE, device);
1291 break;
1292 default:
1293 error_setg_errno(errp, -ret, "Could not resize");
1294 break;
1298 static void block_job_cb(void *opaque, int ret)
1300 BlockDriverState *bs = opaque;
1301 QObject *obj;
1303 trace_block_job_cb(bs, bs->job, ret);
1305 assert(bs->job);
1306 obj = qobject_from_block_job(bs->job);
1307 if (ret < 0) {
1308 QDict *dict = qobject_to_qdict(obj);
1309 qdict_put(dict, "error", qstring_from_str(strerror(-ret)));
1312 if (block_job_is_cancelled(bs->job)) {
1313 monitor_protocol_event(QEVENT_BLOCK_JOB_CANCELLED, obj);
1314 } else {
1315 monitor_protocol_event(QEVENT_BLOCK_JOB_COMPLETED, obj);
1317 qobject_decref(obj);
1319 drive_put_ref_bh_schedule(drive_get_by_blockdev(bs));
1322 void qmp_block_stream(const char *device, bool has_base,
1323 const char *base, bool has_speed, int64_t speed,
1324 bool has_on_error, BlockdevOnError on_error,
1325 Error **errp)
1327 BlockDriverState *bs;
1328 BlockDriverState *base_bs = NULL;
1329 Error *local_err = NULL;
1331 if (!has_on_error) {
1332 on_error = BLOCKDEV_ON_ERROR_REPORT;
1335 bs = bdrv_find(device);
1336 if (!bs) {
1337 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1338 return;
1341 if (base) {
1342 base_bs = bdrv_find_backing_image(bs, base);
1343 if (base_bs == NULL) {
1344 error_set(errp, QERR_BASE_NOT_FOUND, base);
1345 return;
1349 stream_start(bs, base_bs, base, has_speed ? speed : 0,
1350 on_error, block_job_cb, bs, &local_err);
1351 if (error_is_set(&local_err)) {
1352 error_propagate(errp, local_err);
1353 return;
1356 /* Grab a reference so hotplug does not delete the BlockDriverState from
1357 * underneath us.
1359 drive_get_ref(drive_get_by_blockdev(bs));
1361 trace_qmp_block_stream(bs, bs->job);
1364 void qmp_block_commit(const char *device,
1365 bool has_base, const char *base, const char *top,
1366 bool has_speed, int64_t speed,
1367 Error **errp)
1369 BlockDriverState *bs;
1370 BlockDriverState *base_bs, *top_bs;
1371 Error *local_err = NULL;
1372 /* This will be part of the QMP command, if/when the
1373 * BlockdevOnError change for blkmirror makes it in
1375 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
1377 /* drain all i/o before commits */
1378 bdrv_drain_all();
1380 bs = bdrv_find(device);
1381 if (!bs) {
1382 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1383 return;
1386 /* default top_bs is the active layer */
1387 top_bs = bs;
1389 if (top) {
1390 if (strcmp(bs->filename, top) != 0) {
1391 top_bs = bdrv_find_backing_image(bs, top);
1395 if (top_bs == NULL) {
1396 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
1397 return;
1400 if (has_base && base) {
1401 base_bs = bdrv_find_backing_image(top_bs, base);
1402 } else {
1403 base_bs = bdrv_find_base(top_bs);
1406 if (base_bs == NULL) {
1407 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
1408 return;
1411 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
1412 &local_err);
1413 if (local_err != NULL) {
1414 error_propagate(errp, local_err);
1415 return;
1417 /* Grab a reference so hotplug does not delete the BlockDriverState from
1418 * underneath us.
1420 drive_get_ref(drive_get_by_blockdev(bs));
1423 void qmp_drive_backup(const char *device, const char *target,
1424 bool has_format, const char *format,
1425 enum MirrorSyncMode sync,
1426 bool has_mode, enum NewImageMode mode,
1427 bool has_speed, int64_t speed,
1428 bool has_on_source_error, BlockdevOnError on_source_error,
1429 bool has_on_target_error, BlockdevOnError on_target_error,
1430 Error **errp)
1432 BlockDriverState *bs;
1433 BlockDriverState *target_bs;
1434 BlockDriver *drv = NULL;
1435 Error *local_err = NULL;
1436 int flags;
1437 int64_t size;
1438 int ret;
1440 if (sync != MIRROR_SYNC_MODE_FULL) {
1441 error_setg(errp, "only sync mode 'full' is currently supported");
1442 return;
1444 if (!has_speed) {
1445 speed = 0;
1447 if (!has_on_source_error) {
1448 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
1450 if (!has_on_target_error) {
1451 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
1453 if (!has_mode) {
1454 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1457 bs = bdrv_find(device);
1458 if (!bs) {
1459 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1460 return;
1463 if (!bdrv_is_inserted(bs)) {
1464 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1465 return;
1468 if (!has_format) {
1469 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
1471 if (format) {
1472 drv = bdrv_find_format(format);
1473 if (!drv) {
1474 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1475 return;
1479 if (bdrv_in_use(bs)) {
1480 error_set(errp, QERR_DEVICE_IN_USE, device);
1481 return;
1484 flags = bs->open_flags | BDRV_O_RDWR;
1486 size = bdrv_getlength(bs);
1487 if (size < 0) {
1488 error_setg_errno(errp, -size, "bdrv_getlength failed");
1489 return;
1492 if (mode != NEW_IMAGE_MODE_EXISTING) {
1493 assert(format && drv);
1494 bdrv_img_create(target, format,
1495 NULL, NULL, NULL, size, flags, &local_err, false);
1498 if (error_is_set(&local_err)) {
1499 error_propagate(errp, local_err);
1500 return;
1503 target_bs = bdrv_new("");
1504 ret = bdrv_open(target_bs, target, NULL, flags, drv);
1505 if (ret < 0) {
1506 bdrv_delete(target_bs);
1507 error_setg_file_open(errp, -ret, target);
1508 return;
1511 backup_start(bs, target_bs, speed, on_source_error, on_target_error,
1512 block_job_cb, bs, &local_err);
1513 if (local_err != NULL) {
1514 bdrv_delete(target_bs);
1515 error_propagate(errp, local_err);
1516 return;
1519 /* Grab a reference so hotplug does not delete the BlockDriverState from
1520 * underneath us.
1522 drive_get_ref(drive_get_by_blockdev(bs));
1525 #define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
1527 void qmp_drive_mirror(const char *device, const char *target,
1528 bool has_format, const char *format,
1529 enum MirrorSyncMode sync,
1530 bool has_mode, enum NewImageMode mode,
1531 bool has_speed, int64_t speed,
1532 bool has_granularity, uint32_t granularity,
1533 bool has_buf_size, int64_t buf_size,
1534 bool has_on_source_error, BlockdevOnError on_source_error,
1535 bool has_on_target_error, BlockdevOnError on_target_error,
1536 Error **errp)
1538 BlockDriverState *bs;
1539 BlockDriverState *source, *target_bs;
1540 BlockDriver *drv = NULL;
1541 Error *local_err = NULL;
1542 int flags;
1543 int64_t size;
1544 int ret;
1546 if (!has_speed) {
1547 speed = 0;
1549 if (!has_on_source_error) {
1550 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
1552 if (!has_on_target_error) {
1553 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
1555 if (!has_mode) {
1556 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1558 if (!has_granularity) {
1559 granularity = 0;
1561 if (!has_buf_size) {
1562 buf_size = DEFAULT_MIRROR_BUF_SIZE;
1565 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
1566 error_set(errp, QERR_INVALID_PARAMETER, device);
1567 return;
1569 if (granularity & (granularity - 1)) {
1570 error_set(errp, QERR_INVALID_PARAMETER, device);
1571 return;
1574 bs = bdrv_find(device);
1575 if (!bs) {
1576 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1577 return;
1580 if (!bdrv_is_inserted(bs)) {
1581 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1582 return;
1585 if (!has_format) {
1586 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
1588 if (format) {
1589 drv = bdrv_find_format(format);
1590 if (!drv) {
1591 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1592 return;
1596 if (bdrv_in_use(bs)) {
1597 error_set(errp, QERR_DEVICE_IN_USE, device);
1598 return;
1601 flags = bs->open_flags | BDRV_O_RDWR;
1602 source = bs->backing_hd;
1603 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
1604 sync = MIRROR_SYNC_MODE_FULL;
1607 size = bdrv_getlength(bs);
1608 if (size < 0) {
1609 error_setg_errno(errp, -size, "bdrv_getlength failed");
1610 return;
1613 if (sync == MIRROR_SYNC_MODE_FULL && mode != NEW_IMAGE_MODE_EXISTING) {
1614 /* create new image w/o backing file */
1615 assert(format && drv);
1616 bdrv_img_create(target, format,
1617 NULL, NULL, NULL, size, flags, &local_err, false);
1618 } else {
1619 switch (mode) {
1620 case NEW_IMAGE_MODE_EXISTING:
1621 ret = 0;
1622 break;
1623 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
1624 /* create new image with backing file */
1625 bdrv_img_create(target, format,
1626 source->filename,
1627 source->drv->format_name,
1628 NULL, size, flags, &local_err, false);
1629 break;
1630 default:
1631 abort();
1635 if (error_is_set(&local_err)) {
1636 error_propagate(errp, local_err);
1637 return;
1640 /* Mirroring takes care of copy-on-write using the source's backing
1641 * file.
1643 target_bs = bdrv_new("");
1644 ret = bdrv_open(target_bs, target, NULL, flags | BDRV_O_NO_BACKING, drv);
1645 if (ret < 0) {
1646 bdrv_delete(target_bs);
1647 error_setg_file_open(errp, -ret, target);
1648 return;
1651 mirror_start(bs, target_bs, speed, granularity, buf_size, sync,
1652 on_source_error, on_target_error,
1653 block_job_cb, bs, &local_err);
1654 if (local_err != NULL) {
1655 bdrv_delete(target_bs);
1656 error_propagate(errp, local_err);
1657 return;
1660 /* Grab a reference so hotplug does not delete the BlockDriverState from
1661 * underneath us.
1663 drive_get_ref(drive_get_by_blockdev(bs));
1666 static BlockJob *find_block_job(const char *device)
1668 BlockDriverState *bs;
1670 bs = bdrv_find(device);
1671 if (!bs || !bs->job) {
1672 return NULL;
1674 return bs->job;
1677 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
1679 BlockJob *job = find_block_job(device);
1681 if (!job) {
1682 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
1683 return;
1686 block_job_set_speed(job, speed, errp);
1689 void qmp_block_job_cancel(const char *device,
1690 bool has_force, bool force, Error **errp)
1692 BlockJob *job = find_block_job(device);
1694 if (!has_force) {
1695 force = false;
1698 if (!job) {
1699 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
1700 return;
1702 if (job->paused && !force) {
1703 error_set(errp, QERR_BLOCK_JOB_PAUSED, device);
1704 return;
1707 trace_qmp_block_job_cancel(job);
1708 block_job_cancel(job);
1711 void qmp_block_job_pause(const char *device, Error **errp)
1713 BlockJob *job = find_block_job(device);
1715 if (!job) {
1716 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
1717 return;
1720 trace_qmp_block_job_pause(job);
1721 block_job_pause(job);
1724 void qmp_block_job_resume(const char *device, Error **errp)
1726 BlockJob *job = find_block_job(device);
1728 if (!job) {
1729 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
1730 return;
1733 trace_qmp_block_job_resume(job);
1734 block_job_resume(job);
1737 void qmp_block_job_complete(const char *device, Error **errp)
1739 BlockJob *job = find_block_job(device);
1741 if (!job) {
1742 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
1743 return;
1746 trace_qmp_block_job_complete(job);
1747 block_job_complete(job, errp);
1750 static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
1752 BlockJobInfoList **prev = opaque;
1753 BlockJob *job = bs->job;
1755 if (job) {
1756 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
1757 elem->value = block_job_query(bs->job);
1758 (*prev)->next = elem;
1759 *prev = elem;
1763 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
1765 /* Dummy is a fake list element for holding the head pointer */
1766 BlockJobInfoList dummy = {};
1767 BlockJobInfoList *prev = &dummy;
1768 bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
1769 return dummy.next;
1772 QemuOptsList qemu_common_drive_opts = {
1773 .name = "drive",
1774 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
1775 .desc = {
1777 .name = "bus",
1778 .type = QEMU_OPT_NUMBER,
1779 .help = "bus number",
1781 .name = "unit",
1782 .type = QEMU_OPT_NUMBER,
1783 .help = "unit number (i.e. lun for scsi)",
1785 .name = "if",
1786 .type = QEMU_OPT_STRING,
1787 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
1789 .name = "index",
1790 .type = QEMU_OPT_NUMBER,
1791 .help = "index number",
1793 .name = "cyls",
1794 .type = QEMU_OPT_NUMBER,
1795 .help = "number of cylinders (ide disk geometry)",
1797 .name = "heads",
1798 .type = QEMU_OPT_NUMBER,
1799 .help = "number of heads (ide disk geometry)",
1801 .name = "secs",
1802 .type = QEMU_OPT_NUMBER,
1803 .help = "number of sectors (ide disk geometry)",
1805 .name = "trans",
1806 .type = QEMU_OPT_STRING,
1807 .help = "chs translation (auto, lba. none)",
1809 .name = "media",
1810 .type = QEMU_OPT_STRING,
1811 .help = "media type (disk, cdrom)",
1813 .name = "snapshot",
1814 .type = QEMU_OPT_BOOL,
1815 .help = "enable/disable snapshot mode",
1817 .name = "file",
1818 .type = QEMU_OPT_STRING,
1819 .help = "disk image",
1821 .name = "discard",
1822 .type = QEMU_OPT_STRING,
1823 .help = "discard operation (ignore/off, unmap/on)",
1825 .name = "cache",
1826 .type = QEMU_OPT_STRING,
1827 .help = "host cache usage (none, writeback, writethrough, "
1828 "directsync, unsafe)",
1830 .name = "aio",
1831 .type = QEMU_OPT_STRING,
1832 .help = "host AIO implementation (threads, native)",
1834 .name = "format",
1835 .type = QEMU_OPT_STRING,
1836 .help = "disk format (raw, qcow2, ...)",
1838 .name = "serial",
1839 .type = QEMU_OPT_STRING,
1840 .help = "disk serial number",
1842 .name = "rerror",
1843 .type = QEMU_OPT_STRING,
1844 .help = "read error action",
1846 .name = "werror",
1847 .type = QEMU_OPT_STRING,
1848 .help = "write error action",
1850 .name = "addr",
1851 .type = QEMU_OPT_STRING,
1852 .help = "pci address (virtio only)",
1854 .name = "readonly",
1855 .type = QEMU_OPT_BOOL,
1856 .help = "open drive file as read-only",
1858 .name = "iops",
1859 .type = QEMU_OPT_NUMBER,
1860 .help = "limit total I/O operations per second",
1862 .name = "iops_rd",
1863 .type = QEMU_OPT_NUMBER,
1864 .help = "limit read operations per second",
1866 .name = "iops_wr",
1867 .type = QEMU_OPT_NUMBER,
1868 .help = "limit write operations per second",
1870 .name = "bps",
1871 .type = QEMU_OPT_NUMBER,
1872 .help = "limit total bytes per second",
1874 .name = "bps_rd",
1875 .type = QEMU_OPT_NUMBER,
1876 .help = "limit read bytes per second",
1878 .name = "bps_wr",
1879 .type = QEMU_OPT_NUMBER,
1880 .help = "limit write bytes per second",
1882 .name = "copy-on-read",
1883 .type = QEMU_OPT_BOOL,
1884 .help = "copy read data from backing file into image file",
1886 .name = "boot",
1887 .type = QEMU_OPT_BOOL,
1888 .help = "(deprecated, ignored)",
1890 { /* end of list */ }
1894 QemuOptsList qemu_drive_opts = {
1895 .name = "drive",
1896 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
1897 .desc = {
1899 * no elements => accept any params
1900 * validation will happen later
1902 { /* end of list */ }