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