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