]> git.proxmox.com Git - qemu.git/blame - blockdev.c
Mostly revert "qemu-help: Sort devices by logical functionality"
[qemu.git] / blockdev.c
CommitLineData
666daa68
MA
1/*
2 * QEMU host block devices
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 *
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.
3618a094
MA
8 *
9 * This file incorporates work covered by the following copyright and
10 * permission notice:
11 *
12 * Copyright (c) 2003-2008 Fabrice Bellard
13 *
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:
20 *
21 * The above copyright notice and this permission notice shall be included in
22 * all copies or substantial portions of the Software.
23 *
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.
666daa68
MA
31 */
32
9c17d615 33#include "sysemu/blockdev.h"
0d09e41a 34#include "hw/block/block.h"
737e150e 35#include "block/blockjob.h"
83c9089e 36#include "monitor/monitor.h"
7b1b5d19 37#include "qapi/qmp/qerror.h"
1de7afc9
PB
38#include "qemu/option.h"
39#include "qemu/config-file.h"
7b1b5d19 40#include "qapi/qmp/types.h"
d26c9a15
KW
41#include "qapi-visit.h"
42#include "qapi/qmp-output-visitor.h"
9c17d615 43#include "sysemu/sysemu.h"
737e150e 44#include "block/block_int.h"
a4dea8a9 45#include "qmp-commands.h"
12bd451f 46#include "trace.h"
9c17d615 47#include "sysemu/arch_init.h"
666daa68 48
c9b62a7e 49static QTAILQ_HEAD(drivelist, DriveInfo) drives = QTAILQ_HEAD_INITIALIZER(drives);
0006383e 50extern QemuOptsList qemu_common_drive_opts;
666daa68 51
1960966d
MA
52static const char *const if_name[IF_COUNT] = {
53 [IF_NONE] = "none",
54 [IF_IDE] = "ide",
55 [IF_SCSI] = "scsi",
56 [IF_FLOPPY] = "floppy",
57 [IF_PFLASH] = "pflash",
58 [IF_MTD] = "mtd",
59 [IF_SD] = "sd",
60 [IF_VIRTIO] = "virtio",
61 [IF_XEN] = "xen",
62};
63
64static const int if_max_devs[IF_COUNT] = {
27d6bf40
MA
65 /*
66 * Do not change these numbers! They govern how drive option
67 * index maps to unit and bus. That mapping is ABI.
68 *
69 * All controllers used to imlement if=T drives need to support
70 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
71 * Otherwise, some index values map to "impossible" bus, unit
72 * values.
73 *
74 * For instance, if you change [IF_SCSI] to 255, -drive
75 * if=scsi,index=12 no longer means bus=1,unit=5, but
76 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
77 * the drive can't be set up. Regression.
78 */
79 [IF_IDE] = 2,
80 [IF_SCSI] = 7,
1960966d
MA
81};
82
14bafc54
MA
83/*
84 * We automatically delete the drive when a device using it gets
85 * unplugged. Questionable feature, but we can't just drop it.
86 * Device models call blockdev_mark_auto_del() to schedule the
87 * automatic deletion, and generic qdev code calls blockdev_auto_del()
88 * when deletion is actually safe.
89 */
90void blockdev_mark_auto_del(BlockDriverState *bs)
91{
92 DriveInfo *dinfo = drive_get_by_blockdev(bs);
93
2d246f01
KW
94 if (dinfo && !dinfo->enable_auto_del) {
95 return;
96 }
97
12bde0ee
PB
98 if (bs->job) {
99 block_job_cancel(bs->job);
100 }
0fc0f1fa
RH
101 if (dinfo) {
102 dinfo->auto_del = 1;
103 }
14bafc54
MA
104}
105
106void blockdev_auto_del(BlockDriverState *bs)
107{
108 DriveInfo *dinfo = drive_get_by_blockdev(bs);
109
0fc0f1fa 110 if (dinfo && dinfo->auto_del) {
84fb3925 111 drive_put_ref(dinfo);
14bafc54
MA
112 }
113}
114
505a7fb1
MA
115static int drive_index_to_bus_id(BlockInterfaceType type, int index)
116{
117 int max_devs = if_max_devs[type];
118 return max_devs ? index / max_devs : 0;
119}
120
121static int drive_index_to_unit_id(BlockInterfaceType type, int index)
122{
123 int max_devs = if_max_devs[type];
124 return max_devs ? index % max_devs : index;
125}
126
2292ddae
MA
127QemuOpts *drive_def(const char *optstr)
128{
129 return qemu_opts_parse(qemu_find_opts("drive"), optstr, 0);
130}
131
132QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
5645b0f4 133 const char *optstr)
666daa68 134{
666daa68 135 QemuOpts *opts;
2292ddae 136 char buf[32];
666daa68 137
2292ddae 138 opts = drive_def(optstr);
666daa68
MA
139 if (!opts) {
140 return NULL;
141 }
2292ddae
MA
142 if (type != IF_DEFAULT) {
143 qemu_opt_set(opts, "if", if_name[type]);
144 }
145 if (index >= 0) {
146 snprintf(buf, sizeof(buf), "%d", index);
147 qemu_opt_set(opts, "index", buf);
148 }
666daa68
MA
149 if (file)
150 qemu_opt_set(opts, "file", file);
151 return opts;
152}
153
154DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
155{
156 DriveInfo *dinfo;
157
158 /* seek interface, bus and unit */
159
160 QTAILQ_FOREACH(dinfo, &drives, next) {
161 if (dinfo->type == type &&
162 dinfo->bus == bus &&
163 dinfo->unit == unit)
164 return dinfo;
165 }
166
167 return NULL;
168}
169
f1bd51ac
MA
170DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
171{
172 return drive_get(type,
173 drive_index_to_bus_id(type, index),
174 drive_index_to_unit_id(type, index));
175}
176
666daa68
MA
177int drive_get_max_bus(BlockInterfaceType type)
178{
179 int max_bus;
180 DriveInfo *dinfo;
181
182 max_bus = -1;
183 QTAILQ_FOREACH(dinfo, &drives, next) {
184 if(dinfo->type == type &&
185 dinfo->bus > max_bus)
186 max_bus = dinfo->bus;
187 }
188 return max_bus;
189}
190
13839974
MA
191/* Get a block device. This should only be used for single-drive devices
192 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
193 appropriate bus. */
194DriveInfo *drive_get_next(BlockInterfaceType type)
195{
196 static int next_block_unit[IF_COUNT];
197
198 return drive_get(type, 0, next_block_unit[type]++);
199}
200
e4700e59 201DriveInfo *drive_get_by_blockdev(BlockDriverState *bs)
666daa68
MA
202{
203 DriveInfo *dinfo;
204
205 QTAILQ_FOREACH(dinfo, &drives, next) {
e4700e59
MA
206 if (dinfo->bdrv == bs) {
207 return dinfo;
208 }
666daa68 209 }
e4700e59 210 return NULL;
666daa68
MA
211}
212
666daa68
MA
213static void bdrv_format_print(void *opaque, const char *name)
214{
807105a7 215 error_printf(" %s", name);
666daa68
MA
216}
217
84fb3925 218static void drive_uninit(DriveInfo *dinfo)
666daa68 219{
f298d071
KW
220 if (dinfo->opts) {
221 qemu_opts_del(dinfo->opts);
222 }
223
4f6fd349 224 bdrv_unref(dinfo->bdrv);
7267c094 225 g_free(dinfo->id);
666daa68 226 QTAILQ_REMOVE(&drives, dinfo, next);
bb44619b 227 g_free(dinfo->serial);
7267c094 228 g_free(dinfo);
666daa68
MA
229}
230
84fb3925
MT
231void drive_put_ref(DriveInfo *dinfo)
232{
233 assert(dinfo->refcount);
234 if (--dinfo->refcount == 0) {
235 drive_uninit(dinfo);
236 }
237}
238
239void drive_get_ref(DriveInfo *dinfo)
240{
241 dinfo->refcount++;
242}
243
aa398a5c
SH
244typedef struct {
245 QEMUBH *bh;
fa510ebf
FZ
246 BlockDriverState *bs;
247} BDRVPutRefBH;
aa398a5c 248
fa510ebf 249static void bdrv_put_ref_bh(void *opaque)
aa398a5c 250{
fa510ebf 251 BDRVPutRefBH *s = opaque;
aa398a5c 252
fa510ebf 253 bdrv_unref(s->bs);
aa398a5c
SH
254 qemu_bh_delete(s->bh);
255 g_free(s);
256}
257
258/*
fa510ebf 259 * Release a BDS reference in a BH
aa398a5c 260 *
fa510ebf
FZ
261 * It is not safe to use bdrv_unref() from a callback function when the callers
262 * still need the BlockDriverState. In such cases we schedule a BH to release
263 * the reference.
aa398a5c 264 */
fa510ebf 265static void bdrv_put_ref_bh_schedule(BlockDriverState *bs)
aa398a5c 266{
fa510ebf 267 BDRVPutRefBH *s;
aa398a5c 268
fa510ebf
FZ
269 s = g_new(BDRVPutRefBH, 1);
270 s->bh = qemu_bh_new(bdrv_put_ref_bh, s);
271 s->bs = bs;
aa398a5c
SH
272 qemu_bh_schedule(s->bh);
273}
274
b681072d 275static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
666daa68
MA
276{
277 if (!strcmp(buf, "ignore")) {
92aa5c6d 278 return BLOCKDEV_ON_ERROR_IGNORE;
666daa68 279 } else if (!is_read && !strcmp(buf, "enospc")) {
92aa5c6d 280 return BLOCKDEV_ON_ERROR_ENOSPC;
666daa68 281 } else if (!strcmp(buf, "stop")) {
92aa5c6d 282 return BLOCKDEV_ON_ERROR_STOP;
666daa68 283 } else if (!strcmp(buf, "report")) {
92aa5c6d 284 return BLOCKDEV_ON_ERROR_REPORT;
666daa68 285 } else {
b681072d
KW
286 error_setg(errp, "'%s' invalid %s error action",
287 buf, is_read ? "read" : "write");
666daa68
MA
288 return -1;
289 }
290}
291
cc0681c4 292static bool check_throttle_config(ThrottleConfig *cfg, Error **errp)
0563e191 293{
cc0681c4
BC
294 if (throttle_conflicting(cfg)) {
295 error_setg(errp, "bps/iops/max total values and read/write values"
296 " cannot be used at the same time");
0563e191
ZYW
297 return false;
298 }
299
cc0681c4
BC
300 if (!throttle_is_valid(cfg)) {
301 error_setg(errp, "bps/iops/maxs values must be 0 or greater");
7d81c141
SH
302 return false;
303 }
304
0563e191
ZYW
305 return true;
306}
307
33cb7dc8
KW
308typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
309
f298d071
KW
310/* Takes the ownership of bs_opts */
311static DriveInfo *blockdev_init(QDict *bs_opts,
b681072d
KW
312 BlockInterfaceType type,
313 Error **errp)
666daa68
MA
314{
315 const char *buf;
316 const char *file = NULL;
666daa68 317 const char *serial;
666daa68
MA
318 int ro = 0;
319 int bdrv_flags = 0;
320 int on_read_error, on_write_error;
666daa68 321 DriveInfo *dinfo;
cc0681c4 322 ThrottleConfig cfg;
666daa68 323 int snapshot = 0;
fb0490f6 324 bool copy_on_read;
666daa68 325 int ret;
c546194f 326 Error *error = NULL;
0006383e 327 QemuOpts *opts;
0006383e 328 const char *id;
74fe54f2 329 bool has_driver_specific_opts;
6db5f5d6 330 BlockDriver *drv = NULL;
666daa68 331
f298d071
KW
332 /* Check common options by copying from bs_opts to opts, all other options
333 * stay in bs_opts for processing by bdrv_open(). */
334 id = qdict_get_try_str(bs_opts, "id");
0006383e
KW
335 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
336 if (error_is_set(&error)) {
b681072d 337 error_propagate(errp, error);
0006383e
KW
338 return NULL;
339 }
340
0006383e
KW
341 qemu_opts_absorb_qdict(opts, bs_opts, &error);
342 if (error_is_set(&error)) {
b681072d 343 error_propagate(errp, error);
0006383e
KW
344 return NULL;
345 }
346
347 if (id) {
348 qdict_del(bs_opts, "id");
349 }
350
74fe54f2
KW
351 has_driver_specific_opts = !!qdict_size(bs_opts);
352
666daa68 353 /* extract parameters */
666daa68 354 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
0f227a94 355 ro = qemu_opt_get_bool(opts, "read-only", 0);
fb0490f6 356 copy_on_read = qemu_opt_get_bool(opts, "copy-on-read", false);
666daa68
MA
357
358 file = qemu_opt_get(opts, "file");
359 serial = qemu_opt_get(opts, "serial");
360
a9384aff
PB
361 if ((buf = qemu_opt_get(opts, "discard")) != NULL) {
362 if (bdrv_parse_discard_flags(buf, &bdrv_flags) != 0) {
b681072d 363 error_setg(errp, "invalid discard option");
a9384aff
PB
364 return NULL;
365 }
366 }
367
29c4e2b5
KW
368 if (qemu_opt_get_bool(opts, "cache.writeback", true)) {
369 bdrv_flags |= BDRV_O_CACHE_WB;
370 }
371 if (qemu_opt_get_bool(opts, "cache.direct", false)) {
372 bdrv_flags |= BDRV_O_NOCACHE;
373 }
1df6fa4b 374 if (qemu_opt_get_bool(opts, "cache.no-flush", false)) {
29c4e2b5 375 bdrv_flags |= BDRV_O_NO_FLUSH;
666daa68
MA
376 }
377
378#ifdef CONFIG_LINUX_AIO
379 if ((buf = qemu_opt_get(opts, "aio")) != NULL) {
380 if (!strcmp(buf, "native")) {
381 bdrv_flags |= BDRV_O_NATIVE_AIO;
382 } else if (!strcmp(buf, "threads")) {
383 /* this is the default */
384 } else {
b681072d 385 error_setg(errp, "invalid aio option");
666daa68
MA
386 return NULL;
387 }
388 }
389#endif
390
391 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
c8057f95
PM
392 if (is_help_option(buf)) {
393 error_printf("Supported formats:");
394 bdrv_iterate_format(bdrv_format_print, NULL);
395 error_printf("\n");
396 return NULL;
666daa68 397 }
74fe54f2 398
8f94a6e4 399 drv = bdrv_find_format(buf);
6db5f5d6 400 if (!drv) {
b681072d 401 error_setg(errp, "'%s' invalid format", buf);
6db5f5d6
MQ
402 return NULL;
403 }
666daa68
MA
404 }
405
0563e191 406 /* disk I/O throttling */
cc0681c4
BC
407 memset(&cfg, 0, sizeof(cfg));
408 cfg.buckets[THROTTLE_BPS_TOTAL].avg =
57975222 409 qemu_opt_get_number(opts, "throttling.bps-total", 0);
cc0681c4 410 cfg.buckets[THROTTLE_BPS_READ].avg =
57975222 411 qemu_opt_get_number(opts, "throttling.bps-read", 0);
cc0681c4 412 cfg.buckets[THROTTLE_BPS_WRITE].avg =
57975222 413 qemu_opt_get_number(opts, "throttling.bps-write", 0);
cc0681c4 414 cfg.buckets[THROTTLE_OPS_TOTAL].avg =
57975222 415 qemu_opt_get_number(opts, "throttling.iops-total", 0);
cc0681c4 416 cfg.buckets[THROTTLE_OPS_READ].avg =
57975222 417 qemu_opt_get_number(opts, "throttling.iops-read", 0);
cc0681c4 418 cfg.buckets[THROTTLE_OPS_WRITE].avg =
57975222 419 qemu_opt_get_number(opts, "throttling.iops-write", 0);
0563e191 420
3e9fab69
BC
421 cfg.buckets[THROTTLE_BPS_TOTAL].max =
422 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
423 cfg.buckets[THROTTLE_BPS_READ].max =
424 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
425 cfg.buckets[THROTTLE_BPS_WRITE].max =
426 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
427 cfg.buckets[THROTTLE_OPS_TOTAL].max =
428 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
429 cfg.buckets[THROTTLE_OPS_READ].max =
430 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
431 cfg.buckets[THROTTLE_OPS_WRITE].max =
432 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
cc0681c4 433
2024c1df 434 cfg.op_size = qemu_opt_get_number(opts, "throttling.iops-size", 0);
cc0681c4
BC
435
436 if (!check_throttle_config(&cfg, &error)) {
b681072d 437 error_propagate(errp, error);
0563e191
ZYW
438 return NULL;
439 }
440
92aa5c6d 441 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
666daa68
MA
442 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
443 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) {
b681072d 444 error_setg(errp, "werror is not supported by this bus type");
666daa68
MA
445 return NULL;
446 }
447
b681072d
KW
448 on_write_error = parse_block_error_action(buf, 0, &error);
449 if (error_is_set(&error)) {
450 error_propagate(errp, error);
666daa68
MA
451 return NULL;
452 }
453 }
454
92aa5c6d 455 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
666daa68 456 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
5dba48a8 457 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI && type != IF_NONE) {
807105a7 458 error_report("rerror is not supported by this bus type");
666daa68
MA
459 return NULL;
460 }
461
b681072d
KW
462 on_read_error = parse_block_error_action(buf, 1, &error);
463 if (error_is_set(&error)) {
464 error_propagate(errp, error);
666daa68
MA
465 return NULL;
466 }
467 }
468
326642bc
KW
469 /* init */
470 dinfo = g_malloc0(sizeof(*dinfo));
471 dinfo->id = g_strdup(qemu_opts_id(opts));
666daa68 472 dinfo->bdrv = bdrv_new(dinfo->id);
80dd1aae
KS
473 dinfo->bdrv->open_flags = snapshot ? BDRV_O_SNAPSHOT : 0;
474 dinfo->bdrv->read_only = ro;
666daa68 475 dinfo->type = type;
84fb3925 476 dinfo->refcount = 1;
bb44619b
KW
477 if (serial != NULL) {
478 dinfo->serial = g_strdup(serial);
479 }
666daa68
MA
480 QTAILQ_INSERT_TAIL(&drives, dinfo, next);
481
abd7f68d
MA
482 bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);
483
0563e191 484 /* disk I/O throttling */
cc0681c4
BC
485 if (throttle_enabled(&cfg)) {
486 bdrv_io_limits_enable(dinfo->bdrv);
487 bdrv_set_io_limits(dinfo->bdrv, &cfg);
488 }
0563e191 489
dd5b0d71 490 if (!file || !*file) {
74fe54f2 491 if (has_driver_specific_opts) {
c2ad1b0c
KW
492 file = NULL;
493 } else {
494 return dinfo;
495 }
666daa68
MA
496 }
497 if (snapshot) {
498 /* always use cache=unsafe with snapshot */
499 bdrv_flags &= ~BDRV_O_CACHE_MASK;
500 bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);
501 }
502
fb0490f6
SH
503 if (copy_on_read) {
504 bdrv_flags |= BDRV_O_COPY_ON_READ;
505 }
506
ed9d4205
BC
507 if (runstate_check(RUN_STATE_INMIGRATE)) {
508 bdrv_flags |= BDRV_O_INCOMING;
509 }
510
666daa68
MA
511 bdrv_flags |= ro ? 0 : BDRV_O_RDWR;
512
74fe54f2 513 QINCREF(bs_opts);
34b5d2c6 514 ret = bdrv_open(dinfo->bdrv, file, bs_opts, bdrv_flags, drv, &error);
0006383e 515
666daa68 516 if (ret < 0) {
b681072d
KW
517 error_setg(errp, "could not open disk image %s: %s",
518 file ?: dinfo->id, error_get_pretty(error));
519 error_free(error);
a9ae2bff 520 goto err;
666daa68
MA
521 }
522
523 if (bdrv_key_required(dinfo->bdrv))
524 autostart = 0;
0006383e 525
74fe54f2 526 QDECREF(bs_opts);
0006383e
KW
527 qemu_opts_del(opts);
528
666daa68 529 return dinfo;
a9ae2bff
MA
530
531err:
0006383e
KW
532 qemu_opts_del(opts);
533 QDECREF(bs_opts);
4f6fd349 534 bdrv_unref(dinfo->bdrv);
7267c094 535 g_free(dinfo->id);
a9ae2bff 536 QTAILQ_REMOVE(&drives, dinfo, next);
7267c094 537 g_free(dinfo);
a9ae2bff 538 return NULL;
666daa68
MA
539}
540
57975222
KW
541static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to)
542{
543 const char *value;
544
545 value = qemu_opt_get(opts, from);
546 if (value) {
547 qemu_opt_set(opts, to, value);
548 qemu_opt_unset(opts, from);
549 }
550}
551
33cb7dc8
KW
552QemuOptsList qemu_legacy_drive_opts = {
553 .name = "drive",
554 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
555 .desc = {
556 {
87a899c5
KW
557 .name = "bus",
558 .type = QEMU_OPT_NUMBER,
559 .help = "bus number",
560 },{
561 .name = "unit",
562 .type = QEMU_OPT_NUMBER,
563 .help = "unit number (i.e. lun for scsi)",
564 },{
565 .name = "index",
566 .type = QEMU_OPT_NUMBER,
567 .help = "index number",
568 },{
33cb7dc8
KW
569 .name = "media",
570 .type = QEMU_OPT_STRING,
571 .help = "media type (disk, cdrom)",
593d464b
KW
572 },{
573 .name = "if",
574 .type = QEMU_OPT_STRING,
575 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
b41a7338
KW
576 },{
577 .name = "cyls",
578 .type = QEMU_OPT_NUMBER,
579 .help = "number of cylinders (ide disk geometry)",
580 },{
581 .name = "heads",
582 .type = QEMU_OPT_NUMBER,
583 .help = "number of heads (ide disk geometry)",
584 },{
585 .name = "secs",
586 .type = QEMU_OPT_NUMBER,
587 .help = "number of sectors (ide disk geometry)",
588 },{
589 .name = "trans",
590 .type = QEMU_OPT_STRING,
591 .help = "chs translation (auto, lba, none)",
26929298
KW
592 },{
593 .name = "boot",
594 .type = QEMU_OPT_BOOL,
595 .help = "(deprecated, ignored)",
394c7d4d
KW
596 },{
597 .name = "addr",
598 .type = QEMU_OPT_STRING,
599 .help = "pci address (virtio only)",
33cb7dc8 600 },
0ebd24e0
KW
601
602 /* Options that are passed on, but have special semantics with -drive */
603 {
604 .name = "read-only",
605 .type = QEMU_OPT_BOOL,
606 .help = "open drive file as read-only",
607 },{
608 .name = "copy-on-read",
609 .type = QEMU_OPT_BOOL,
610 .help = "copy read data from backing file into image file",
611 },
612
33cb7dc8
KW
613 { /* end of list */ }
614 },
615};
616
57975222
KW
617DriveInfo *drive_init(QemuOpts *all_opts, BlockInterfaceType block_default_type)
618{
29c4e2b5 619 const char *value;
33cb7dc8 620 DriveInfo *dinfo = NULL;
f298d071 621 QDict *bs_opts;
33cb7dc8
KW
622 QemuOpts *legacy_opts;
623 DriveMediaType media = MEDIA_DISK;
593d464b 624 BlockInterfaceType type;
b41a7338 625 int cyls, heads, secs, translation;
87a899c5 626 int max_devs, bus_id, unit_id, index;
394c7d4d 627 const char *devaddr;
0ebd24e0 628 bool read_only, copy_on_read;
33cb7dc8 629 Error *local_err = NULL;
29c4e2b5 630
57975222
KW
631 /* Change legacy command line options into QMP ones */
632 qemu_opt_rename(all_opts, "iops", "throttling.iops-total");
633 qemu_opt_rename(all_opts, "iops_rd", "throttling.iops-read");
634 qemu_opt_rename(all_opts, "iops_wr", "throttling.iops-write");
635
636 qemu_opt_rename(all_opts, "bps", "throttling.bps-total");
637 qemu_opt_rename(all_opts, "bps_rd", "throttling.bps-read");
638 qemu_opt_rename(all_opts, "bps_wr", "throttling.bps-write");
639
3e9fab69
BC
640 qemu_opt_rename(all_opts, "iops_max", "throttling.iops-total-max");
641 qemu_opt_rename(all_opts, "iops_rd_max", "throttling.iops-read-max");
642 qemu_opt_rename(all_opts, "iops_wr_max", "throttling.iops-write-max");
643
644 qemu_opt_rename(all_opts, "bps_max", "throttling.bps-total-max");
645 qemu_opt_rename(all_opts, "bps_rd_max", "throttling.bps-read-max");
646 qemu_opt_rename(all_opts, "bps_wr_max", "throttling.bps-write-max");
647
2024c1df
BC
648 qemu_opt_rename(all_opts,
649 "iops_size", "throttling.iops-size");
650
0f227a94
KW
651 qemu_opt_rename(all_opts, "readonly", "read-only");
652
29c4e2b5
KW
653 value = qemu_opt_get(all_opts, "cache");
654 if (value) {
655 int flags = 0;
656
657 if (bdrv_parse_cache_flags(value, &flags) != 0) {
658 error_report("invalid cache option");
659 return NULL;
660 }
661
662 /* Specific options take precedence */
663 if (!qemu_opt_get(all_opts, "cache.writeback")) {
664 qemu_opt_set_bool(all_opts, "cache.writeback",
665 !!(flags & BDRV_O_CACHE_WB));
666 }
667 if (!qemu_opt_get(all_opts, "cache.direct")) {
668 qemu_opt_set_bool(all_opts, "cache.direct",
669 !!(flags & BDRV_O_NOCACHE));
670 }
671 if (!qemu_opt_get(all_opts, "cache.no-flush")) {
672 qemu_opt_set_bool(all_opts, "cache.no-flush",
673 !!(flags & BDRV_O_NO_FLUSH));
674 }
675 qemu_opt_unset(all_opts, "cache");
676 }
677
f298d071
KW
678 /* Get a QDict for processing the options */
679 bs_opts = qdict_new();
680 qemu_opts_to_qdict(all_opts, bs_opts);
681
33cb7dc8
KW
682 legacy_opts = qemu_opts_create_nofail(&qemu_legacy_drive_opts);
683 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
684 if (error_is_set(&local_err)) {
685 qerror_report_err(local_err);
686 error_free(local_err);
687 goto fail;
688 }
689
26929298
KW
690 /* Deprecated option boot=[on|off] */
691 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
692 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
693 "ignored. Future versions will reject this parameter. Please "
694 "update your scripts.\n");
695 }
696
33cb7dc8
KW
697 /* Media type */
698 value = qemu_opt_get(legacy_opts, "media");
699 if (value) {
700 if (!strcmp(value, "disk")) {
701 media = MEDIA_DISK;
702 } else if (!strcmp(value, "cdrom")) {
703 media = MEDIA_CDROM;
e34ef046 704 qdict_put(bs_opts, "read-only", qstring_from_str("on"));
33cb7dc8
KW
705 } else {
706 error_report("'%s' invalid media", value);
707 goto fail;
708 }
709 }
710
0ebd24e0
KW
711 /* copy-on-read is disabled with a warning for read-only devices */
712 read_only = qemu_opt_get_bool(legacy_opts, "read-only", false);
713 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
714
715 if (read_only && copy_on_read) {
716 error_report("warning: disabling copy-on-read on read-only drive");
717 copy_on_read = false;
718 }
719
720 qdict_put(bs_opts, "read-only",
721 qstring_from_str(read_only ? "on" : "off"));
722 qdict_put(bs_opts, "copy-on-read",
723 qstring_from_str(copy_on_read ? "on" :"off"));
724
593d464b
KW
725 /* Controller type */
726 value = qemu_opt_get(legacy_opts, "if");
727 if (value) {
728 for (type = 0;
729 type < IF_COUNT && strcmp(value, if_name[type]);
730 type++) {
731 }
732 if (type == IF_COUNT) {
733 error_report("unsupported bus type '%s'", value);
734 goto fail;
735 }
736 } else {
737 type = block_default_type;
738 }
739
b41a7338
KW
740 /* Geometry */
741 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
742 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
743 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
744
745 if (cyls || heads || secs) {
746 if (cyls < 1) {
747 error_report("invalid physical cyls number");
748 goto fail;
749 }
750 if (heads < 1) {
751 error_report("invalid physical heads number");
752 goto fail;
753 }
754 if (secs < 1) {
755 error_report("invalid physical secs number");
756 goto fail;
757 }
758 }
759
760 translation = BIOS_ATA_TRANSLATION_AUTO;
761 value = qemu_opt_get(legacy_opts, "trans");
762 if (value != NULL) {
763 if (!cyls) {
764 error_report("'%s' trans must be used with cyls, heads and secs",
765 value);
766 goto fail;
767 }
768 if (!strcmp(value, "none")) {
769 translation = BIOS_ATA_TRANSLATION_NONE;
770 } else if (!strcmp(value, "lba")) {
771 translation = BIOS_ATA_TRANSLATION_LBA;
772 } else if (!strcmp(value, "auto")) {
773 translation = BIOS_ATA_TRANSLATION_AUTO;
774 } else {
775 error_report("'%s' invalid translation type", value);
776 goto fail;
777 }
778 }
779
780 if (media == MEDIA_CDROM) {
781 if (cyls || secs || heads) {
782 error_report("CHS can't be set with media=cdrom");
783 goto fail;
784 }
785 }
786
87a899c5
KW
787 /* Device address specified by bus/unit or index.
788 * If none was specified, try to find the first free one. */
789 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
790 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
791 index = qemu_opt_get_number(legacy_opts, "index", -1);
792
793 max_devs = if_max_devs[type];
794
795 if (index != -1) {
796 if (bus_id != 0 || unit_id != -1) {
797 error_report("index cannot be used with bus and unit");
798 goto fail;
799 }
800 bus_id = drive_index_to_bus_id(type, index);
801 unit_id = drive_index_to_unit_id(type, index);
802 }
803
804 if (unit_id == -1) {
805 unit_id = 0;
806 while (drive_get(type, bus_id, unit_id) != NULL) {
807 unit_id++;
808 if (max_devs && unit_id >= max_devs) {
809 unit_id -= max_devs;
810 bus_id++;
811 }
812 }
813 }
814
815 if (max_devs && unit_id >= max_devs) {
816 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
817 goto fail;
818 }
819
820 if (drive_get(type, bus_id, unit_id) != NULL) {
821 error_report("drive with bus=%d, unit=%d (index=%d) exists",
822 bus_id, unit_id, index);
823 goto fail;
824 }
825
826 /* no id supplied -> create one */
827 if (qemu_opts_id(all_opts) == NULL) {
828 char *new_id;
829 const char *mediastr = "";
830 if (type == IF_IDE || type == IF_SCSI) {
831 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
832 }
833 if (max_devs) {
834 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
835 mediastr, unit_id);
836 } else {
837 new_id = g_strdup_printf("%s%s%i", if_name[type],
838 mediastr, unit_id);
839 }
840 qdict_put(bs_opts, "id", qstring_from_str(new_id));
841 g_free(new_id);
842 }
843
394c7d4d
KW
844 /* Add virtio block device */
845 devaddr = qemu_opt_get(legacy_opts, "addr");
846 if (devaddr && type != IF_VIRTIO) {
847 error_report("addr is not supported by this bus type");
848 goto fail;
849 }
850
851 if (type == IF_VIRTIO) {
852 QemuOpts *devopts;
853 devopts = qemu_opts_create_nofail(qemu_find_opts("device"));
854 if (arch_type == QEMU_ARCH_S390X) {
855 qemu_opt_set(devopts, "driver", "virtio-blk-s390");
856 } else {
857 qemu_opt_set(devopts, "driver", "virtio-blk-pci");
858 }
859 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
860 if (devaddr) {
861 qemu_opt_set(devopts, "addr", devaddr);
862 }
863 }
864
2d246f01 865 /* Actual block device init: Functionality shared with blockdev-add */
b681072d 866 dinfo = blockdev_init(bs_opts, type, &local_err);
2d246f01 867 if (dinfo == NULL) {
b681072d
KW
868 if (error_is_set(&local_err)) {
869 qerror_report_err(local_err);
870 error_free(local_err);
871 }
2d246f01 872 goto fail;
b681072d
KW
873 } else {
874 assert(!error_is_set(&local_err));
2d246f01
KW
875 }
876
877 /* Set legacy DriveInfo fields */
878 dinfo->enable_auto_del = true;
f298d071 879 dinfo->opts = all_opts;
2d246f01 880
b41a7338
KW
881 dinfo->cyls = cyls;
882 dinfo->heads = heads;
883 dinfo->secs = secs;
884 dinfo->trans = translation;
885
87a899c5
KW
886 dinfo->bus = bus_id;
887 dinfo->unit = unit_id;
394c7d4d 888 dinfo->devaddr = devaddr;
87a899c5 889
e34ef046
KW
890 switch(type) {
891 case IF_IDE:
892 case IF_SCSI:
893 case IF_XEN:
894 case IF_NONE:
895 dinfo->media_cd = media == MEDIA_CDROM;
896 break;
897 default:
898 break;
899 }
900
2d246f01 901fail:
33cb7dc8 902 qemu_opts_del(legacy_opts);
2d246f01 903 return dinfo;
57975222
KW
904}
905
666daa68
MA
906void do_commit(Monitor *mon, const QDict *qdict)
907{
666daa68 908 const char *device = qdict_get_str(qdict, "device");
6ab4b5ab 909 BlockDriverState *bs;
e8877497 910 int ret;
666daa68 911
6ab4b5ab 912 if (!strcmp(device, "all")) {
e8877497 913 ret = bdrv_commit_all();
6ab4b5ab
MA
914 } else {
915 bs = bdrv_find(device);
ac59eb95 916 if (!bs) {
58513bde 917 monitor_printf(mon, "Device '%s' not found\n", device);
ac59eb95 918 return;
6ab4b5ab 919 }
2d3735d3 920 ret = bdrv_commit(bs);
58513bde
JC
921 }
922 if (ret < 0) {
923 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
924 strerror(-ret));
666daa68
MA
925 }
926}
927
6cc2a415
PB
928static void blockdev_do_action(int kind, void *data, Error **errp)
929{
c8a83e85
KW
930 TransactionAction action;
931 TransactionActionList list;
6cc2a415
PB
932
933 action.kind = kind;
934 action.data = data;
935 list.value = &action;
936 list.next = NULL;
937 qmp_transaction(&list, errp);
938}
939
6106e249
LC
940void qmp_blockdev_snapshot_sync(const char *device, const char *snapshot_file,
941 bool has_format, const char *format,
6cc2a415 942 bool has_mode, enum NewImageMode mode,
6106e249 943 Error **errp)
f8882568 944{
6cc2a415
PB
945 BlockdevSnapshot snapshot = {
946 .device = (char *) device,
947 .snapshot_file = (char *) snapshot_file,
948 .has_format = has_format,
949 .format = (char *) format,
950 .has_mode = has_mode,
951 .mode = mode,
952 };
c8a83e85
KW
953 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
954 &snapshot, errp);
f8882568
JS
955}
956
f323bc9e
WX
957void qmp_blockdev_snapshot_internal_sync(const char *device,
958 const char *name,
959 Error **errp)
960{
961 BlockdevSnapshotInternal snapshot = {
962 .device = (char *) device,
963 .name = (char *) name
964 };
965
966 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
967 &snapshot, errp);
968}
969
44e3e053
WX
970SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
971 bool has_id,
972 const char *id,
973 bool has_name,
974 const char *name,
975 Error **errp)
976{
977 BlockDriverState *bs = bdrv_find(device);
978 QEMUSnapshotInfo sn;
979 Error *local_err = NULL;
980 SnapshotInfo *info = NULL;
981 int ret;
982
983 if (!bs) {
984 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
985 return NULL;
986 }
987
988 if (!has_id) {
989 id = NULL;
990 }
991
992 if (!has_name) {
993 name = NULL;
994 }
995
996 if (!id && !name) {
997 error_setg(errp, "Name or id must be provided");
998 return NULL;
999 }
1000
1001 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1002 if (error_is_set(&local_err)) {
1003 error_propagate(errp, local_err);
1004 return NULL;
1005 }
1006 if (!ret) {
1007 error_setg(errp,
1008 "Snapshot with id '%s' and name '%s' does not exist on "
1009 "device '%s'",
1010 STR_OR_NULL(id), STR_OR_NULL(name), device);
1011 return NULL;
1012 }
1013
1014 bdrv_snapshot_delete(bs, id, name, &local_err);
1015 if (error_is_set(&local_err)) {
1016 error_propagate(errp, local_err);
1017 return NULL;
1018 }
1019
1020 info = g_malloc0(sizeof(SnapshotInfo));
1021 info->id = g_strdup(sn.id_str);
1022 info->name = g_strdup(sn.name);
1023 info->date_nsec = sn.date_nsec;
1024 info->date_sec = sn.date_sec;
1025 info->vm_state_size = sn.vm_state_size;
1026 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1027 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1028
1029 return info;
1030}
8802d1fd
JC
1031
1032/* New and old BlockDriverState structs for group snapshots */
ba0c86a3 1033
ba5d6ab6 1034typedef struct BlkTransactionState BlkTransactionState;
ba0c86a3
WX
1035
1036/* Only prepare() may fail. In a single transaction, only one of commit() or
1037 abort() will be called, clean() will always be called if it present. */
1038typedef struct BdrvActionOps {
1039 /* Size of state struct, in bytes. */
1040 size_t instance_size;
1041 /* Prepare the work, must NOT be NULL. */
ba5d6ab6 1042 void (*prepare)(BlkTransactionState *common, Error **errp);
f9ea81e8 1043 /* Commit the changes, can be NULL. */
ba5d6ab6 1044 void (*commit)(BlkTransactionState *common);
ba0c86a3 1045 /* Abort the changes on fail, can be NULL. */
ba5d6ab6 1046 void (*abort)(BlkTransactionState *common);
ba0c86a3 1047 /* Clean up resource in the end, can be NULL. */
ba5d6ab6 1048 void (*clean)(BlkTransactionState *common);
ba0c86a3
WX
1049} BdrvActionOps;
1050
1051/*
1052 * This structure must be arranged as first member in child type, assuming
1053 * that compiler will also arrange it to the same address with parent instance.
1054 * Later it will be used in free().
1055 */
ba5d6ab6 1056struct BlkTransactionState {
c8a83e85 1057 TransactionAction *action;
ba0c86a3 1058 const BdrvActionOps *ops;
ba5d6ab6 1059 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
ba0c86a3
WX
1060};
1061
bbe86010
WX
1062/* internal snapshot private data */
1063typedef struct InternalSnapshotState {
1064 BlkTransactionState common;
1065 BlockDriverState *bs;
1066 QEMUSnapshotInfo sn;
1067} InternalSnapshotState;
1068
1069static void internal_snapshot_prepare(BlkTransactionState *common,
1070 Error **errp)
1071{
1072 const char *device;
1073 const char *name;
1074 BlockDriverState *bs;
1075 QEMUSnapshotInfo old_sn, *sn;
1076 bool ret;
1077 qemu_timeval tv;
1078 BlockdevSnapshotInternal *internal;
1079 InternalSnapshotState *state;
1080 int ret1;
1081
1082 g_assert(common->action->kind ==
1083 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1084 internal = common->action->blockdev_snapshot_internal_sync;
1085 state = DO_UPCAST(InternalSnapshotState, common, common);
1086
1087 /* 1. parse input */
1088 device = internal->device;
1089 name = internal->name;
1090
1091 /* 2. check for validation */
1092 bs = bdrv_find(device);
1093 if (!bs) {
1094 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1095 return;
1096 }
1097
1098 if (!bdrv_is_inserted(bs)) {
1099 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1100 return;
1101 }
1102
1103 if (bdrv_is_read_only(bs)) {
1104 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1105 return;
1106 }
1107
1108 if (!bdrv_can_snapshot(bs)) {
1109 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1110 bs->drv->format_name, device, "internal snapshot");
1111 return;
1112 }
1113
1114 if (!strlen(name)) {
1115 error_setg(errp, "Name is empty");
1116 return;
1117 }
1118
1119 /* check whether a snapshot with name exist */
1120 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn, errp);
1121 if (error_is_set(errp)) {
1122 return;
1123 } else if (ret) {
1124 error_setg(errp,
1125 "Snapshot with name '%s' already exists on device '%s'",
1126 name, device);
1127 return;
1128 }
1129
1130 /* 3. take the snapshot */
1131 sn = &state->sn;
1132 pstrcpy(sn->name, sizeof(sn->name), name);
1133 qemu_gettimeofday(&tv);
1134 sn->date_sec = tv.tv_sec;
1135 sn->date_nsec = tv.tv_usec * 1000;
1136 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1137
1138 ret1 = bdrv_snapshot_create(bs, sn);
1139 if (ret1 < 0) {
1140 error_setg_errno(errp, -ret1,
1141 "Failed to create snapshot '%s' on device '%s'",
1142 name, device);
1143 return;
1144 }
1145
1146 /* 4. succeed, mark a snapshot is created */
1147 state->bs = bs;
1148}
1149
1150static void internal_snapshot_abort(BlkTransactionState *common)
1151{
1152 InternalSnapshotState *state =
1153 DO_UPCAST(InternalSnapshotState, common, common);
1154 BlockDriverState *bs = state->bs;
1155 QEMUSnapshotInfo *sn = &state->sn;
1156 Error *local_error = NULL;
1157
1158 if (!bs) {
1159 return;
1160 }
1161
1162 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1163 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1164 "device '%s' in abort: %s",
1165 sn->id_str,
1166 sn->name,
1167 bdrv_get_device_name(bs),
1168 error_get_pretty(local_error));
1169 error_free(local_error);
1170 }
1171}
1172
ba0c86a3 1173/* external snapshot private data */
ba5d6ab6
SH
1174typedef struct ExternalSnapshotState {
1175 BlkTransactionState common;
8802d1fd
JC
1176 BlockDriverState *old_bs;
1177 BlockDriverState *new_bs;
ba5d6ab6 1178} ExternalSnapshotState;
8802d1fd 1179
ba5d6ab6 1180static void external_snapshot_prepare(BlkTransactionState *common,
9b9877ee
WX
1181 Error **errp)
1182{
9b9877ee
WX
1183 BlockDriver *drv;
1184 int flags, ret;
1185 Error *local_err = NULL;
e2a31e87
WX
1186 const char *device;
1187 const char *new_image_file;
1188 const char *format = "qcow2";
1189 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
ba5d6ab6
SH
1190 ExternalSnapshotState *state =
1191 DO_UPCAST(ExternalSnapshotState, common, common);
c8a83e85 1192 TransactionAction *action = common->action;
9b9877ee 1193
e2a31e87 1194 /* get parameters */
c8a83e85 1195 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
e2a31e87
WX
1196
1197 device = action->blockdev_snapshot_sync->device;
1198 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1199 if (action->blockdev_snapshot_sync->has_format) {
1200 format = action->blockdev_snapshot_sync->format;
1201 }
1202 if (action->blockdev_snapshot_sync->has_mode) {
1203 mode = action->blockdev_snapshot_sync->mode;
1204 }
1205
1206 /* start processing */
9b9877ee
WX
1207 drv = bdrv_find_format(format);
1208 if (!drv) {
1209 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1210 return;
1211 }
1212
ba5d6ab6
SH
1213 state->old_bs = bdrv_find(device);
1214 if (!state->old_bs) {
9b9877ee
WX
1215 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1216 return;
1217 }
1218
ba5d6ab6 1219 if (!bdrv_is_inserted(state->old_bs)) {
9b9877ee
WX
1220 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1221 return;
1222 }
1223
ba5d6ab6 1224 if (bdrv_in_use(state->old_bs)) {
9b9877ee
WX
1225 error_set(errp, QERR_DEVICE_IN_USE, device);
1226 return;
1227 }
1228
ba5d6ab6
SH
1229 if (!bdrv_is_read_only(state->old_bs)) {
1230 if (bdrv_flush(state->old_bs)) {
9b9877ee
WX
1231 error_set(errp, QERR_IO_ERROR);
1232 return;
1233 }
1234 }
1235
f6186f49
BC
1236 if (bdrv_check_ext_snapshot(state->old_bs) != EXT_SNAPSHOT_ALLOWED) {
1237 error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1238 return;
1239 }
1240
ba5d6ab6 1241 flags = state->old_bs->open_flags;
9b9877ee 1242
9b9877ee
WX
1243 /* create new image w/backing file */
1244 if (mode != NEW_IMAGE_MODE_EXISTING) {
1245 bdrv_img_create(new_image_file, format,
ba5d6ab6
SH
1246 state->old_bs->filename,
1247 state->old_bs->drv->format_name,
9b9877ee
WX
1248 NULL, -1, flags, &local_err, false);
1249 if (error_is_set(&local_err)) {
1250 error_propagate(errp, local_err);
1251 return;
1252 }
1253 }
1254
1255 /* We will manually add the backing_hd field to the bs later */
ba5d6ab6 1256 state->new_bs = bdrv_new("");
9b9877ee
WX
1257 /* TODO Inherit bs->options or only take explicit options with an
1258 * extended QMP command? */
ba5d6ab6 1259 ret = bdrv_open(state->new_bs, new_image_file, NULL,
34b5d2c6 1260 flags | BDRV_O_NO_BACKING, drv, &local_err);
9b9877ee 1261 if (ret != 0) {
34b5d2c6 1262 error_propagate(errp, local_err);
9b9877ee
WX
1263 }
1264}
1265
ba5d6ab6 1266static void external_snapshot_commit(BlkTransactionState *common)
3b0047e8 1267{
ba5d6ab6
SH
1268 ExternalSnapshotState *state =
1269 DO_UPCAST(ExternalSnapshotState, common, common);
ba0c86a3 1270
ba5d6ab6
SH
1271 /* This removes our old bs and adds the new bs */
1272 bdrv_append(state->new_bs, state->old_bs);
3b0047e8
WX
1273 /* We don't need (or want) to use the transactional
1274 * bdrv_reopen_multiple() across all the entries at once, because we
1275 * don't want to abort all of them if one of them fails the reopen */
ba5d6ab6 1276 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
3b0047e8
WX
1277 NULL);
1278}
1279
ba5d6ab6 1280static void external_snapshot_abort(BlkTransactionState *common)
96b86bf7 1281{
ba5d6ab6
SH
1282 ExternalSnapshotState *state =
1283 DO_UPCAST(ExternalSnapshotState, common, common);
1284 if (state->new_bs) {
4f6fd349 1285 bdrv_unref(state->new_bs);
96b86bf7
WX
1286 }
1287}
1288
3037f364
SH
1289typedef struct DriveBackupState {
1290 BlkTransactionState common;
1291 BlockDriverState *bs;
1292 BlockJob *job;
1293} DriveBackupState;
1294
1295static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1296{
1297 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1298 DriveBackup *backup;
1299 Error *local_err = NULL;
1300
1301 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1302 backup = common->action->drive_backup;
1303
1304 qmp_drive_backup(backup->device, backup->target,
1305 backup->has_format, backup->format,
b53169ea 1306 backup->sync,
3037f364
SH
1307 backup->has_mode, backup->mode,
1308 backup->has_speed, backup->speed,
1309 backup->has_on_source_error, backup->on_source_error,
1310 backup->has_on_target_error, backup->on_target_error,
1311 &local_err);
1312 if (error_is_set(&local_err)) {
1313 error_propagate(errp, local_err);
1314 state->bs = NULL;
1315 state->job = NULL;
1316 return;
1317 }
1318
1319 state->bs = bdrv_find(backup->device);
1320 state->job = state->bs->job;
1321}
1322
1323static void drive_backup_abort(BlkTransactionState *common)
1324{
1325 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1326 BlockDriverState *bs = state->bs;
1327
1328 /* Only cancel if it's the job we started */
1329 if (bs && bs->job && bs->job == state->job) {
1330 block_job_cancel_sync(bs->job);
1331 }
1332}
1333
78b18b78
SH
1334static void abort_prepare(BlkTransactionState *common, Error **errp)
1335{
1336 error_setg(errp, "Transaction aborted using Abort action");
1337}
1338
1339static void abort_commit(BlkTransactionState *common)
1340{
dfc6f865 1341 g_assert_not_reached(); /* this action never succeeds */
78b18b78
SH
1342}
1343
ba0c86a3 1344static const BdrvActionOps actions[] = {
c8a83e85 1345 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
ba5d6ab6 1346 .instance_size = sizeof(ExternalSnapshotState),
ba0c86a3
WX
1347 .prepare = external_snapshot_prepare,
1348 .commit = external_snapshot_commit,
1349 .abort = external_snapshot_abort,
1350 },
3037f364
SH
1351 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1352 .instance_size = sizeof(DriveBackupState),
1353 .prepare = drive_backup_prepare,
1354 .abort = drive_backup_abort,
1355 },
78b18b78
SH
1356 [TRANSACTION_ACTION_KIND_ABORT] = {
1357 .instance_size = sizeof(BlkTransactionState),
1358 .prepare = abort_prepare,
1359 .commit = abort_commit,
1360 },
bbe86010
WX
1361 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1362 .instance_size = sizeof(InternalSnapshotState),
1363 .prepare = internal_snapshot_prepare,
1364 .abort = internal_snapshot_abort,
1365 },
ba0c86a3
WX
1366};
1367
8802d1fd
JC
1368/*
1369 * 'Atomic' group snapshots. The snapshots are taken as a set, and if any fail
1370 * then we do not pivot any of the devices in the group, and abandon the
1371 * snapshots
1372 */
c8a83e85 1373void qmp_transaction(TransactionActionList *dev_list, Error **errp)
8802d1fd 1374{
c8a83e85 1375 TransactionActionList *dev_entry = dev_list;
ba5d6ab6 1376 BlkTransactionState *state, *next;
43e17041 1377 Error *local_err = NULL;
8802d1fd 1378
ba5d6ab6 1379 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
8802d1fd
JC
1380 QSIMPLEQ_INIT(&snap_bdrv_states);
1381
1382 /* drain all i/o before any snapshots */
1383 bdrv_drain_all();
1384
1385 /* We don't do anything in this loop that commits us to the snapshot */
1386 while (NULL != dev_entry) {
c8a83e85 1387 TransactionAction *dev_info = NULL;
ba0c86a3 1388 const BdrvActionOps *ops;
52e7c241 1389
8802d1fd
JC
1390 dev_info = dev_entry->value;
1391 dev_entry = dev_entry->next;
1392
ba0c86a3
WX
1393 assert(dev_info->kind < ARRAY_SIZE(actions));
1394
1395 ops = &actions[dev_info->kind];
aa3fe714
MR
1396 assert(ops->instance_size > 0);
1397
ba5d6ab6
SH
1398 state = g_malloc0(ops->instance_size);
1399 state->ops = ops;
1400 state->action = dev_info;
1401 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
8802d1fd 1402
ba5d6ab6 1403 state->ops->prepare(state, &local_err);
ba0c86a3
WX
1404 if (error_is_set(&local_err)) {
1405 error_propagate(errp, local_err);
1406 goto delete_and_fail;
8802d1fd 1407 }
8802d1fd
JC
1408 }
1409
ba5d6ab6 1410 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
f9ea81e8
SH
1411 if (state->ops->commit) {
1412 state->ops->commit(state);
1413 }
8802d1fd
JC
1414 }
1415
1416 /* success */
1417 goto exit;
1418
1419delete_and_fail:
1420 /*
1421 * failure, and it is all-or-none; abandon each new bs, and keep using
1422 * the original bs for all images
1423 */
ba5d6ab6
SH
1424 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1425 if (state->ops->abort) {
1426 state->ops->abort(state);
ba0c86a3 1427 }
8802d1fd
JC
1428 }
1429exit:
ba5d6ab6
SH
1430 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1431 if (state->ops->clean) {
1432 state->ops->clean(state);
ba0c86a3 1433 }
ba5d6ab6 1434 g_free(state);
8802d1fd 1435 }
8802d1fd
JC
1436}
1437
1438
92d48558 1439static void eject_device(BlockDriverState *bs, int force, Error **errp)
666daa68 1440{
2d3735d3
SH
1441 if (bdrv_in_use(bs)) {
1442 error_set(errp, QERR_DEVICE_IN_USE, bdrv_get_device_name(bs));
1443 return;
1444 }
2c6942fa 1445 if (!bdrv_dev_has_removable_media(bs)) {
92d48558
LC
1446 error_set(errp, QERR_DEVICE_NOT_REMOVABLE, bdrv_get_device_name(bs));
1447 return;
ea8f942f 1448 }
92d48558 1449
025ccaa7
PB
1450 if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
1451 bdrv_dev_eject_request(bs, force);
1452 if (!force) {
92d48558
LC
1453 error_set(errp, QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
1454 return;
025ccaa7 1455 }
666daa68 1456 }
92d48558 1457
3b5276b5 1458 bdrv_close(bs);
666daa68
MA
1459}
1460
c245b6a3 1461void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
666daa68
MA
1462{
1463 BlockDriverState *bs;
666daa68 1464
c245b6a3 1465 bs = bdrv_find(device);
666daa68 1466 if (!bs) {
c245b6a3
LC
1467 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1468 return;
92d48558
LC
1469 }
1470
c245b6a3 1471 eject_device(bs, force, errp);
666daa68
MA
1472}
1473
a4dea8a9 1474void qmp_block_passwd(const char *device, const char *password, Error **errp)
666daa68
MA
1475{
1476 BlockDriverState *bs;
1477 int err;
1478
a4dea8a9 1479 bs = bdrv_find(device);
666daa68 1480 if (!bs) {
a4dea8a9
LC
1481 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1482 return;
666daa68
MA
1483 }
1484
a4dea8a9 1485 err = bdrv_set_key(bs, password);
666daa68 1486 if (err == -EINVAL) {
a4dea8a9
LC
1487 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1488 return;
666daa68 1489 } else if (err < 0) {
a4dea8a9
LC
1490 error_set(errp, QERR_INVALID_PASSWORD);
1491 return;
666daa68 1492 }
666daa68
MA
1493}
1494
333a96ec
LC
1495static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1496 int bdrv_flags, BlockDriver *drv,
1497 const char *password, Error **errp)
1498{
34b5d2c6 1499 Error *local_err = NULL;
0eef407c
LC
1500 int ret;
1501
34b5d2c6 1502 ret = bdrv_open(bs, filename, NULL, bdrv_flags, drv, &local_err);
0eef407c 1503 if (ret < 0) {
34b5d2c6 1504 error_propagate(errp, local_err);
333a96ec
LC
1505 return;
1506 }
1507
1508 if (bdrv_key_required(bs)) {
1509 if (password) {
1510 if (bdrv_set_key(bs, password) < 0) {
1511 error_set(errp, QERR_INVALID_PASSWORD);
1512 }
1513 } else {
1514 error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1515 bdrv_get_encrypted_filename(bs));
1516 }
1517 } else if (password) {
1518 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1519 }
1520}
1521
1522void qmp_change_blockdev(const char *device, const char *filename,
1523 bool has_format, const char *format, Error **errp)
666daa68
MA
1524{
1525 BlockDriverState *bs;
1526 BlockDriver *drv = NULL;
1527 int bdrv_flags;
92d48558 1528 Error *err = NULL;
666daa68
MA
1529
1530 bs = bdrv_find(device);
1531 if (!bs) {
333a96ec
LC
1532 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1533 return;
666daa68 1534 }
333a96ec
LC
1535
1536 if (format) {
b64ec4e4 1537 drv = bdrv_find_whitelisted_format(format, bs->read_only);
666daa68 1538 if (!drv) {
333a96ec
LC
1539 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1540 return;
666daa68
MA
1541 }
1542 }
333a96ec 1543
92d48558
LC
1544 eject_device(bs, 0, &err);
1545 if (error_is_set(&err)) {
333a96ec
LC
1546 error_propagate(errp, err);
1547 return;
666daa68 1548 }
333a96ec 1549
528f7663 1550 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
199630b6 1551 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
333a96ec
LC
1552
1553 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
666daa68 1554}
9063f814 1555
727f005e 1556/* throttling disk I/O limits */
80047da5 1557void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
3e9fab69
BC
1558 int64_t bps_wr,
1559 int64_t iops,
1560 int64_t iops_rd,
1561 int64_t iops_wr,
1562 bool has_bps_max,
1563 int64_t bps_max,
1564 bool has_bps_rd_max,
1565 int64_t bps_rd_max,
1566 bool has_bps_wr_max,
1567 int64_t bps_wr_max,
1568 bool has_iops_max,
1569 int64_t iops_max,
1570 bool has_iops_rd_max,
1571 int64_t iops_rd_max,
1572 bool has_iops_wr_max,
2024c1df
BC
1573 int64_t iops_wr_max,
1574 bool has_iops_size,
1575 int64_t iops_size, Error **errp)
727f005e 1576{
cc0681c4 1577 ThrottleConfig cfg;
727f005e
ZYW
1578 BlockDriverState *bs;
1579
80047da5 1580 bs = bdrv_find(device);
727f005e 1581 if (!bs) {
80047da5
LC
1582 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1583 return;
727f005e
ZYW
1584 }
1585
cc0681c4
BC
1586 memset(&cfg, 0, sizeof(cfg));
1587 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1588 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1589 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1590
1591 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1592 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1593 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1594
3e9fab69
BC
1595 if (has_bps_max) {
1596 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1597 }
1598 if (has_bps_rd_max) {
1599 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1600 }
1601 if (has_bps_wr_max) {
1602 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1603 }
1604 if (has_iops_max) {
1605 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1606 }
1607 if (has_iops_rd_max) {
1608 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1609 }
1610 if (has_iops_wr_max) {
1611 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1612 }
727f005e 1613
2024c1df
BC
1614 if (has_iops_size) {
1615 cfg.op_size = iops_size;
1616 }
cc0681c4
BC
1617
1618 if (!check_throttle_config(&cfg, errp)) {
80047da5 1619 return;
727f005e
ZYW
1620 }
1621
cc0681c4 1622 if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
727f005e 1623 bdrv_io_limits_enable(bs);
cc0681c4 1624 } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
727f005e 1625 bdrv_io_limits_disable(bs);
cc0681c4
BC
1626 }
1627
1628 if (bs->io_limits_enabled) {
1629 bdrv_set_io_limits(bs, &cfg);
727f005e 1630 }
727f005e
ZYW
1631}
1632
9063f814
RH
1633int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1634{
1635 const char *id = qdict_get_str(qdict, "id");
1636 BlockDriverState *bs;
9063f814
RH
1637
1638 bs = bdrv_find(id);
1639 if (!bs) {
1640 qerror_report(QERR_DEVICE_NOT_FOUND, id);
1641 return -1;
1642 }
8591675f
MT
1643 if (bdrv_in_use(bs)) {
1644 qerror_report(QERR_DEVICE_IN_USE, id);
1645 return -1;
1646 }
9063f814
RH
1647
1648 /* quiesce block driver; prevent further io */
922453bc 1649 bdrv_drain_all();
9063f814
RH
1650 bdrv_flush(bs);
1651 bdrv_close(bs);
1652
fa879d62 1653 /* if we have a device attached to this BlockDriverState
d22b2f41
RH
1654 * then we need to make the drive anonymous until the device
1655 * can be removed. If this is a drive with no device backing
1656 * then we can just get rid of the block driver state right here.
1657 */
fa879d62 1658 if (bdrv_get_attached_dev(bs)) {
d22b2f41 1659 bdrv_make_anon(bs);
293c51a6
SH
1660
1661 /* Further I/O must not pause the guest */
1662 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1663 BLOCKDEV_ON_ERROR_REPORT);
d22b2f41
RH
1664 } else {
1665 drive_uninit(drive_get_by_blockdev(bs));
9063f814
RH
1666 }
1667
9063f814
RH
1668 return 0;
1669}
6d4a2b3a 1670
5e7caacb 1671void qmp_block_resize(const char *device, int64_t size, Error **errp)
6d4a2b3a 1672{
6d4a2b3a 1673 BlockDriverState *bs;
8732901e 1674 int ret;
6d4a2b3a
CH
1675
1676 bs = bdrv_find(device);
1677 if (!bs) {
5e7caacb
LC
1678 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1679 return;
6d4a2b3a
CH
1680 }
1681
1682 if (size < 0) {
939a1cc3 1683 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
5e7caacb 1684 return;
6d4a2b3a
CH
1685 }
1686
92b7a08d
PL
1687 /* complete all in-flight operations before resizing the device */
1688 bdrv_drain_all();
1689
8732901e
KW
1690 ret = bdrv_truncate(bs, size);
1691 switch (ret) {
939a1cc3
SH
1692 case 0:
1693 break;
1694 case -ENOMEDIUM:
1695 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1696 break;
1697 case -ENOTSUP:
1698 error_set(errp, QERR_UNSUPPORTED);
1699 break;
1700 case -EACCES:
1701 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1702 break;
1703 case -EBUSY:
1704 error_set(errp, QERR_DEVICE_IN_USE, device);
1705 break;
1706 default:
8732901e 1707 error_setg_errno(errp, -ret, "Could not resize");
939a1cc3 1708 break;
6d4a2b3a 1709 }
6d4a2b3a 1710}
12bd451f 1711
9abf2dba 1712static void block_job_cb(void *opaque, int ret)
12bd451f
SH
1713{
1714 BlockDriverState *bs = opaque;
1715 QObject *obj;
1716
9abf2dba 1717 trace_block_job_cb(bs, bs->job, ret);
12bd451f
SH
1718
1719 assert(bs->job);
1720 obj = qobject_from_block_job(bs->job);
1721 if (ret < 0) {
1722 QDict *dict = qobject_to_qdict(obj);
1723 qdict_put(dict, "error", qstring_from_str(strerror(-ret)));
1724 }
1725
370521a1
SH
1726 if (block_job_is_cancelled(bs->job)) {
1727 monitor_protocol_event(QEVENT_BLOCK_JOB_CANCELLED, obj);
1728 } else {
1729 monitor_protocol_event(QEVENT_BLOCK_JOB_COMPLETED, obj);
1730 }
12bd451f 1731 qobject_decref(obj);
aa398a5c 1732
fa510ebf 1733 bdrv_put_ref_bh_schedule(bs);
12bd451f
SH
1734}
1735
1736void qmp_block_stream(const char *device, bool has_base,
1d809098
PB
1737 const char *base, bool has_speed, int64_t speed,
1738 bool has_on_error, BlockdevOnError on_error,
1739 Error **errp)
12bd451f
SH
1740{
1741 BlockDriverState *bs;
c8c3080f 1742 BlockDriverState *base_bs = NULL;
fd7f8c65 1743 Error *local_err = NULL;
12bd451f 1744
1d809098
PB
1745 if (!has_on_error) {
1746 on_error = BLOCKDEV_ON_ERROR_REPORT;
1747 }
1748
12bd451f
SH
1749 bs = bdrv_find(device);
1750 if (!bs) {
1751 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1752 return;
1753 }
1754
12bd451f 1755 if (base) {
c8c3080f
MT
1756 base_bs = bdrv_find_backing_image(bs, base);
1757 if (base_bs == NULL) {
1758 error_set(errp, QERR_BASE_NOT_FOUND, base);
1759 return;
1760 }
12bd451f
SH
1761 }
1762
c83c66c3 1763 stream_start(bs, base_bs, base, has_speed ? speed : 0,
1d809098 1764 on_error, block_job_cb, bs, &local_err);
fd7f8c65
SH
1765 if (error_is_set(&local_err)) {
1766 error_propagate(errp, local_err);
1767 return;
12bd451f
SH
1768 }
1769
1770 trace_qmp_block_stream(bs, bs->job);
1771}
2d47c6e9 1772
ed61fc10
JC
1773void qmp_block_commit(const char *device,
1774 bool has_base, const char *base, const char *top,
1775 bool has_speed, int64_t speed,
1776 Error **errp)
1777{
1778 BlockDriverState *bs;
1779 BlockDriverState *base_bs, *top_bs;
1780 Error *local_err = NULL;
1781 /* This will be part of the QMP command, if/when the
1782 * BlockdevOnError change for blkmirror makes it in
1783 */
92aa5c6d 1784 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
ed61fc10
JC
1785
1786 /* drain all i/o before commits */
1787 bdrv_drain_all();
1788
1789 bs = bdrv_find(device);
1790 if (!bs) {
1791 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1792 return;
1793 }
ed61fc10
JC
1794
1795 /* default top_bs is the active layer */
1796 top_bs = bs;
1797
1798 if (top) {
1799 if (strcmp(bs->filename, top) != 0) {
1800 top_bs = bdrv_find_backing_image(bs, top);
1801 }
1802 }
1803
1804 if (top_bs == NULL) {
1805 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
1806 return;
1807 }
1808
d5208c45
JC
1809 if (has_base && base) {
1810 base_bs = bdrv_find_backing_image(top_bs, base);
1811 } else {
1812 base_bs = bdrv_find_base(top_bs);
1813 }
1814
1815 if (base_bs == NULL) {
1816 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
1817 return;
1818 }
1819
ed61fc10
JC
1820 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
1821 &local_err);
1822 if (local_err != NULL) {
1823 error_propagate(errp, local_err);
1824 return;
1825 }
ed61fc10
JC
1826}
1827
99a9addf
SH
1828void qmp_drive_backup(const char *device, const char *target,
1829 bool has_format, const char *format,
b53169ea 1830 enum MirrorSyncMode sync,
99a9addf
SH
1831 bool has_mode, enum NewImageMode mode,
1832 bool has_speed, int64_t speed,
1833 bool has_on_source_error, BlockdevOnError on_source_error,
1834 bool has_on_target_error, BlockdevOnError on_target_error,
1835 Error **errp)
1836{
1837 BlockDriverState *bs;
1838 BlockDriverState *target_bs;
fc5d3f84 1839 BlockDriverState *source = NULL;
99a9addf
SH
1840 BlockDriver *drv = NULL;
1841 Error *local_err = NULL;
1842 int flags;
1843 int64_t size;
1844 int ret;
1845
1846 if (!has_speed) {
1847 speed = 0;
1848 }
1849 if (!has_on_source_error) {
1850 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
1851 }
1852 if (!has_on_target_error) {
1853 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
1854 }
1855 if (!has_mode) {
1856 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1857 }
1858
1859 bs = bdrv_find(device);
1860 if (!bs) {
1861 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1862 return;
1863 }
1864
1865 if (!bdrv_is_inserted(bs)) {
1866 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1867 return;
1868 }
1869
1870 if (!has_format) {
1871 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
1872 }
1873 if (format) {
1874 drv = bdrv_find_format(format);
1875 if (!drv) {
1876 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1877 return;
1878 }
1879 }
1880
1881 if (bdrv_in_use(bs)) {
1882 error_set(errp, QERR_DEVICE_IN_USE, device);
1883 return;
1884 }
1885
1886 flags = bs->open_flags | BDRV_O_RDWR;
1887
fc5d3f84
IM
1888 /* See if we have a backing HD we can use to create our new image
1889 * on top of. */
1890 if (sync == MIRROR_SYNC_MODE_TOP) {
1891 source = bs->backing_hd;
1892 if (!source) {
1893 sync = MIRROR_SYNC_MODE_FULL;
1894 }
1895 }
1896 if (sync == MIRROR_SYNC_MODE_NONE) {
1897 source = bs;
1898 }
1899
99a9addf
SH
1900 size = bdrv_getlength(bs);
1901 if (size < 0) {
1902 error_setg_errno(errp, -size, "bdrv_getlength failed");
1903 return;
1904 }
1905
1906 if (mode != NEW_IMAGE_MODE_EXISTING) {
1907 assert(format && drv);
fc5d3f84
IM
1908 if (source) {
1909 bdrv_img_create(target, format, source->filename,
1910 source->drv->format_name, NULL,
1911 size, flags, &local_err, false);
1912 } else {
1913 bdrv_img_create(target, format, NULL, NULL, NULL,
1914 size, flags, &local_err, false);
1915 }
99a9addf
SH
1916 }
1917
1918 if (error_is_set(&local_err)) {
1919 error_propagate(errp, local_err);
1920 return;
1921 }
1922
1923 target_bs = bdrv_new("");
34b5d2c6 1924 ret = bdrv_open(target_bs, target, NULL, flags, drv, &local_err);
99a9addf 1925 if (ret < 0) {
4f6fd349 1926 bdrv_unref(target_bs);
34b5d2c6 1927 error_propagate(errp, local_err);
99a9addf
SH
1928 return;
1929 }
1930
fc5d3f84 1931 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
99a9addf
SH
1932 block_job_cb, bs, &local_err);
1933 if (local_err != NULL) {
4f6fd349 1934 bdrv_unref(target_bs);
99a9addf
SH
1935 error_propagate(errp, local_err);
1936 return;
1937 }
99a9addf
SH
1938}
1939
08e4ed6c
PB
1940#define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
1941
d9b902db
PB
1942void qmp_drive_mirror(const char *device, const char *target,
1943 bool has_format, const char *format,
1944 enum MirrorSyncMode sync,
1945 bool has_mode, enum NewImageMode mode,
b952b558 1946 bool has_speed, int64_t speed,
eee13dfe 1947 bool has_granularity, uint32_t granularity,
08e4ed6c 1948 bool has_buf_size, int64_t buf_size,
b952b558
PB
1949 bool has_on_source_error, BlockdevOnError on_source_error,
1950 bool has_on_target_error, BlockdevOnError on_target_error,
1951 Error **errp)
d9b902db 1952{
d9b902db
PB
1953 BlockDriverState *bs;
1954 BlockDriverState *source, *target_bs;
d9b902db
PB
1955 BlockDriver *drv = NULL;
1956 Error *local_err = NULL;
1957 int flags;
ac3c5d83 1958 int64_t size;
d9b902db
PB
1959 int ret;
1960
1961 if (!has_speed) {
1962 speed = 0;
1963 }
b952b558
PB
1964 if (!has_on_source_error) {
1965 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
1966 }
1967 if (!has_on_target_error) {
1968 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
1969 }
d9b902db
PB
1970 if (!has_mode) {
1971 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1972 }
eee13dfe
PB
1973 if (!has_granularity) {
1974 granularity = 0;
1975 }
08e4ed6c
PB
1976 if (!has_buf_size) {
1977 buf_size = DEFAULT_MIRROR_BUF_SIZE;
1978 }
1979
eee13dfe
PB
1980 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
1981 error_set(errp, QERR_INVALID_PARAMETER, device);
1982 return;
1983 }
1984 if (granularity & (granularity - 1)) {
1985 error_set(errp, QERR_INVALID_PARAMETER, device);
1986 return;
1987 }
d9b902db
PB
1988
1989 bs = bdrv_find(device);
1990 if (!bs) {
1991 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1992 return;
1993 }
1994
1995 if (!bdrv_is_inserted(bs)) {
1996 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1997 return;
1998 }
1999
2000 if (!has_format) {
2001 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2002 }
2003 if (format) {
2004 drv = bdrv_find_format(format);
2005 if (!drv) {
2006 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2007 return;
2008 }
2009 }
2010
2011 if (bdrv_in_use(bs)) {
2012 error_set(errp, QERR_DEVICE_IN_USE, device);
2013 return;
2014 }
2015
2016 flags = bs->open_flags | BDRV_O_RDWR;
2017 source = bs->backing_hd;
2018 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2019 sync = MIRROR_SYNC_MODE_FULL;
2020 }
2021
ac3c5d83
SH
2022 size = bdrv_getlength(bs);
2023 if (size < 0) {
2024 error_setg_errno(errp, -size, "bdrv_getlength failed");
2025 return;
2026 }
2027
d9b902db
PB
2028 if (sync == MIRROR_SYNC_MODE_FULL && mode != NEW_IMAGE_MODE_EXISTING) {
2029 /* create new image w/o backing file */
2030 assert(format && drv);
cf8f2426 2031 bdrv_img_create(target, format,
f382d43a 2032 NULL, NULL, NULL, size, flags, &local_err, false);
d9b902db
PB
2033 } else {
2034 switch (mode) {
2035 case NEW_IMAGE_MODE_EXISTING:
d9b902db
PB
2036 break;
2037 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2038 /* create new image with backing file */
cf8f2426
LC
2039 bdrv_img_create(target, format,
2040 source->filename,
2041 source->drv->format_name,
f382d43a 2042 NULL, size, flags, &local_err, false);
d9b902db
PB
2043 break;
2044 default:
2045 abort();
2046 }
2047 }
2048
cf8f2426
LC
2049 if (error_is_set(&local_err)) {
2050 error_propagate(errp, local_err);
d9b902db
PB
2051 return;
2052 }
2053
b812f671
PB
2054 /* Mirroring takes care of copy-on-write using the source's backing
2055 * file.
2056 */
d9b902db 2057 target_bs = bdrv_new("");
34b5d2c6
MR
2058 ret = bdrv_open(target_bs, target, NULL, flags | BDRV_O_NO_BACKING, drv,
2059 &local_err);
d9b902db 2060 if (ret < 0) {
4f6fd349 2061 bdrv_unref(target_bs);
34b5d2c6 2062 error_propagate(errp, local_err);
d9b902db
PB
2063 return;
2064 }
2065
08e4ed6c 2066 mirror_start(bs, target_bs, speed, granularity, buf_size, sync,
eee13dfe 2067 on_source_error, on_target_error,
b952b558 2068 block_job_cb, bs, &local_err);
d9b902db 2069 if (local_err != NULL) {
4f6fd349 2070 bdrv_unref(target_bs);
d9b902db
PB
2071 error_propagate(errp, local_err);
2072 return;
2073 }
d9b902db
PB
2074}
2075
2d47c6e9
SH
2076static BlockJob *find_block_job(const char *device)
2077{
2078 BlockDriverState *bs;
2079
2080 bs = bdrv_find(device);
2081 if (!bs || !bs->job) {
2082 return NULL;
2083 }
2084 return bs->job;
2085}
2086
882ec7ce 2087void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2d47c6e9
SH
2088{
2089 BlockJob *job = find_block_job(device);
2090
2091 if (!job) {
7ef15070 2092 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2d47c6e9
SH
2093 return;
2094 }
2095
882ec7ce 2096 block_job_set_speed(job, speed, errp);
2d47c6e9 2097}
370521a1 2098
6e37fb81
PB
2099void qmp_block_job_cancel(const char *device,
2100 bool has_force, bool force, Error **errp)
370521a1
SH
2101{
2102 BlockJob *job = find_block_job(device);
2103
6e37fb81
PB
2104 if (!has_force) {
2105 force = false;
2106 }
2107
370521a1 2108 if (!job) {
7ef15070 2109 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
370521a1
SH
2110 return;
2111 }
6e37fb81 2112 if (job->paused && !force) {
8acc72a4
PB
2113 error_set(errp, QERR_BLOCK_JOB_PAUSED, device);
2114 return;
2115 }
370521a1
SH
2116
2117 trace_qmp_block_job_cancel(job);
2118 block_job_cancel(job);
2119}
fb5458cd 2120
6e37fb81
PB
2121void qmp_block_job_pause(const char *device, Error **errp)
2122{
2123 BlockJob *job = find_block_job(device);
2124
2125 if (!job) {
2126 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2127 return;
2128 }
2129
2130 trace_qmp_block_job_pause(job);
2131 block_job_pause(job);
2132}
2133
2134void qmp_block_job_resume(const char *device, Error **errp)
2135{
2136 BlockJob *job = find_block_job(device);
2137
2138 if (!job) {
2139 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2140 return;
2141 }
2142
2143 trace_qmp_block_job_resume(job);
2144 block_job_resume(job);
2145}
2146
aeae883b
PB
2147void qmp_block_job_complete(const char *device, Error **errp)
2148{
2149 BlockJob *job = find_block_job(device);
2150
2151 if (!job) {
2152 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2153 return;
2154 }
2155
2156 trace_qmp_block_job_complete(job);
2157 block_job_complete(job, errp);
2158}
2159
d26c9a15
KW
2160void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2161{
2162 QmpOutputVisitor *ov = qmp_output_visitor_new();
2163 QObject *obj;
2164 QDict *qdict;
d26c9a15
KW
2165 Error *local_err = NULL;
2166
2167 /* Require an ID in the top level */
2168 if (!options->has_id) {
2169 error_setg(errp, "Block device needs an ID");
2170 goto fail;
2171 }
2172
2173 /* TODO Sort it out in raw-posix and drive_init: Reject aio=native with
2174 * cache.direct=false instead of silently switching to aio=threads, except
2175 * if called from drive_init.
2176 *
2177 * For now, simply forbidding the combination for all drivers will do. */
2178 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2179 bool direct = options->cache->has_direct && options->cache->direct;
2180 if (!options->has_cache && !direct) {
2181 error_setg(errp, "aio=native requires cache.direct=true");
2182 goto fail;
2183 }
2184 }
2185
2186 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2187 &options, NULL, &local_err);
2188 if (error_is_set(&local_err)) {
2189 error_propagate(errp, local_err);
2190 goto fail;
2191 }
2192
2193 obj = qmp_output_get_qobject(ov);
2194 qdict = qobject_to_qdict(obj);
2195
2196 qdict_flatten(qdict);
2197
b681072d
KW
2198 blockdev_init(qdict, IF_NONE, &local_err);
2199 if (error_is_set(&local_err)) {
2200 error_propagate(errp, local_err);
d26c9a15
KW
2201 goto fail;
2202 }
2203
2204fail:
2205 qmp_output_visitor_cleanup(ov);
2206}
2207
fb5458cd
SH
2208static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
2209{
2210 BlockJobInfoList **prev = opaque;
2211 BlockJob *job = bs->job;
2212
2213 if (job) {
30e628b7
PB
2214 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2215 elem->value = block_job_query(bs->job);
fb5458cd
SH
2216 (*prev)->next = elem;
2217 *prev = elem;
2218 }
2219}
2220
2221BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2222{
2223 /* Dummy is a fake list element for holding the head pointer */
2224 BlockJobInfoList dummy = {};
2225 BlockJobInfoList *prev = &dummy;
2226 bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
2227 return dummy.next;
2228}
4d454574 2229
0006383e 2230QemuOptsList qemu_common_drive_opts = {
4d454574 2231 .name = "drive",
0006383e 2232 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4d454574
PB
2233 .desc = {
2234 {
4d454574
PB
2235 .name = "snapshot",
2236 .type = QEMU_OPT_BOOL,
2237 .help = "enable/disable snapshot mode",
2238 },{
2239 .name = "file",
2240 .type = QEMU_OPT_STRING,
2241 .help = "disk image",
a9384aff
PB
2242 },{
2243 .name = "discard",
2244 .type = QEMU_OPT_STRING,
2245 .help = "discard operation (ignore/off, unmap/on)",
4d454574 2246 },{
29c4e2b5
KW
2247 .name = "cache.writeback",
2248 .type = QEMU_OPT_BOOL,
2249 .help = "enables writeback mode for any caches",
2250 },{
2251 .name = "cache.direct",
2252 .type = QEMU_OPT_BOOL,
2253 .help = "enables use of O_DIRECT (bypass the host page cache)",
2254 },{
2255 .name = "cache.no-flush",
2256 .type = QEMU_OPT_BOOL,
2257 .help = "ignore any flush requests for the device",
4d454574
PB
2258 },{
2259 .name = "aio",
2260 .type = QEMU_OPT_STRING,
2261 .help = "host AIO implementation (threads, native)",
2262 },{
2263 .name = "format",
2264 .type = QEMU_OPT_STRING,
2265 .help = "disk format (raw, qcow2, ...)",
2266 },{
2267 .name = "serial",
2268 .type = QEMU_OPT_STRING,
2269 .help = "disk serial number",
2270 },{
2271 .name = "rerror",
2272 .type = QEMU_OPT_STRING,
2273 .help = "read error action",
2274 },{
2275 .name = "werror",
2276 .type = QEMU_OPT_STRING,
2277 .help = "write error action",
4d454574 2278 },{
0f227a94 2279 .name = "read-only",
4d454574
PB
2280 .type = QEMU_OPT_BOOL,
2281 .help = "open drive file as read-only",
2282 },{
57975222 2283 .name = "throttling.iops-total",
4d454574
PB
2284 .type = QEMU_OPT_NUMBER,
2285 .help = "limit total I/O operations per second",
2286 },{
57975222 2287 .name = "throttling.iops-read",
4d454574
PB
2288 .type = QEMU_OPT_NUMBER,
2289 .help = "limit read operations per second",
2290 },{
57975222 2291 .name = "throttling.iops-write",
4d454574
PB
2292 .type = QEMU_OPT_NUMBER,
2293 .help = "limit write operations per second",
2294 },{
57975222 2295 .name = "throttling.bps-total",
4d454574
PB
2296 .type = QEMU_OPT_NUMBER,
2297 .help = "limit total bytes per second",
2298 },{
57975222 2299 .name = "throttling.bps-read",
4d454574
PB
2300 .type = QEMU_OPT_NUMBER,
2301 .help = "limit read bytes per second",
2302 },{
57975222 2303 .name = "throttling.bps-write",
4d454574
PB
2304 .type = QEMU_OPT_NUMBER,
2305 .help = "limit write bytes per second",
3e9fab69
BC
2306 },{
2307 .name = "throttling.iops-total-max",
2308 .type = QEMU_OPT_NUMBER,
2309 .help = "I/O operations burst",
2310 },{
2311 .name = "throttling.iops-read-max",
2312 .type = QEMU_OPT_NUMBER,
2313 .help = "I/O operations read burst",
2314 },{
2315 .name = "throttling.iops-write-max",
2316 .type = QEMU_OPT_NUMBER,
2317 .help = "I/O operations write burst",
2318 },{
2319 .name = "throttling.bps-total-max",
2320 .type = QEMU_OPT_NUMBER,
2321 .help = "total bytes burst",
2322 },{
2323 .name = "throttling.bps-read-max",
2324 .type = QEMU_OPT_NUMBER,
2325 .help = "total bytes read burst",
2326 },{
2327 .name = "throttling.bps-write-max",
2328 .type = QEMU_OPT_NUMBER,
2329 .help = "total bytes write burst",
2024c1df
BC
2330 },{
2331 .name = "throttling.iops-size",
2332 .type = QEMU_OPT_NUMBER,
2333 .help = "when limiting by iops max size of an I/O in bytes",
4d454574
PB
2334 },{
2335 .name = "copy-on-read",
2336 .type = QEMU_OPT_BOOL,
2337 .help = "copy read data from backing file into image file",
4d454574
PB
2338 },
2339 { /* end of list */ }
2340 },
2341};
0006383e
KW
2342
2343QemuOptsList qemu_drive_opts = {
2344 .name = "drive",
2345 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2346 .desc = {
492fdc6f
KW
2347 /*
2348 * no elements => accept any params
2349 * validation will happen later
2350 */
0006383e
KW
2351 { /* end of list */ }
2352 },
2353};