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