]> git.proxmox.com Git - qemu.git/blame - blockdev.c
hw/i386/Makefile.obj: use $(PYTHON) to run .py scripts consistently
[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;
a7fdbcf0
FZ
628 bool read_only = false;
629 bool copy_on_read;
33cb7dc8 630 Error *local_err = NULL;
29c4e2b5 631
57975222
KW
632 /* Change legacy command line options into QMP ones */
633 qemu_opt_rename(all_opts, "iops", "throttling.iops-total");
634 qemu_opt_rename(all_opts, "iops_rd", "throttling.iops-read");
635 qemu_opt_rename(all_opts, "iops_wr", "throttling.iops-write");
636
637 qemu_opt_rename(all_opts, "bps", "throttling.bps-total");
638 qemu_opt_rename(all_opts, "bps_rd", "throttling.bps-read");
639 qemu_opt_rename(all_opts, "bps_wr", "throttling.bps-write");
640
3e9fab69
BC
641 qemu_opt_rename(all_opts, "iops_max", "throttling.iops-total-max");
642 qemu_opt_rename(all_opts, "iops_rd_max", "throttling.iops-read-max");
643 qemu_opt_rename(all_opts, "iops_wr_max", "throttling.iops-write-max");
644
645 qemu_opt_rename(all_opts, "bps_max", "throttling.bps-total-max");
646 qemu_opt_rename(all_opts, "bps_rd_max", "throttling.bps-read-max");
647 qemu_opt_rename(all_opts, "bps_wr_max", "throttling.bps-write-max");
648
2024c1df
BC
649 qemu_opt_rename(all_opts,
650 "iops_size", "throttling.iops-size");
651
0f227a94
KW
652 qemu_opt_rename(all_opts, "readonly", "read-only");
653
29c4e2b5
KW
654 value = qemu_opt_get(all_opts, "cache");
655 if (value) {
656 int flags = 0;
657
658 if (bdrv_parse_cache_flags(value, &flags) != 0) {
659 error_report("invalid cache option");
660 return NULL;
661 }
662
663 /* Specific options take precedence */
664 if (!qemu_opt_get(all_opts, "cache.writeback")) {
665 qemu_opt_set_bool(all_opts, "cache.writeback",
666 !!(flags & BDRV_O_CACHE_WB));
667 }
668 if (!qemu_opt_get(all_opts, "cache.direct")) {
669 qemu_opt_set_bool(all_opts, "cache.direct",
670 !!(flags & BDRV_O_NOCACHE));
671 }
672 if (!qemu_opt_get(all_opts, "cache.no-flush")) {
673 qemu_opt_set_bool(all_opts, "cache.no-flush",
674 !!(flags & BDRV_O_NO_FLUSH));
675 }
676 qemu_opt_unset(all_opts, "cache");
677 }
678
f298d071
KW
679 /* Get a QDict for processing the options */
680 bs_opts = qdict_new();
681 qemu_opts_to_qdict(all_opts, bs_opts);
682
33cb7dc8
KW
683 legacy_opts = qemu_opts_create_nofail(&qemu_legacy_drive_opts);
684 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
685 if (error_is_set(&local_err)) {
686 qerror_report_err(local_err);
687 error_free(local_err);
688 goto fail;
689 }
690
26929298
KW
691 /* Deprecated option boot=[on|off] */
692 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
693 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
694 "ignored. Future versions will reject this parameter. Please "
695 "update your scripts.\n");
696 }
697
33cb7dc8
KW
698 /* Media type */
699 value = qemu_opt_get(legacy_opts, "media");
700 if (value) {
701 if (!strcmp(value, "disk")) {
702 media = MEDIA_DISK;
703 } else if (!strcmp(value, "cdrom")) {
704 media = MEDIA_CDROM;
a7fdbcf0 705 read_only = true;
33cb7dc8
KW
706 } else {
707 error_report("'%s' invalid media", value);
708 goto fail;
709 }
710 }
711
0ebd24e0 712 /* copy-on-read is disabled with a warning for read-only devices */
a7fdbcf0 713 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
0ebd24e0
KW
714 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
715
716 if (read_only && copy_on_read) {
717 error_report("warning: disabling copy-on-read on read-only drive");
718 copy_on_read = false;
719 }
720
721 qdict_put(bs_opts, "read-only",
722 qstring_from_str(read_only ? "on" : "off"));
723 qdict_put(bs_opts, "copy-on-read",
724 qstring_from_str(copy_on_read ? "on" :"off"));
725
593d464b
KW
726 /* Controller type */
727 value = qemu_opt_get(legacy_opts, "if");
728 if (value) {
729 for (type = 0;
730 type < IF_COUNT && strcmp(value, if_name[type]);
731 type++) {
732 }
733 if (type == IF_COUNT) {
734 error_report("unsupported bus type '%s'", value);
735 goto fail;
736 }
737 } else {
738 type = block_default_type;
739 }
740
b41a7338
KW
741 /* Geometry */
742 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
743 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
744 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
745
746 if (cyls || heads || secs) {
747 if (cyls < 1) {
748 error_report("invalid physical cyls number");
749 goto fail;
750 }
751 if (heads < 1) {
752 error_report("invalid physical heads number");
753 goto fail;
754 }
755 if (secs < 1) {
756 error_report("invalid physical secs number");
757 goto fail;
758 }
759 }
760
761 translation = BIOS_ATA_TRANSLATION_AUTO;
762 value = qemu_opt_get(legacy_opts, "trans");
763 if (value != NULL) {
764 if (!cyls) {
765 error_report("'%s' trans must be used with cyls, heads and secs",
766 value);
767 goto fail;
768 }
769 if (!strcmp(value, "none")) {
770 translation = BIOS_ATA_TRANSLATION_NONE;
771 } else if (!strcmp(value, "lba")) {
772 translation = BIOS_ATA_TRANSLATION_LBA;
773 } else if (!strcmp(value, "auto")) {
774 translation = BIOS_ATA_TRANSLATION_AUTO;
775 } else {
776 error_report("'%s' invalid translation type", value);
777 goto fail;
778 }
779 }
780
781 if (media == MEDIA_CDROM) {
782 if (cyls || secs || heads) {
783 error_report("CHS can't be set with media=cdrom");
784 goto fail;
785 }
786 }
787
87a899c5
KW
788 /* Device address specified by bus/unit or index.
789 * If none was specified, try to find the first free one. */
790 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
791 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
792 index = qemu_opt_get_number(legacy_opts, "index", -1);
793
794 max_devs = if_max_devs[type];
795
796 if (index != -1) {
797 if (bus_id != 0 || unit_id != -1) {
798 error_report("index cannot be used with bus and unit");
799 goto fail;
800 }
801 bus_id = drive_index_to_bus_id(type, index);
802 unit_id = drive_index_to_unit_id(type, index);
803 }
804
805 if (unit_id == -1) {
806 unit_id = 0;
807 while (drive_get(type, bus_id, unit_id) != NULL) {
808 unit_id++;
809 if (max_devs && unit_id >= max_devs) {
810 unit_id -= max_devs;
811 bus_id++;
812 }
813 }
814 }
815
816 if (max_devs && unit_id >= max_devs) {
817 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
818 goto fail;
819 }
820
821 if (drive_get(type, bus_id, unit_id) != NULL) {
822 error_report("drive with bus=%d, unit=%d (index=%d) exists",
823 bus_id, unit_id, index);
824 goto fail;
825 }
826
827 /* no id supplied -> create one */
828 if (qemu_opts_id(all_opts) == NULL) {
829 char *new_id;
830 const char *mediastr = "";
831 if (type == IF_IDE || type == IF_SCSI) {
832 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
833 }
834 if (max_devs) {
835 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
836 mediastr, unit_id);
837 } else {
838 new_id = g_strdup_printf("%s%s%i", if_name[type],
839 mediastr, unit_id);
840 }
841 qdict_put(bs_opts, "id", qstring_from_str(new_id));
842 g_free(new_id);
843 }
844
394c7d4d
KW
845 /* Add virtio block device */
846 devaddr = qemu_opt_get(legacy_opts, "addr");
847 if (devaddr && type != IF_VIRTIO) {
848 error_report("addr is not supported by this bus type");
849 goto fail;
850 }
851
852 if (type == IF_VIRTIO) {
853 QemuOpts *devopts;
854 devopts = qemu_opts_create_nofail(qemu_find_opts("device"));
855 if (arch_type == QEMU_ARCH_S390X) {
856 qemu_opt_set(devopts, "driver", "virtio-blk-s390");
857 } else {
858 qemu_opt_set(devopts, "driver", "virtio-blk-pci");
859 }
860 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"));
861 if (devaddr) {
862 qemu_opt_set(devopts, "addr", devaddr);
863 }
864 }
865
2d246f01 866 /* Actual block device init: Functionality shared with blockdev-add */
b681072d 867 dinfo = blockdev_init(bs_opts, type, &local_err);
2d246f01 868 if (dinfo == NULL) {
b681072d
KW
869 if (error_is_set(&local_err)) {
870 qerror_report_err(local_err);
871 error_free(local_err);
872 }
2d246f01 873 goto fail;
b681072d
KW
874 } else {
875 assert(!error_is_set(&local_err));
2d246f01
KW
876 }
877
878 /* Set legacy DriveInfo fields */
879 dinfo->enable_auto_del = true;
f298d071 880 dinfo->opts = all_opts;
2d246f01 881
b41a7338
KW
882 dinfo->cyls = cyls;
883 dinfo->heads = heads;
884 dinfo->secs = secs;
885 dinfo->trans = translation;
886
87a899c5
KW
887 dinfo->bus = bus_id;
888 dinfo->unit = unit_id;
394c7d4d 889 dinfo->devaddr = devaddr;
87a899c5 890
e34ef046
KW
891 switch(type) {
892 case IF_IDE:
893 case IF_SCSI:
894 case IF_XEN:
895 case IF_NONE:
896 dinfo->media_cd = media == MEDIA_CDROM;
897 break;
898 default:
899 break;
900 }
901
2d246f01 902fail:
33cb7dc8 903 qemu_opts_del(legacy_opts);
2d246f01 904 return dinfo;
57975222
KW
905}
906
666daa68
MA
907void do_commit(Monitor *mon, const QDict *qdict)
908{
666daa68 909 const char *device = qdict_get_str(qdict, "device");
6ab4b5ab 910 BlockDriverState *bs;
e8877497 911 int ret;
666daa68 912
6ab4b5ab 913 if (!strcmp(device, "all")) {
e8877497 914 ret = bdrv_commit_all();
6ab4b5ab
MA
915 } else {
916 bs = bdrv_find(device);
ac59eb95 917 if (!bs) {
58513bde 918 monitor_printf(mon, "Device '%s' not found\n", device);
ac59eb95 919 return;
6ab4b5ab 920 }
2d3735d3 921 ret = bdrv_commit(bs);
58513bde
JC
922 }
923 if (ret < 0) {
924 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
925 strerror(-ret));
666daa68
MA
926 }
927}
928
6cc2a415
PB
929static void blockdev_do_action(int kind, void *data, Error **errp)
930{
c8a83e85
KW
931 TransactionAction action;
932 TransactionActionList list;
6cc2a415
PB
933
934 action.kind = kind;
935 action.data = data;
936 list.value = &action;
937 list.next = NULL;
938 qmp_transaction(&list, errp);
939}
940
6106e249
LC
941void qmp_blockdev_snapshot_sync(const char *device, const char *snapshot_file,
942 bool has_format, const char *format,
6cc2a415 943 bool has_mode, enum NewImageMode mode,
6106e249 944 Error **errp)
f8882568 945{
6cc2a415
PB
946 BlockdevSnapshot snapshot = {
947 .device = (char *) device,
948 .snapshot_file = (char *) snapshot_file,
949 .has_format = has_format,
950 .format = (char *) format,
951 .has_mode = has_mode,
952 .mode = mode,
953 };
c8a83e85
KW
954 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
955 &snapshot, errp);
f8882568
JS
956}
957
f323bc9e
WX
958void qmp_blockdev_snapshot_internal_sync(const char *device,
959 const char *name,
960 Error **errp)
961{
962 BlockdevSnapshotInternal snapshot = {
963 .device = (char *) device,
964 .name = (char *) name
965 };
966
967 blockdev_do_action(TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
968 &snapshot, errp);
969}
970
44e3e053
WX
971SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
972 bool has_id,
973 const char *id,
974 bool has_name,
975 const char *name,
976 Error **errp)
977{
978 BlockDriverState *bs = bdrv_find(device);
979 QEMUSnapshotInfo sn;
980 Error *local_err = NULL;
981 SnapshotInfo *info = NULL;
982 int ret;
983
984 if (!bs) {
985 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
986 return NULL;
987 }
988
989 if (!has_id) {
990 id = NULL;
991 }
992
993 if (!has_name) {
994 name = NULL;
995 }
996
997 if (!id && !name) {
998 error_setg(errp, "Name or id must be provided");
999 return NULL;
1000 }
1001
1002 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1003 if (error_is_set(&local_err)) {
1004 error_propagate(errp, local_err);
1005 return NULL;
1006 }
1007 if (!ret) {
1008 error_setg(errp,
1009 "Snapshot with id '%s' and name '%s' does not exist on "
1010 "device '%s'",
1011 STR_OR_NULL(id), STR_OR_NULL(name), device);
1012 return NULL;
1013 }
1014
1015 bdrv_snapshot_delete(bs, id, name, &local_err);
1016 if (error_is_set(&local_err)) {
1017 error_propagate(errp, local_err);
1018 return NULL;
1019 }
1020
1021 info = g_malloc0(sizeof(SnapshotInfo));
1022 info->id = g_strdup(sn.id_str);
1023 info->name = g_strdup(sn.name);
1024 info->date_nsec = sn.date_nsec;
1025 info->date_sec = sn.date_sec;
1026 info->vm_state_size = sn.vm_state_size;
1027 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1028 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1029
1030 return info;
1031}
8802d1fd
JC
1032
1033/* New and old BlockDriverState structs for group snapshots */
ba0c86a3 1034
ba5d6ab6 1035typedef struct BlkTransactionState BlkTransactionState;
ba0c86a3
WX
1036
1037/* Only prepare() may fail. In a single transaction, only one of commit() or
1038 abort() will be called, clean() will always be called if it present. */
1039typedef struct BdrvActionOps {
1040 /* Size of state struct, in bytes. */
1041 size_t instance_size;
1042 /* Prepare the work, must NOT be NULL. */
ba5d6ab6 1043 void (*prepare)(BlkTransactionState *common, Error **errp);
f9ea81e8 1044 /* Commit the changes, can be NULL. */
ba5d6ab6 1045 void (*commit)(BlkTransactionState *common);
ba0c86a3 1046 /* Abort the changes on fail, can be NULL. */
ba5d6ab6 1047 void (*abort)(BlkTransactionState *common);
ba0c86a3 1048 /* Clean up resource in the end, can be NULL. */
ba5d6ab6 1049 void (*clean)(BlkTransactionState *common);
ba0c86a3
WX
1050} BdrvActionOps;
1051
1052/*
1053 * This structure must be arranged as first member in child type, assuming
1054 * that compiler will also arrange it to the same address with parent instance.
1055 * Later it will be used in free().
1056 */
ba5d6ab6 1057struct BlkTransactionState {
c8a83e85 1058 TransactionAction *action;
ba0c86a3 1059 const BdrvActionOps *ops;
ba5d6ab6 1060 QSIMPLEQ_ENTRY(BlkTransactionState) entry;
ba0c86a3
WX
1061};
1062
bbe86010
WX
1063/* internal snapshot private data */
1064typedef struct InternalSnapshotState {
1065 BlkTransactionState common;
1066 BlockDriverState *bs;
1067 QEMUSnapshotInfo sn;
1068} InternalSnapshotState;
1069
1070static void internal_snapshot_prepare(BlkTransactionState *common,
1071 Error **errp)
1072{
1073 const char *device;
1074 const char *name;
1075 BlockDriverState *bs;
1076 QEMUSnapshotInfo old_sn, *sn;
1077 bool ret;
1078 qemu_timeval tv;
1079 BlockdevSnapshotInternal *internal;
1080 InternalSnapshotState *state;
1081 int ret1;
1082
1083 g_assert(common->action->kind ==
1084 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1085 internal = common->action->blockdev_snapshot_internal_sync;
1086 state = DO_UPCAST(InternalSnapshotState, common, common);
1087
1088 /* 1. parse input */
1089 device = internal->device;
1090 name = internal->name;
1091
1092 /* 2. check for validation */
1093 bs = bdrv_find(device);
1094 if (!bs) {
1095 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1096 return;
1097 }
1098
1099 if (!bdrv_is_inserted(bs)) {
1100 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1101 return;
1102 }
1103
1104 if (bdrv_is_read_only(bs)) {
1105 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1106 return;
1107 }
1108
1109 if (!bdrv_can_snapshot(bs)) {
1110 error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1111 bs->drv->format_name, device, "internal snapshot");
1112 return;
1113 }
1114
1115 if (!strlen(name)) {
1116 error_setg(errp, "Name is empty");
1117 return;
1118 }
1119
1120 /* check whether a snapshot with name exist */
1121 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn, errp);
1122 if (error_is_set(errp)) {
1123 return;
1124 } else if (ret) {
1125 error_setg(errp,
1126 "Snapshot with name '%s' already exists on device '%s'",
1127 name, device);
1128 return;
1129 }
1130
1131 /* 3. take the snapshot */
1132 sn = &state->sn;
1133 pstrcpy(sn->name, sizeof(sn->name), name);
1134 qemu_gettimeofday(&tv);
1135 sn->date_sec = tv.tv_sec;
1136 sn->date_nsec = tv.tv_usec * 1000;
1137 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1138
1139 ret1 = bdrv_snapshot_create(bs, sn);
1140 if (ret1 < 0) {
1141 error_setg_errno(errp, -ret1,
1142 "Failed to create snapshot '%s' on device '%s'",
1143 name, device);
1144 return;
1145 }
1146
1147 /* 4. succeed, mark a snapshot is created */
1148 state->bs = bs;
1149}
1150
1151static void internal_snapshot_abort(BlkTransactionState *common)
1152{
1153 InternalSnapshotState *state =
1154 DO_UPCAST(InternalSnapshotState, common, common);
1155 BlockDriverState *bs = state->bs;
1156 QEMUSnapshotInfo *sn = &state->sn;
1157 Error *local_error = NULL;
1158
1159 if (!bs) {
1160 return;
1161 }
1162
1163 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1164 error_report("Failed to delete snapshot with id '%s' and name '%s' on "
1165 "device '%s' in abort: %s",
1166 sn->id_str,
1167 sn->name,
1168 bdrv_get_device_name(bs),
1169 error_get_pretty(local_error));
1170 error_free(local_error);
1171 }
1172}
1173
ba0c86a3 1174/* external snapshot private data */
ba5d6ab6
SH
1175typedef struct ExternalSnapshotState {
1176 BlkTransactionState common;
8802d1fd
JC
1177 BlockDriverState *old_bs;
1178 BlockDriverState *new_bs;
ba5d6ab6 1179} ExternalSnapshotState;
8802d1fd 1180
ba5d6ab6 1181static void external_snapshot_prepare(BlkTransactionState *common,
9b9877ee
WX
1182 Error **errp)
1183{
9b9877ee
WX
1184 BlockDriver *drv;
1185 int flags, ret;
1186 Error *local_err = NULL;
e2a31e87
WX
1187 const char *device;
1188 const char *new_image_file;
1189 const char *format = "qcow2";
1190 enum NewImageMode mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
ba5d6ab6
SH
1191 ExternalSnapshotState *state =
1192 DO_UPCAST(ExternalSnapshotState, common, common);
c8a83e85 1193 TransactionAction *action = common->action;
9b9877ee 1194
e2a31e87 1195 /* get parameters */
c8a83e85 1196 g_assert(action->kind == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC);
e2a31e87
WX
1197
1198 device = action->blockdev_snapshot_sync->device;
1199 new_image_file = action->blockdev_snapshot_sync->snapshot_file;
1200 if (action->blockdev_snapshot_sync->has_format) {
1201 format = action->blockdev_snapshot_sync->format;
1202 }
1203 if (action->blockdev_snapshot_sync->has_mode) {
1204 mode = action->blockdev_snapshot_sync->mode;
1205 }
1206
1207 /* start processing */
9b9877ee
WX
1208 drv = bdrv_find_format(format);
1209 if (!drv) {
1210 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1211 return;
1212 }
1213
ba5d6ab6
SH
1214 state->old_bs = bdrv_find(device);
1215 if (!state->old_bs) {
9b9877ee
WX
1216 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1217 return;
1218 }
1219
ba5d6ab6 1220 if (!bdrv_is_inserted(state->old_bs)) {
9b9877ee
WX
1221 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1222 return;
1223 }
1224
ba5d6ab6 1225 if (bdrv_in_use(state->old_bs)) {
9b9877ee
WX
1226 error_set(errp, QERR_DEVICE_IN_USE, device);
1227 return;
1228 }
1229
ba5d6ab6
SH
1230 if (!bdrv_is_read_only(state->old_bs)) {
1231 if (bdrv_flush(state->old_bs)) {
9b9877ee
WX
1232 error_set(errp, QERR_IO_ERROR);
1233 return;
1234 }
1235 }
1236
f6186f49
BC
1237 if (bdrv_check_ext_snapshot(state->old_bs) != EXT_SNAPSHOT_ALLOWED) {
1238 error_set(errp, QERR_FEATURE_DISABLED, "snapshot");
1239 return;
1240 }
1241
ba5d6ab6 1242 flags = state->old_bs->open_flags;
9b9877ee 1243
9b9877ee
WX
1244 /* create new image w/backing file */
1245 if (mode != NEW_IMAGE_MODE_EXISTING) {
1246 bdrv_img_create(new_image_file, format,
ba5d6ab6
SH
1247 state->old_bs->filename,
1248 state->old_bs->drv->format_name,
9b9877ee
WX
1249 NULL, -1, flags, &local_err, false);
1250 if (error_is_set(&local_err)) {
1251 error_propagate(errp, local_err);
1252 return;
1253 }
1254 }
1255
1256 /* We will manually add the backing_hd field to the bs later */
ba5d6ab6 1257 state->new_bs = bdrv_new("");
9b9877ee
WX
1258 /* TODO Inherit bs->options or only take explicit options with an
1259 * extended QMP command? */
ba5d6ab6 1260 ret = bdrv_open(state->new_bs, new_image_file, NULL,
34b5d2c6 1261 flags | BDRV_O_NO_BACKING, drv, &local_err);
9b9877ee 1262 if (ret != 0) {
34b5d2c6 1263 error_propagate(errp, local_err);
9b9877ee
WX
1264 }
1265}
1266
ba5d6ab6 1267static void external_snapshot_commit(BlkTransactionState *common)
3b0047e8 1268{
ba5d6ab6
SH
1269 ExternalSnapshotState *state =
1270 DO_UPCAST(ExternalSnapshotState, common, common);
ba0c86a3 1271
ba5d6ab6
SH
1272 /* This removes our old bs and adds the new bs */
1273 bdrv_append(state->new_bs, state->old_bs);
3b0047e8
WX
1274 /* We don't need (or want) to use the transactional
1275 * bdrv_reopen_multiple() across all the entries at once, because we
1276 * don't want to abort all of them if one of them fails the reopen */
ba5d6ab6 1277 bdrv_reopen(state->new_bs, state->new_bs->open_flags & ~BDRV_O_RDWR,
3b0047e8
WX
1278 NULL);
1279}
1280
ba5d6ab6 1281static void external_snapshot_abort(BlkTransactionState *common)
96b86bf7 1282{
ba5d6ab6
SH
1283 ExternalSnapshotState *state =
1284 DO_UPCAST(ExternalSnapshotState, common, common);
1285 if (state->new_bs) {
4f6fd349 1286 bdrv_unref(state->new_bs);
96b86bf7
WX
1287 }
1288}
1289
3037f364
SH
1290typedef struct DriveBackupState {
1291 BlkTransactionState common;
1292 BlockDriverState *bs;
1293 BlockJob *job;
1294} DriveBackupState;
1295
1296static void drive_backup_prepare(BlkTransactionState *common, Error **errp)
1297{
1298 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1299 DriveBackup *backup;
1300 Error *local_err = NULL;
1301
1302 assert(common->action->kind == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1303 backup = common->action->drive_backup;
1304
1305 qmp_drive_backup(backup->device, backup->target,
1306 backup->has_format, backup->format,
b53169ea 1307 backup->sync,
3037f364
SH
1308 backup->has_mode, backup->mode,
1309 backup->has_speed, backup->speed,
1310 backup->has_on_source_error, backup->on_source_error,
1311 backup->has_on_target_error, backup->on_target_error,
1312 &local_err);
1313 if (error_is_set(&local_err)) {
1314 error_propagate(errp, local_err);
1315 state->bs = NULL;
1316 state->job = NULL;
1317 return;
1318 }
1319
1320 state->bs = bdrv_find(backup->device);
1321 state->job = state->bs->job;
1322}
1323
1324static void drive_backup_abort(BlkTransactionState *common)
1325{
1326 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1327 BlockDriverState *bs = state->bs;
1328
1329 /* Only cancel if it's the job we started */
1330 if (bs && bs->job && bs->job == state->job) {
1331 block_job_cancel_sync(bs->job);
1332 }
1333}
1334
78b18b78
SH
1335static void abort_prepare(BlkTransactionState *common, Error **errp)
1336{
1337 error_setg(errp, "Transaction aborted using Abort action");
1338}
1339
1340static void abort_commit(BlkTransactionState *common)
1341{
dfc6f865 1342 g_assert_not_reached(); /* this action never succeeds */
78b18b78
SH
1343}
1344
ba0c86a3 1345static const BdrvActionOps actions[] = {
c8a83e85 1346 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
ba5d6ab6 1347 .instance_size = sizeof(ExternalSnapshotState),
ba0c86a3
WX
1348 .prepare = external_snapshot_prepare,
1349 .commit = external_snapshot_commit,
1350 .abort = external_snapshot_abort,
1351 },
3037f364
SH
1352 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
1353 .instance_size = sizeof(DriveBackupState),
1354 .prepare = drive_backup_prepare,
1355 .abort = drive_backup_abort,
1356 },
78b18b78
SH
1357 [TRANSACTION_ACTION_KIND_ABORT] = {
1358 .instance_size = sizeof(BlkTransactionState),
1359 .prepare = abort_prepare,
1360 .commit = abort_commit,
1361 },
bbe86010
WX
1362 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
1363 .instance_size = sizeof(InternalSnapshotState),
1364 .prepare = internal_snapshot_prepare,
1365 .abort = internal_snapshot_abort,
1366 },
ba0c86a3
WX
1367};
1368
8802d1fd
JC
1369/*
1370 * 'Atomic' group snapshots. The snapshots are taken as a set, and if any fail
1371 * then we do not pivot any of the devices in the group, and abandon the
1372 * snapshots
1373 */
c8a83e85 1374void qmp_transaction(TransactionActionList *dev_list, Error **errp)
8802d1fd 1375{
c8a83e85 1376 TransactionActionList *dev_entry = dev_list;
ba5d6ab6 1377 BlkTransactionState *state, *next;
43e17041 1378 Error *local_err = NULL;
8802d1fd 1379
ba5d6ab6 1380 QSIMPLEQ_HEAD(snap_bdrv_states, BlkTransactionState) snap_bdrv_states;
8802d1fd
JC
1381 QSIMPLEQ_INIT(&snap_bdrv_states);
1382
1383 /* drain all i/o before any snapshots */
1384 bdrv_drain_all();
1385
1386 /* We don't do anything in this loop that commits us to the snapshot */
1387 while (NULL != dev_entry) {
c8a83e85 1388 TransactionAction *dev_info = NULL;
ba0c86a3 1389 const BdrvActionOps *ops;
52e7c241 1390
8802d1fd
JC
1391 dev_info = dev_entry->value;
1392 dev_entry = dev_entry->next;
1393
ba0c86a3
WX
1394 assert(dev_info->kind < ARRAY_SIZE(actions));
1395
1396 ops = &actions[dev_info->kind];
aa3fe714
MR
1397 assert(ops->instance_size > 0);
1398
ba5d6ab6
SH
1399 state = g_malloc0(ops->instance_size);
1400 state->ops = ops;
1401 state->action = dev_info;
1402 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
8802d1fd 1403
ba5d6ab6 1404 state->ops->prepare(state, &local_err);
ba0c86a3
WX
1405 if (error_is_set(&local_err)) {
1406 error_propagate(errp, local_err);
1407 goto delete_and_fail;
8802d1fd 1408 }
8802d1fd
JC
1409 }
1410
ba5d6ab6 1411 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
f9ea81e8
SH
1412 if (state->ops->commit) {
1413 state->ops->commit(state);
1414 }
8802d1fd
JC
1415 }
1416
1417 /* success */
1418 goto exit;
1419
1420delete_and_fail:
1421 /*
1422 * failure, and it is all-or-none; abandon each new bs, and keep using
1423 * the original bs for all images
1424 */
ba5d6ab6
SH
1425 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
1426 if (state->ops->abort) {
1427 state->ops->abort(state);
ba0c86a3 1428 }
8802d1fd
JC
1429 }
1430exit:
ba5d6ab6
SH
1431 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
1432 if (state->ops->clean) {
1433 state->ops->clean(state);
ba0c86a3 1434 }
ba5d6ab6 1435 g_free(state);
8802d1fd 1436 }
8802d1fd
JC
1437}
1438
1439
92d48558 1440static void eject_device(BlockDriverState *bs, int force, Error **errp)
666daa68 1441{
2d3735d3
SH
1442 if (bdrv_in_use(bs)) {
1443 error_set(errp, QERR_DEVICE_IN_USE, bdrv_get_device_name(bs));
1444 return;
1445 }
2c6942fa 1446 if (!bdrv_dev_has_removable_media(bs)) {
92d48558
LC
1447 error_set(errp, QERR_DEVICE_NOT_REMOVABLE, bdrv_get_device_name(bs));
1448 return;
ea8f942f 1449 }
92d48558 1450
025ccaa7
PB
1451 if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {
1452 bdrv_dev_eject_request(bs, force);
1453 if (!force) {
92d48558
LC
1454 error_set(errp, QERR_DEVICE_LOCKED, bdrv_get_device_name(bs));
1455 return;
025ccaa7 1456 }
666daa68 1457 }
92d48558 1458
3b5276b5 1459 bdrv_close(bs);
666daa68
MA
1460}
1461
c245b6a3 1462void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
666daa68
MA
1463{
1464 BlockDriverState *bs;
666daa68 1465
c245b6a3 1466 bs = bdrv_find(device);
666daa68 1467 if (!bs) {
c245b6a3
LC
1468 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1469 return;
92d48558
LC
1470 }
1471
c245b6a3 1472 eject_device(bs, force, errp);
666daa68
MA
1473}
1474
a4dea8a9 1475void qmp_block_passwd(const char *device, const char *password, Error **errp)
666daa68
MA
1476{
1477 BlockDriverState *bs;
1478 int err;
1479
a4dea8a9 1480 bs = bdrv_find(device);
666daa68 1481 if (!bs) {
a4dea8a9
LC
1482 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1483 return;
666daa68
MA
1484 }
1485
a4dea8a9 1486 err = bdrv_set_key(bs, password);
666daa68 1487 if (err == -EINVAL) {
a4dea8a9
LC
1488 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1489 return;
666daa68 1490 } else if (err < 0) {
a4dea8a9
LC
1491 error_set(errp, QERR_INVALID_PASSWORD);
1492 return;
666daa68 1493 }
666daa68
MA
1494}
1495
333a96ec
LC
1496static void qmp_bdrv_open_encrypted(BlockDriverState *bs, const char *filename,
1497 int bdrv_flags, BlockDriver *drv,
1498 const char *password, Error **errp)
1499{
34b5d2c6 1500 Error *local_err = NULL;
0eef407c
LC
1501 int ret;
1502
34b5d2c6 1503 ret = bdrv_open(bs, filename, NULL, bdrv_flags, drv, &local_err);
0eef407c 1504 if (ret < 0) {
34b5d2c6 1505 error_propagate(errp, local_err);
333a96ec
LC
1506 return;
1507 }
1508
1509 if (bdrv_key_required(bs)) {
1510 if (password) {
1511 if (bdrv_set_key(bs, password) < 0) {
1512 error_set(errp, QERR_INVALID_PASSWORD);
1513 }
1514 } else {
1515 error_set(errp, QERR_DEVICE_ENCRYPTED, bdrv_get_device_name(bs),
1516 bdrv_get_encrypted_filename(bs));
1517 }
1518 } else if (password) {
1519 error_set(errp, QERR_DEVICE_NOT_ENCRYPTED, bdrv_get_device_name(bs));
1520 }
1521}
1522
1523void qmp_change_blockdev(const char *device, const char *filename,
1524 bool has_format, const char *format, Error **errp)
666daa68
MA
1525{
1526 BlockDriverState *bs;
1527 BlockDriver *drv = NULL;
1528 int bdrv_flags;
92d48558 1529 Error *err = NULL;
666daa68
MA
1530
1531 bs = bdrv_find(device);
1532 if (!bs) {
333a96ec
LC
1533 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1534 return;
666daa68 1535 }
333a96ec
LC
1536
1537 if (format) {
b64ec4e4 1538 drv = bdrv_find_whitelisted_format(format, bs->read_only);
666daa68 1539 if (!drv) {
333a96ec
LC
1540 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1541 return;
666daa68
MA
1542 }
1543 }
333a96ec 1544
92d48558
LC
1545 eject_device(bs, 0, &err);
1546 if (error_is_set(&err)) {
333a96ec
LC
1547 error_propagate(errp, err);
1548 return;
666daa68 1549 }
333a96ec 1550
528f7663 1551 bdrv_flags = bdrv_is_read_only(bs) ? 0 : BDRV_O_RDWR;
199630b6 1552 bdrv_flags |= bdrv_is_snapshot(bs) ? BDRV_O_SNAPSHOT : 0;
333a96ec
LC
1553
1554 qmp_bdrv_open_encrypted(bs, filename, bdrv_flags, drv, NULL, errp);
666daa68 1555}
9063f814 1556
727f005e 1557/* throttling disk I/O limits */
80047da5 1558void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,
3e9fab69
BC
1559 int64_t bps_wr,
1560 int64_t iops,
1561 int64_t iops_rd,
1562 int64_t iops_wr,
1563 bool has_bps_max,
1564 int64_t bps_max,
1565 bool has_bps_rd_max,
1566 int64_t bps_rd_max,
1567 bool has_bps_wr_max,
1568 int64_t bps_wr_max,
1569 bool has_iops_max,
1570 int64_t iops_max,
1571 bool has_iops_rd_max,
1572 int64_t iops_rd_max,
1573 bool has_iops_wr_max,
2024c1df
BC
1574 int64_t iops_wr_max,
1575 bool has_iops_size,
1576 int64_t iops_size, Error **errp)
727f005e 1577{
cc0681c4 1578 ThrottleConfig cfg;
727f005e
ZYW
1579 BlockDriverState *bs;
1580
80047da5 1581 bs = bdrv_find(device);
727f005e 1582 if (!bs) {
80047da5
LC
1583 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1584 return;
727f005e
ZYW
1585 }
1586
cc0681c4
BC
1587 memset(&cfg, 0, sizeof(cfg));
1588 cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;
1589 cfg.buckets[THROTTLE_BPS_READ].avg = bps_rd;
1590 cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;
1591
1592 cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;
1593 cfg.buckets[THROTTLE_OPS_READ].avg = iops_rd;
1594 cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;
1595
3e9fab69
BC
1596 if (has_bps_max) {
1597 cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;
1598 }
1599 if (has_bps_rd_max) {
1600 cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;
1601 }
1602 if (has_bps_wr_max) {
1603 cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;
1604 }
1605 if (has_iops_max) {
1606 cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;
1607 }
1608 if (has_iops_rd_max) {
1609 cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;
1610 }
1611 if (has_iops_wr_max) {
1612 cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;
1613 }
727f005e 1614
2024c1df
BC
1615 if (has_iops_size) {
1616 cfg.op_size = iops_size;
1617 }
cc0681c4
BC
1618
1619 if (!check_throttle_config(&cfg, errp)) {
80047da5 1620 return;
727f005e
ZYW
1621 }
1622
cc0681c4 1623 if (!bs->io_limits_enabled && throttle_enabled(&cfg)) {
727f005e 1624 bdrv_io_limits_enable(bs);
cc0681c4 1625 } else if (bs->io_limits_enabled && !throttle_enabled(&cfg)) {
727f005e 1626 bdrv_io_limits_disable(bs);
cc0681c4
BC
1627 }
1628
1629 if (bs->io_limits_enabled) {
1630 bdrv_set_io_limits(bs, &cfg);
727f005e 1631 }
727f005e
ZYW
1632}
1633
9063f814
RH
1634int do_drive_del(Monitor *mon, const QDict *qdict, QObject **ret_data)
1635{
1636 const char *id = qdict_get_str(qdict, "id");
1637 BlockDriverState *bs;
9063f814
RH
1638
1639 bs = bdrv_find(id);
1640 if (!bs) {
1641 qerror_report(QERR_DEVICE_NOT_FOUND, id);
1642 return -1;
1643 }
8591675f
MT
1644 if (bdrv_in_use(bs)) {
1645 qerror_report(QERR_DEVICE_IN_USE, id);
1646 return -1;
1647 }
9063f814
RH
1648
1649 /* quiesce block driver; prevent further io */
922453bc 1650 bdrv_drain_all();
9063f814
RH
1651 bdrv_flush(bs);
1652 bdrv_close(bs);
1653
fa879d62 1654 /* if we have a device attached to this BlockDriverState
d22b2f41
RH
1655 * then we need to make the drive anonymous until the device
1656 * can be removed. If this is a drive with no device backing
1657 * then we can just get rid of the block driver state right here.
1658 */
fa879d62 1659 if (bdrv_get_attached_dev(bs)) {
d22b2f41 1660 bdrv_make_anon(bs);
293c51a6
SH
1661
1662 /* Further I/O must not pause the guest */
1663 bdrv_set_on_error(bs, BLOCKDEV_ON_ERROR_REPORT,
1664 BLOCKDEV_ON_ERROR_REPORT);
d22b2f41
RH
1665 } else {
1666 drive_uninit(drive_get_by_blockdev(bs));
9063f814
RH
1667 }
1668
9063f814
RH
1669 return 0;
1670}
6d4a2b3a 1671
5e7caacb 1672void qmp_block_resize(const char *device, int64_t size, Error **errp)
6d4a2b3a 1673{
6d4a2b3a 1674 BlockDriverState *bs;
8732901e 1675 int ret;
6d4a2b3a
CH
1676
1677 bs = bdrv_find(device);
1678 if (!bs) {
5e7caacb
LC
1679 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1680 return;
6d4a2b3a
CH
1681 }
1682
1683 if (size < 0) {
939a1cc3 1684 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
5e7caacb 1685 return;
6d4a2b3a
CH
1686 }
1687
92b7a08d
PL
1688 /* complete all in-flight operations before resizing the device */
1689 bdrv_drain_all();
1690
8732901e
KW
1691 ret = bdrv_truncate(bs, size);
1692 switch (ret) {
939a1cc3
SH
1693 case 0:
1694 break;
1695 case -ENOMEDIUM:
1696 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1697 break;
1698 case -ENOTSUP:
1699 error_set(errp, QERR_UNSUPPORTED);
1700 break;
1701 case -EACCES:
1702 error_set(errp, QERR_DEVICE_IS_READ_ONLY, device);
1703 break;
1704 case -EBUSY:
1705 error_set(errp, QERR_DEVICE_IN_USE, device);
1706 break;
1707 default:
8732901e 1708 error_setg_errno(errp, -ret, "Could not resize");
939a1cc3 1709 break;
6d4a2b3a 1710 }
6d4a2b3a 1711}
12bd451f 1712
9abf2dba 1713static void block_job_cb(void *opaque, int ret)
12bd451f
SH
1714{
1715 BlockDriverState *bs = opaque;
1716 QObject *obj;
1717
9abf2dba 1718 trace_block_job_cb(bs, bs->job, ret);
12bd451f
SH
1719
1720 assert(bs->job);
1721 obj = qobject_from_block_job(bs->job);
1722 if (ret < 0) {
1723 QDict *dict = qobject_to_qdict(obj);
1724 qdict_put(dict, "error", qstring_from_str(strerror(-ret)));
1725 }
1726
370521a1
SH
1727 if (block_job_is_cancelled(bs->job)) {
1728 monitor_protocol_event(QEVENT_BLOCK_JOB_CANCELLED, obj);
1729 } else {
1730 monitor_protocol_event(QEVENT_BLOCK_JOB_COMPLETED, obj);
1731 }
12bd451f 1732 qobject_decref(obj);
aa398a5c 1733
fa510ebf 1734 bdrv_put_ref_bh_schedule(bs);
12bd451f
SH
1735}
1736
1737void qmp_block_stream(const char *device, bool has_base,
1d809098
PB
1738 const char *base, bool has_speed, int64_t speed,
1739 bool has_on_error, BlockdevOnError on_error,
1740 Error **errp)
12bd451f
SH
1741{
1742 BlockDriverState *bs;
c8c3080f 1743 BlockDriverState *base_bs = NULL;
fd7f8c65 1744 Error *local_err = NULL;
12bd451f 1745
1d809098
PB
1746 if (!has_on_error) {
1747 on_error = BLOCKDEV_ON_ERROR_REPORT;
1748 }
1749
12bd451f
SH
1750 bs = bdrv_find(device);
1751 if (!bs) {
1752 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1753 return;
1754 }
1755
12bd451f 1756 if (base) {
c8c3080f
MT
1757 base_bs = bdrv_find_backing_image(bs, base);
1758 if (base_bs == NULL) {
1759 error_set(errp, QERR_BASE_NOT_FOUND, base);
1760 return;
1761 }
12bd451f
SH
1762 }
1763
c83c66c3 1764 stream_start(bs, base_bs, base, has_speed ? speed : 0,
1d809098 1765 on_error, block_job_cb, bs, &local_err);
fd7f8c65
SH
1766 if (error_is_set(&local_err)) {
1767 error_propagate(errp, local_err);
1768 return;
12bd451f
SH
1769 }
1770
1771 trace_qmp_block_stream(bs, bs->job);
1772}
2d47c6e9 1773
ed61fc10
JC
1774void qmp_block_commit(const char *device,
1775 bool has_base, const char *base, const char *top,
1776 bool has_speed, int64_t speed,
1777 Error **errp)
1778{
1779 BlockDriverState *bs;
1780 BlockDriverState *base_bs, *top_bs;
1781 Error *local_err = NULL;
1782 /* This will be part of the QMP command, if/when the
1783 * BlockdevOnError change for blkmirror makes it in
1784 */
92aa5c6d 1785 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
ed61fc10
JC
1786
1787 /* drain all i/o before commits */
1788 bdrv_drain_all();
1789
1790 bs = bdrv_find(device);
1791 if (!bs) {
1792 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1793 return;
1794 }
ed61fc10
JC
1795
1796 /* default top_bs is the active layer */
1797 top_bs = bs;
1798
1799 if (top) {
1800 if (strcmp(bs->filename, top) != 0) {
1801 top_bs = bdrv_find_backing_image(bs, top);
1802 }
1803 }
1804
1805 if (top_bs == NULL) {
1806 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
1807 return;
1808 }
1809
d5208c45
JC
1810 if (has_base && base) {
1811 base_bs = bdrv_find_backing_image(top_bs, base);
1812 } else {
1813 base_bs = bdrv_find_base(top_bs);
1814 }
1815
1816 if (base_bs == NULL) {
1817 error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
1818 return;
1819 }
1820
ed61fc10
JC
1821 commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,
1822 &local_err);
1823 if (local_err != NULL) {
1824 error_propagate(errp, local_err);
1825 return;
1826 }
ed61fc10
JC
1827}
1828
99a9addf
SH
1829void qmp_drive_backup(const char *device, const char *target,
1830 bool has_format, const char *format,
b53169ea 1831 enum MirrorSyncMode sync,
99a9addf
SH
1832 bool has_mode, enum NewImageMode mode,
1833 bool has_speed, int64_t speed,
1834 bool has_on_source_error, BlockdevOnError on_source_error,
1835 bool has_on_target_error, BlockdevOnError on_target_error,
1836 Error **errp)
1837{
1838 BlockDriverState *bs;
1839 BlockDriverState *target_bs;
fc5d3f84 1840 BlockDriverState *source = NULL;
99a9addf
SH
1841 BlockDriver *drv = NULL;
1842 Error *local_err = NULL;
1843 int flags;
1844 int64_t size;
1845 int ret;
1846
1847 if (!has_speed) {
1848 speed = 0;
1849 }
1850 if (!has_on_source_error) {
1851 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
1852 }
1853 if (!has_on_target_error) {
1854 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
1855 }
1856 if (!has_mode) {
1857 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1858 }
1859
1860 bs = bdrv_find(device);
1861 if (!bs) {
1862 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1863 return;
1864 }
1865
1866 if (!bdrv_is_inserted(bs)) {
1867 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1868 return;
1869 }
1870
1871 if (!has_format) {
1872 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
1873 }
1874 if (format) {
1875 drv = bdrv_find_format(format);
1876 if (!drv) {
1877 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
1878 return;
1879 }
1880 }
1881
1882 if (bdrv_in_use(bs)) {
1883 error_set(errp, QERR_DEVICE_IN_USE, device);
1884 return;
1885 }
1886
1887 flags = bs->open_flags | BDRV_O_RDWR;
1888
fc5d3f84
IM
1889 /* See if we have a backing HD we can use to create our new image
1890 * on top of. */
1891 if (sync == MIRROR_SYNC_MODE_TOP) {
1892 source = bs->backing_hd;
1893 if (!source) {
1894 sync = MIRROR_SYNC_MODE_FULL;
1895 }
1896 }
1897 if (sync == MIRROR_SYNC_MODE_NONE) {
1898 source = bs;
1899 }
1900
99a9addf
SH
1901 size = bdrv_getlength(bs);
1902 if (size < 0) {
1903 error_setg_errno(errp, -size, "bdrv_getlength failed");
1904 return;
1905 }
1906
1907 if (mode != NEW_IMAGE_MODE_EXISTING) {
1908 assert(format && drv);
fc5d3f84
IM
1909 if (source) {
1910 bdrv_img_create(target, format, source->filename,
1911 source->drv->format_name, NULL,
1912 size, flags, &local_err, false);
1913 } else {
1914 bdrv_img_create(target, format, NULL, NULL, NULL,
1915 size, flags, &local_err, false);
1916 }
99a9addf
SH
1917 }
1918
1919 if (error_is_set(&local_err)) {
1920 error_propagate(errp, local_err);
1921 return;
1922 }
1923
1924 target_bs = bdrv_new("");
34b5d2c6 1925 ret = bdrv_open(target_bs, target, NULL, flags, drv, &local_err);
99a9addf 1926 if (ret < 0) {
4f6fd349 1927 bdrv_unref(target_bs);
34b5d2c6 1928 error_propagate(errp, local_err);
99a9addf
SH
1929 return;
1930 }
1931
fc5d3f84 1932 backup_start(bs, target_bs, speed, sync, on_source_error, on_target_error,
99a9addf
SH
1933 block_job_cb, bs, &local_err);
1934 if (local_err != NULL) {
4f6fd349 1935 bdrv_unref(target_bs);
99a9addf
SH
1936 error_propagate(errp, local_err);
1937 return;
1938 }
99a9addf
SH
1939}
1940
08e4ed6c
PB
1941#define DEFAULT_MIRROR_BUF_SIZE (10 << 20)
1942
d9b902db
PB
1943void qmp_drive_mirror(const char *device, const char *target,
1944 bool has_format, const char *format,
1945 enum MirrorSyncMode sync,
1946 bool has_mode, enum NewImageMode mode,
b952b558 1947 bool has_speed, int64_t speed,
eee13dfe 1948 bool has_granularity, uint32_t granularity,
08e4ed6c 1949 bool has_buf_size, int64_t buf_size,
b952b558
PB
1950 bool has_on_source_error, BlockdevOnError on_source_error,
1951 bool has_on_target_error, BlockdevOnError on_target_error,
1952 Error **errp)
d9b902db 1953{
d9b902db
PB
1954 BlockDriverState *bs;
1955 BlockDriverState *source, *target_bs;
d9b902db
PB
1956 BlockDriver *drv = NULL;
1957 Error *local_err = NULL;
1958 int flags;
ac3c5d83 1959 int64_t size;
d9b902db
PB
1960 int ret;
1961
1962 if (!has_speed) {
1963 speed = 0;
1964 }
b952b558
PB
1965 if (!has_on_source_error) {
1966 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
1967 }
1968 if (!has_on_target_error) {
1969 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
1970 }
d9b902db
PB
1971 if (!has_mode) {
1972 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1973 }
eee13dfe
PB
1974 if (!has_granularity) {
1975 granularity = 0;
1976 }
08e4ed6c
PB
1977 if (!has_buf_size) {
1978 buf_size = DEFAULT_MIRROR_BUF_SIZE;
1979 }
1980
eee13dfe
PB
1981 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
1982 error_set(errp, QERR_INVALID_PARAMETER, device);
1983 return;
1984 }
1985 if (granularity & (granularity - 1)) {
1986 error_set(errp, QERR_INVALID_PARAMETER, device);
1987 return;
1988 }
d9b902db
PB
1989
1990 bs = bdrv_find(device);
1991 if (!bs) {
1992 error_set(errp, QERR_DEVICE_NOT_FOUND, device);
1993 return;
1994 }
1995
1996 if (!bdrv_is_inserted(bs)) {
1997 error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1998 return;
1999 }
2000
2001 if (!has_format) {
2002 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
2003 }
2004 if (format) {
2005 drv = bdrv_find_format(format);
2006 if (!drv) {
2007 error_set(errp, QERR_INVALID_BLOCK_FORMAT, format);
2008 return;
2009 }
2010 }
2011
2012 if (bdrv_in_use(bs)) {
2013 error_set(errp, QERR_DEVICE_IN_USE, device);
2014 return;
2015 }
2016
2017 flags = bs->open_flags | BDRV_O_RDWR;
2018 source = bs->backing_hd;
2019 if (!source && sync == MIRROR_SYNC_MODE_TOP) {
2020 sync = MIRROR_SYNC_MODE_FULL;
2021 }
2022
ac3c5d83
SH
2023 size = bdrv_getlength(bs);
2024 if (size < 0) {
2025 error_setg_errno(errp, -size, "bdrv_getlength failed");
2026 return;
2027 }
2028
d9b902db
PB
2029 if (sync == MIRROR_SYNC_MODE_FULL && mode != NEW_IMAGE_MODE_EXISTING) {
2030 /* create new image w/o backing file */
2031 assert(format && drv);
cf8f2426 2032 bdrv_img_create(target, format,
f382d43a 2033 NULL, NULL, NULL, size, flags, &local_err, false);
d9b902db
PB
2034 } else {
2035 switch (mode) {
2036 case NEW_IMAGE_MODE_EXISTING:
d9b902db
PB
2037 break;
2038 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
2039 /* create new image with backing file */
cf8f2426
LC
2040 bdrv_img_create(target, format,
2041 source->filename,
2042 source->drv->format_name,
f382d43a 2043 NULL, size, flags, &local_err, false);
d9b902db
PB
2044 break;
2045 default:
2046 abort();
2047 }
2048 }
2049
cf8f2426
LC
2050 if (error_is_set(&local_err)) {
2051 error_propagate(errp, local_err);
d9b902db
PB
2052 return;
2053 }
2054
b812f671
PB
2055 /* Mirroring takes care of copy-on-write using the source's backing
2056 * file.
2057 */
d9b902db 2058 target_bs = bdrv_new("");
34b5d2c6
MR
2059 ret = bdrv_open(target_bs, target, NULL, flags | BDRV_O_NO_BACKING, drv,
2060 &local_err);
d9b902db 2061 if (ret < 0) {
4f6fd349 2062 bdrv_unref(target_bs);
34b5d2c6 2063 error_propagate(errp, local_err);
d9b902db
PB
2064 return;
2065 }
2066
08e4ed6c 2067 mirror_start(bs, target_bs, speed, granularity, buf_size, sync,
eee13dfe 2068 on_source_error, on_target_error,
b952b558 2069 block_job_cb, bs, &local_err);
d9b902db 2070 if (local_err != NULL) {
4f6fd349 2071 bdrv_unref(target_bs);
d9b902db
PB
2072 error_propagate(errp, local_err);
2073 return;
2074 }
d9b902db
PB
2075}
2076
2d47c6e9
SH
2077static BlockJob *find_block_job(const char *device)
2078{
2079 BlockDriverState *bs;
2080
2081 bs = bdrv_find(device);
2082 if (!bs || !bs->job) {
2083 return NULL;
2084 }
2085 return bs->job;
2086}
2087
882ec7ce 2088void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2d47c6e9
SH
2089{
2090 BlockJob *job = find_block_job(device);
2091
2092 if (!job) {
7ef15070 2093 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2d47c6e9
SH
2094 return;
2095 }
2096
882ec7ce 2097 block_job_set_speed(job, speed, errp);
2d47c6e9 2098}
370521a1 2099
6e37fb81
PB
2100void qmp_block_job_cancel(const char *device,
2101 bool has_force, bool force, Error **errp)
370521a1
SH
2102{
2103 BlockJob *job = find_block_job(device);
2104
6e37fb81
PB
2105 if (!has_force) {
2106 force = false;
2107 }
2108
370521a1 2109 if (!job) {
7ef15070 2110 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
370521a1
SH
2111 return;
2112 }
6e37fb81 2113 if (job->paused && !force) {
8acc72a4
PB
2114 error_set(errp, QERR_BLOCK_JOB_PAUSED, device);
2115 return;
2116 }
370521a1
SH
2117
2118 trace_qmp_block_job_cancel(job);
2119 block_job_cancel(job);
2120}
fb5458cd 2121
6e37fb81
PB
2122void qmp_block_job_pause(const char *device, Error **errp)
2123{
2124 BlockJob *job = find_block_job(device);
2125
2126 if (!job) {
2127 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2128 return;
2129 }
2130
2131 trace_qmp_block_job_pause(job);
2132 block_job_pause(job);
2133}
2134
2135void qmp_block_job_resume(const char *device, Error **errp)
2136{
2137 BlockJob *job = find_block_job(device);
2138
2139 if (!job) {
2140 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2141 return;
2142 }
2143
2144 trace_qmp_block_job_resume(job);
2145 block_job_resume(job);
2146}
2147
aeae883b
PB
2148void qmp_block_job_complete(const char *device, Error **errp)
2149{
2150 BlockJob *job = find_block_job(device);
2151
2152 if (!job) {
2153 error_set(errp, QERR_BLOCK_JOB_NOT_ACTIVE, device);
2154 return;
2155 }
2156
2157 trace_qmp_block_job_complete(job);
2158 block_job_complete(job, errp);
2159}
2160
d26c9a15
KW
2161void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
2162{
2163 QmpOutputVisitor *ov = qmp_output_visitor_new();
2164 QObject *obj;
2165 QDict *qdict;
d26c9a15
KW
2166 Error *local_err = NULL;
2167
2168 /* Require an ID in the top level */
2169 if (!options->has_id) {
2170 error_setg(errp, "Block device needs an ID");
2171 goto fail;
2172 }
2173
2174 /* TODO Sort it out in raw-posix and drive_init: Reject aio=native with
2175 * cache.direct=false instead of silently switching to aio=threads, except
2176 * if called from drive_init.
2177 *
2178 * For now, simply forbidding the combination for all drivers will do. */
2179 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
2180 bool direct = options->cache->has_direct && options->cache->direct;
2181 if (!options->has_cache && !direct) {
2182 error_setg(errp, "aio=native requires cache.direct=true");
2183 goto fail;
2184 }
2185 }
2186
2187 visit_type_BlockdevOptions(qmp_output_get_visitor(ov),
2188 &options, NULL, &local_err);
2189 if (error_is_set(&local_err)) {
2190 error_propagate(errp, local_err);
2191 goto fail;
2192 }
2193
2194 obj = qmp_output_get_qobject(ov);
2195 qdict = qobject_to_qdict(obj);
2196
2197 qdict_flatten(qdict);
2198
b681072d
KW
2199 blockdev_init(qdict, IF_NONE, &local_err);
2200 if (error_is_set(&local_err)) {
2201 error_propagate(errp, local_err);
d26c9a15
KW
2202 goto fail;
2203 }
2204
2205fail:
2206 qmp_output_visitor_cleanup(ov);
2207}
2208
fb5458cd
SH
2209static void do_qmp_query_block_jobs_one(void *opaque, BlockDriverState *bs)
2210{
2211 BlockJobInfoList **prev = opaque;
2212 BlockJob *job = bs->job;
2213
2214 if (job) {
30e628b7
PB
2215 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
2216 elem->value = block_job_query(bs->job);
fb5458cd
SH
2217 (*prev)->next = elem;
2218 *prev = elem;
2219 }
2220}
2221
2222BlockJobInfoList *qmp_query_block_jobs(Error **errp)
2223{
2224 /* Dummy is a fake list element for holding the head pointer */
2225 BlockJobInfoList dummy = {};
2226 BlockJobInfoList *prev = &dummy;
2227 bdrv_iterate(do_qmp_query_block_jobs_one, &prev);
2228 return dummy.next;
2229}
4d454574 2230
0006383e 2231QemuOptsList qemu_common_drive_opts = {
4d454574 2232 .name = "drive",
0006383e 2233 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4d454574
PB
2234 .desc = {
2235 {
4d454574
PB
2236 .name = "snapshot",
2237 .type = QEMU_OPT_BOOL,
2238 .help = "enable/disable snapshot mode",
2239 },{
2240 .name = "file",
2241 .type = QEMU_OPT_STRING,
2242 .help = "disk image",
a9384aff
PB
2243 },{
2244 .name = "discard",
2245 .type = QEMU_OPT_STRING,
2246 .help = "discard operation (ignore/off, unmap/on)",
4d454574 2247 },{
29c4e2b5
KW
2248 .name = "cache.writeback",
2249 .type = QEMU_OPT_BOOL,
2250 .help = "enables writeback mode for any caches",
2251 },{
2252 .name = "cache.direct",
2253 .type = QEMU_OPT_BOOL,
2254 .help = "enables use of O_DIRECT (bypass the host page cache)",
2255 },{
2256 .name = "cache.no-flush",
2257 .type = QEMU_OPT_BOOL,
2258 .help = "ignore any flush requests for the device",
4d454574
PB
2259 },{
2260 .name = "aio",
2261 .type = QEMU_OPT_STRING,
2262 .help = "host AIO implementation (threads, native)",
2263 },{
2264 .name = "format",
2265 .type = QEMU_OPT_STRING,
2266 .help = "disk format (raw, qcow2, ...)",
2267 },{
2268 .name = "serial",
2269 .type = QEMU_OPT_STRING,
2270 .help = "disk serial number",
2271 },{
2272 .name = "rerror",
2273 .type = QEMU_OPT_STRING,
2274 .help = "read error action",
2275 },{
2276 .name = "werror",
2277 .type = QEMU_OPT_STRING,
2278 .help = "write error action",
4d454574 2279 },{
0f227a94 2280 .name = "read-only",
4d454574
PB
2281 .type = QEMU_OPT_BOOL,
2282 .help = "open drive file as read-only",
2283 },{
57975222 2284 .name = "throttling.iops-total",
4d454574
PB
2285 .type = QEMU_OPT_NUMBER,
2286 .help = "limit total I/O operations per second",
2287 },{
57975222 2288 .name = "throttling.iops-read",
4d454574
PB
2289 .type = QEMU_OPT_NUMBER,
2290 .help = "limit read operations per second",
2291 },{
57975222 2292 .name = "throttling.iops-write",
4d454574
PB
2293 .type = QEMU_OPT_NUMBER,
2294 .help = "limit write operations per second",
2295 },{
57975222 2296 .name = "throttling.bps-total",
4d454574
PB
2297 .type = QEMU_OPT_NUMBER,
2298 .help = "limit total bytes per second",
2299 },{
57975222 2300 .name = "throttling.bps-read",
4d454574
PB
2301 .type = QEMU_OPT_NUMBER,
2302 .help = "limit read bytes per second",
2303 },{
57975222 2304 .name = "throttling.bps-write",
4d454574
PB
2305 .type = QEMU_OPT_NUMBER,
2306 .help = "limit write bytes per second",
3e9fab69
BC
2307 },{
2308 .name = "throttling.iops-total-max",
2309 .type = QEMU_OPT_NUMBER,
2310 .help = "I/O operations burst",
2311 },{
2312 .name = "throttling.iops-read-max",
2313 .type = QEMU_OPT_NUMBER,
2314 .help = "I/O operations read burst",
2315 },{
2316 .name = "throttling.iops-write-max",
2317 .type = QEMU_OPT_NUMBER,
2318 .help = "I/O operations write burst",
2319 },{
2320 .name = "throttling.bps-total-max",
2321 .type = QEMU_OPT_NUMBER,
2322 .help = "total bytes burst",
2323 },{
2324 .name = "throttling.bps-read-max",
2325 .type = QEMU_OPT_NUMBER,
2326 .help = "total bytes read burst",
2327 },{
2328 .name = "throttling.bps-write-max",
2329 .type = QEMU_OPT_NUMBER,
2330 .help = "total bytes write burst",
2024c1df
BC
2331 },{
2332 .name = "throttling.iops-size",
2333 .type = QEMU_OPT_NUMBER,
2334 .help = "when limiting by iops max size of an I/O in bytes",
4d454574
PB
2335 },{
2336 .name = "copy-on-read",
2337 .type = QEMU_OPT_BOOL,
2338 .help = "copy read data from backing file into image file",
4d454574
PB
2339 },
2340 { /* end of list */ }
2341 },
2342};
0006383e
KW
2343
2344QemuOptsList qemu_drive_opts = {
2345 .name = "drive",
2346 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
2347 .desc = {
492fdc6f
KW
2348 /*
2349 * no elements => accept any params
2350 * validation will happen later
2351 */
0006383e
KW
2352 { /* end of list */ }
2353 },
2354};