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