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