]> git.proxmox.com Git - mirror_qemu.git/blame - blockdev.c
block: Accept node-name for block-commit
[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
d38ea87a 33#include "qemu/osdep.h"
26f54e9a 34#include "sysemu/block-backend.h"
9c17d615 35#include "sysemu/blockdev.h"
0d09e41a 36#include "hw/block/block.h"
737e150e 37#include "block/blockjob.h"
76f4afb4 38#include "block/throttle-groups.h"
83c9089e 39#include "monitor/monitor.h"
d49b6836 40#include "qemu/error-report.h"
1de7afc9
PB
41#include "qemu/option.h"
42#include "qemu/config-file.h"
7b1b5d19 43#include "qapi/qmp/types.h"
d26c9a15 44#include "qapi-visit.h"
cc7a8ea7 45#include "qapi/qmp/qerror.h"
d26c9a15 46#include "qapi/qmp-output-visitor.h"
9e7dac7c 47#include "qapi/util.h"
9c17d615 48#include "sysemu/sysemu.h"
737e150e 49#include "block/block_int.h"
a4dea8a9 50#include "qmp-commands.h"
12bd451f 51#include "trace.h"
9c17d615 52#include "sysemu/arch_init.h"
f348b6d1
VB
53#include "qemu/cutils.h"
54#include "qemu/help_option.h"
666daa68 55
9c4218e9
HR
56static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
57 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
58
bf18bee5
CL
59static int do_open_tray(const char *device, bool force, Error **errp);
60
1960966d
MA
61static const char *const if_name[IF_COUNT] = {
62 [IF_NONE] = "none",
63 [IF_IDE] = "ide",
64 [IF_SCSI] = "scsi",
65 [IF_FLOPPY] = "floppy",
66 [IF_PFLASH] = "pflash",
67 [IF_MTD] = "mtd",
68 [IF_SD] = "sd",
69 [IF_VIRTIO] = "virtio",
70 [IF_XEN] = "xen",
71};
72
21dff8cf 73static int if_max_devs[IF_COUNT] = {
27d6bf40
MA
74 /*
75 * Do not change these numbers! They govern how drive option
76 * index maps to unit and bus. That mapping is ABI.
77 *
547cb157 78 * All controllers used to implement if=T drives need to support
27d6bf40
MA
79 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
80 * Otherwise, some index values map to "impossible" bus, unit
81 * values.
82 *
83 * For instance, if you change [IF_SCSI] to 255, -drive
84 * if=scsi,index=12 no longer means bus=1,unit=5, but
85 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
86 * the drive can't be set up. Regression.
87 */
88 [IF_IDE] = 2,
89 [IF_SCSI] = 7,
1960966d
MA
90};
91
21dff8cf
JS
92/**
93 * Boards may call this to offer board-by-board overrides
94 * of the default, global values.
95 */
96void override_max_devs(BlockInterfaceType type, int max_devs)
97{
18e46a03 98 BlockBackend *blk;
21dff8cf
JS
99 DriveInfo *dinfo;
100
101 if (max_devs <= 0) {
102 return;
103 }
104
18e46a03
MA
105 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
106 dinfo = blk_legacy_dinfo(blk);
21dff8cf
JS
107 if (dinfo->type == type) {
108 fprintf(stderr, "Cannot override units-per-bus property of"
109 " the %s interface, because a drive of that type has"
110 " already been added.\n", if_name[type]);
111 g_assert_not_reached();
112 }
113 }
114
115 if_max_devs[type] = max_devs;
116}
117
14bafc54
MA
118/*
119 * We automatically delete the drive when a device using it gets
120 * unplugged. Questionable feature, but we can't just drop it.
121 * Device models call blockdev_mark_auto_del() to schedule the
122 * automatic deletion, and generic qdev code calls blockdev_auto_del()
123 * when deletion is actually safe.
124 */
4be74634 125void blockdev_mark_auto_del(BlockBackend *blk)
14bafc54 126{
18e46a03 127 DriveInfo *dinfo = blk_legacy_dinfo(blk);
4be74634 128 BlockDriverState *bs = blk_bs(blk);
91fddb0d 129 AioContext *aio_context;
14bafc54 130
26f8b3a8 131 if (!dinfo) {
2d246f01
KW
132 return;
133 }
134
5433c24f
HR
135 if (bs) {
136 aio_context = bdrv_get_aio_context(bs);
137 aio_context_acquire(aio_context);
91fddb0d 138
5433c24f
HR
139 if (bs->job) {
140 block_job_cancel(bs->job);
141 }
91fddb0d 142
5433c24f
HR
143 aio_context_release(aio_context);
144 }
91fddb0d 145
26f8b3a8 146 dinfo->auto_del = 1;
14bafc54
MA
147}
148
4be74634 149void blockdev_auto_del(BlockBackend *blk)
14bafc54 150{
18e46a03 151 DriveInfo *dinfo = blk_legacy_dinfo(blk);
14bafc54 152
0fc0f1fa 153 if (dinfo && dinfo->auto_del) {
efaa7c4e 154 monitor_remove_blk(blk);
b9fe8a7a 155 blk_unref(blk);
14bafc54
MA
156 }
157}
158
d8f94e1b
JS
159/**
160 * Returns the current mapping of how many units per bus
161 * a particular interface can support.
162 *
163 * A positive integer indicates n units per bus.
164 * 0 implies the mapping has not been established.
165 * -1 indicates an invalid BlockInterfaceType was given.
166 */
167int drive_get_max_devs(BlockInterfaceType type)
168{
169 if (type >= IF_IDE && type < IF_COUNT) {
170 return if_max_devs[type];
171 }
172
173 return -1;
174}
175
505a7fb1
MA
176static int drive_index_to_bus_id(BlockInterfaceType type, int index)
177{
178 int max_devs = if_max_devs[type];
179 return max_devs ? index / max_devs : 0;
180}
181
182static int drive_index_to_unit_id(BlockInterfaceType type, int index)
183{
184 int max_devs = if_max_devs[type];
185 return max_devs ? index % max_devs : index;
186}
187
2292ddae
MA
188QemuOpts *drive_def(const char *optstr)
189{
70b94331 190 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
2292ddae
MA
191}
192
193QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
5645b0f4 194 const char *optstr)
666daa68 195{
666daa68
MA
196 QemuOpts *opts;
197
2292ddae 198 opts = drive_def(optstr);
666daa68
MA
199 if (!opts) {
200 return NULL;
201 }
2292ddae 202 if (type != IF_DEFAULT) {
f43e47db 203 qemu_opt_set(opts, "if", if_name[type], &error_abort);
2292ddae
MA
204 }
205 if (index >= 0) {
a8b18f8f 206 qemu_opt_set_number(opts, "index", index, &error_abort);
2292ddae 207 }
666daa68 208 if (file)
f43e47db 209 qemu_opt_set(opts, "file", file, &error_abort);
666daa68
MA
210 return opts;
211}
212
213DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
214{
18e46a03 215 BlockBackend *blk;
666daa68
MA
216 DriveInfo *dinfo;
217
18e46a03
MA
218 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
219 dinfo = blk_legacy_dinfo(blk);
220 if (dinfo && dinfo->type == type
221 && dinfo->bus == bus && dinfo->unit == unit) {
666daa68 222 return dinfo;
18e46a03 223 }
666daa68
MA
224 }
225
226 return NULL;
227}
228
a66c9dc7
JS
229bool drive_check_orphaned(void)
230{
18e46a03 231 BlockBackend *blk;
a66c9dc7
JS
232 DriveInfo *dinfo;
233 bool rs = false;
234
18e46a03
MA
235 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
236 dinfo = blk_legacy_dinfo(blk);
a66c9dc7
JS
237 /* If dinfo->bdrv->dev is NULL, it has no device attached. */
238 /* Unless this is a default drive, this may be an oversight. */
a7f53e26 239 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
a66c9dc7
JS
240 dinfo->type != IF_NONE) {
241 fprintf(stderr, "Warning: Orphaned drive without device: "
242 "id=%s,file=%s,if=%s,bus=%d,unit=%d\n",
5433c24f
HR
243 blk_name(blk), blk_bs(blk) ? blk_bs(blk)->filename : "",
244 if_name[dinfo->type], dinfo->bus, dinfo->unit);
a66c9dc7
JS
245 rs = true;
246 }
247 }
248
249 return rs;
250}
251
f1bd51ac
MA
252DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
253{
254 return drive_get(type,
255 drive_index_to_bus_id(type, index),
256 drive_index_to_unit_id(type, index));
257}
258
666daa68
MA
259int drive_get_max_bus(BlockInterfaceType type)
260{
261 int max_bus;
18e46a03 262 BlockBackend *blk;
666daa68
MA
263 DriveInfo *dinfo;
264
265 max_bus = -1;
18e46a03
MA
266 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
267 dinfo = blk_legacy_dinfo(blk);
268 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
666daa68 269 max_bus = dinfo->bus;
18e46a03 270 }
666daa68
MA
271 }
272 return max_bus;
273}
274
13839974
MA
275/* Get a block device. This should only be used for single-drive devices
276 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
277 appropriate bus. */
278DriveInfo *drive_get_next(BlockInterfaceType type)
279{
280 static int next_block_unit[IF_COUNT];
281
282 return drive_get(type, 0, next_block_unit[type]++);
283}
284
666daa68
MA
285static void bdrv_format_print(void *opaque, const char *name)
286{
807105a7 287 error_printf(" %s", name);
666daa68
MA
288}
289
aa398a5c
SH
290typedef struct {
291 QEMUBH *bh;
fa510ebf
FZ
292 BlockDriverState *bs;
293} BDRVPutRefBH;
aa398a5c 294
b681072d 295static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
666daa68
MA
296{
297 if (!strcmp(buf, "ignore")) {
92aa5c6d 298 return BLOCKDEV_ON_ERROR_IGNORE;
666daa68 299 } else if (!is_read && !strcmp(buf, "enospc")) {
92aa5c6d 300 return BLOCKDEV_ON_ERROR_ENOSPC;
666daa68 301 } else if (!strcmp(buf, "stop")) {
92aa5c6d 302 return BLOCKDEV_ON_ERROR_STOP;
666daa68 303 } else if (!strcmp(buf, "report")) {
92aa5c6d 304 return BLOCKDEV_ON_ERROR_REPORT;
666daa68 305 } else {
b681072d
KW
306 error_setg(errp, "'%s' invalid %s error action",
307 buf, is_read ? "read" : "write");
666daa68
MA
308 return -1;
309 }
310}
311
40119eff
AG
312static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
313 Error **errp)
314{
315 const QListEntry *entry;
316 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
317 switch (qobject_type(entry->value)) {
318
319 case QTYPE_QSTRING: {
320 unsigned long long length;
321 const char *str = qstring_get_str(qobject_to_qstring(entry->value));
322 if (parse_uint_full(str, &length, 10) == 0 &&
323 length > 0 && length <= UINT_MAX) {
324 block_acct_add_interval(stats, (unsigned) length);
325 } else {
326 error_setg(errp, "Invalid interval length: %s", str);
327 return false;
328 }
329 break;
330 }
331
332 case QTYPE_QINT: {
333 int64_t length = qint_get_int(qobject_to_qint(entry->value));
334 if (length > 0 && length <= UINT_MAX) {
335 block_acct_add_interval(stats, (unsigned) length);
336 } else {
337 error_setg(errp, "Invalid interval length: %" PRId64, length);
338 return false;
339 }
340 break;
341 }
342
343 default:
344 error_setg(errp, "The specification of stats-intervals is invalid");
345 return false;
346 }
347 }
348 return true;
349}
350
33cb7dc8
KW
351typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
352
fbf8175e
HR
353/* All parameters but @opts are optional and may be set to NULL. */
354static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
355 const char **throttling_group, ThrottleConfig *throttle_cfg,
356 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
357{
358 const char *discard;
359 Error *local_error = NULL;
360 const char *aio;
361
362 if (bdrv_flags) {
363 if (!qemu_opt_get_bool(opts, "read-only", false)) {
364 *bdrv_flags |= BDRV_O_RDWR;
365 }
366 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
367 *bdrv_flags |= BDRV_O_COPY_ON_READ;
368 }
369
370 if ((discard = qemu_opt_get(opts, "discard")) != NULL) {
371 if (bdrv_parse_discard_flags(discard, bdrv_flags) != 0) {
372 error_setg(errp, "Invalid discard option");
373 return;
374 }
375 }
376
fbf8175e
HR
377 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
378 if (!strcmp(aio, "native")) {
379 *bdrv_flags |= BDRV_O_NATIVE_AIO;
380 } else if (!strcmp(aio, "threads")) {
381 /* this is the default */
382 } else {
383 error_setg(errp, "invalid aio option");
384 return;
385 }
386 }
387 }
388
389 /* disk I/O throttling */
390 if (throttling_group) {
391 *throttling_group = qemu_opt_get(opts, "throttling.group");
392 }
393
394 if (throttle_cfg) {
1588ab5d 395 throttle_config_init(throttle_cfg);
fbf8175e
HR
396 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
397 qemu_opt_get_number(opts, "throttling.bps-total", 0);
398 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
399 qemu_opt_get_number(opts, "throttling.bps-read", 0);
400 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
401 qemu_opt_get_number(opts, "throttling.bps-write", 0);
402 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
403 qemu_opt_get_number(opts, "throttling.iops-total", 0);
404 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
405 qemu_opt_get_number(opts, "throttling.iops-read", 0);
406 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
407 qemu_opt_get_number(opts, "throttling.iops-write", 0);
408
409 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
410 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
411 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
412 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
413 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
414 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
415 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
416 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
417 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
418 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
419 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
420 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
421
8a0fc18d
AG
422 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
423 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
424 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
425 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
426 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
427 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
428 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
429 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
430 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
431 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
432 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
433 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
434
fbf8175e
HR
435 throttle_cfg->op_size =
436 qemu_opt_get_number(opts, "throttling.iops-size", 0);
437
d5851089 438 if (!throttle_is_valid(throttle_cfg, errp)) {
fbf8175e
HR
439 return;
440 }
441 }
442
443 if (detect_zeroes) {
444 *detect_zeroes =
445 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
446 qemu_opt_get(opts, "detect-zeroes"),
7fb1cf16 447 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
fbf8175e
HR
448 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
449 &local_error);
450 if (local_error) {
451 error_propagate(errp, local_error);
452 return;
453 }
454
455 if (bdrv_flags &&
456 *detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
457 !(*bdrv_flags & BDRV_O_UNMAP))
458 {
459 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
460 "without setting discard operation to unmap");
461 return;
462 }
463 }
464}
465
f298d071 466/* Takes the ownership of bs_opts */
18e46a03
MA
467static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
468 Error **errp)
666daa68
MA
469{
470 const char *buf;
666daa68
MA
471 int bdrv_flags = 0;
472 int on_read_error, on_write_error;
362e9299 473 bool account_invalid, account_failed;
e4b24b49 474 bool writethrough;
26f54e9a 475 BlockBackend *blk;
a0f1eab1 476 BlockDriverState *bs;
cc0681c4 477 ThrottleConfig cfg;
666daa68 478 int snapshot = 0;
c546194f 479 Error *error = NULL;
0006383e 480 QemuOpts *opts;
40119eff
AG
481 QDict *interval_dict = NULL;
482 QList *interval_list = NULL;
0006383e 483 const char *id;
fbf8175e
HR
484 BlockdevDetectZeroesOptions detect_zeroes =
485 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
486 const char *throttling_group = NULL;
666daa68 487
f298d071
KW
488 /* Check common options by copying from bs_opts to opts, all other options
489 * stay in bs_opts for processing by bdrv_open(). */
490 id = qdict_get_try_str(bs_opts, "id");
0006383e 491 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
84d18f06 492 if (error) {
b681072d 493 error_propagate(errp, error);
6376f952 494 goto err_no_opts;
0006383e
KW
495 }
496
0006383e 497 qemu_opts_absorb_qdict(opts, bs_opts, &error);
84d18f06 498 if (error) {
b681072d 499 error_propagate(errp, error);
ec9c10d2 500 goto early_err;
0006383e
KW
501 }
502
503 if (id) {
504 qdict_del(bs_opts, "id");
505 }
506
666daa68 507 /* extract parameters */
666daa68 508 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
666daa68 509
362e9299
AG
510 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
511 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
512
e4b24b49
KW
513 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
514
ff356ee4
AG
515 id = qemu_opts_id(opts);
516
40119eff
AG
517 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
518 qdict_array_split(interval_dict, &interval_list);
519
520 if (qdict_size(interval_dict) != 0) {
521 error_setg(errp, "Invalid option stats-intervals.%s",
522 qdict_first(interval_dict)->key);
523 goto early_err;
524 }
2be5506f 525
fbf8175e
HR
526 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
527 &detect_zeroes, &error);
528 if (error) {
529 error_propagate(errp, error);
530 goto early_err;
666daa68 531 }
666daa68
MA
532
533 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
c8057f95
PM
534 if (is_help_option(buf)) {
535 error_printf("Supported formats:");
536 bdrv_iterate_format(bdrv_format_print, NULL);
537 error_printf("\n");
ec9c10d2 538 goto early_err;
666daa68 539 }
74fe54f2 540
e4342ce5
HR
541 if (qdict_haskey(bs_opts, "driver")) {
542 error_setg(errp, "Cannot specify both 'driver' and 'format'");
ec9c10d2 543 goto early_err;
6db5f5d6 544 }
e4342ce5 545 qdict_put(bs_opts, "driver", qstring_from_str(buf));
666daa68
MA
546 }
547
92aa5c6d 548 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
666daa68 549 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
b681072d 550 on_write_error = parse_block_error_action(buf, 0, &error);
84d18f06 551 if (error) {
b681072d 552 error_propagate(errp, error);
ec9c10d2 553 goto early_err;
666daa68
MA
554 }
555 }
556
92aa5c6d 557 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
666daa68 558 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
b681072d 559 on_read_error = parse_block_error_action(buf, 1, &error);
84d18f06 560 if (error) {
b681072d 561 error_propagate(errp, error);
ec9c10d2 562 goto early_err;
666daa68
MA
563 }
564 }
565
5ec18f8c 566 if (snapshot) {
91a097e7 567 bdrv_flags |= BDRV_O_SNAPSHOT;
5ec18f8c
HR
568 }
569
326642bc 570 /* init */
39c4ae94 571 if ((!file || !*file) && !qdict_size(bs_opts)) {
5ec18f8c
HR
572 BlockBackendRootState *blk_rs;
573
109525ad 574 blk = blk_new();
5ec18f8c
HR
575 blk_rs = blk_get_root_state(blk);
576 blk_rs->open_flags = bdrv_flags;
fbf8175e 577 blk_rs->read_only = !(bdrv_flags & BDRV_O_RDWR);
5ec18f8c
HR
578 blk_rs->detect_zeroes = detect_zeroes;
579
e4342ce5
HR
580 QDECREF(bs_opts);
581 } else {
582 if (file && !*file) {
c2ad1b0c 583 file = NULL;
c2ad1b0c 584 }
666daa68 585
91a097e7
KW
586 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
587 * with other callers) rather than what we want as the real defaults.
588 * Apply the defaults here instead. */
91a097e7
KW
589 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
590 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
72e775c7 591 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
91a097e7 592
12d5ee3a
KW
593 if (runstate_check(RUN_STATE_INMIGRATE)) {
594 bdrv_flags |= BDRV_O_INACTIVE;
595 }
596
efaa7c4e 597 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
e4342ce5
HR
598 if (!blk) {
599 goto err_no_bs_opts;
600 }
601 bs = blk_bs(blk);
ed9d4205 602
5ec18f8c 603 bs->detect_zeroes = detect_zeroes;
666daa68 604
5ec18f8c
HR
605 if (bdrv_key_required(bs)) {
606 autostart = 0;
76f4afb4 607 }
362e9299
AG
608
609 block_acct_init(blk_get_stats(blk), account_invalid, account_failed);
2be5506f 610
40119eff
AG
611 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
612 blk_unref(blk);
613 blk = NULL;
614 goto err_no_bs_opts;
2be5506f 615 }
666daa68
MA
616 }
617
7ca7f0f6
KW
618 /* disk I/O throttling */
619 if (throttle_enabled(&cfg)) {
620 if (!throttling_group) {
ff356ee4 621 throttling_group = id;
7ca7f0f6
KW
622 }
623 blk_io_limits_enable(blk, throttling_group);
624 blk_set_io_limits(blk, &cfg);
625 }
626
e4b24b49 627 blk_set_enable_write_cache(blk, !writethrough);
5ec18f8c 628 blk_set_on_error(blk, on_read_error, on_write_error);
0006383e 629
ff356ee4 630 if (!monitor_add_blk(blk, id, errp)) {
efaa7c4e
HR
631 blk_unref(blk);
632 blk = NULL;
633 goto err_no_bs_opts;
634 }
635
e4342ce5 636err_no_bs_opts:
0006383e 637 qemu_opts_del(opts);
40119eff
AG
638 QDECREF(interval_dict);
639 QDECREF(interval_list);
18e46a03 640 return blk;
a9ae2bff 641
ec9c10d2 642early_err:
ec9c10d2 643 qemu_opts_del(opts);
40119eff
AG
644 QDECREF(interval_dict);
645 QDECREF(interval_list);
6376f952
MA
646err_no_opts:
647 QDECREF(bs_opts);
a9ae2bff 648 return NULL;
666daa68
MA
649}
650
bd745e23
HR
651static QemuOptsList qemu_root_bds_opts;
652
653/* Takes the ownership of bs_opts */
654static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
655{
656 BlockDriverState *bs;
657 QemuOpts *opts;
658 Error *local_error = NULL;
659 BlockdevDetectZeroesOptions detect_zeroes;
bd745e23
HR
660 int bdrv_flags = 0;
661
662 opts = qemu_opts_create(&qemu_root_bds_opts, NULL, 1, errp);
663 if (!opts) {
664 goto fail;
665 }
666
667 qemu_opts_absorb_qdict(opts, bs_opts, &local_error);
668 if (local_error) {
669 error_propagate(errp, local_error);
670 goto fail;
671 }
672
673 extract_common_blockdev_options(opts, &bdrv_flags, NULL, NULL,
674 &detect_zeroes, &local_error);
675 if (local_error) {
676 error_propagate(errp, local_error);
677 goto fail;
678 }
679
a81d6164
KW
680 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
681 * with other callers) rather than what we want as the real defaults.
682 * Apply the defaults here instead. */
a81d6164
KW
683 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
684 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
685
12d5ee3a
KW
686 if (runstate_check(RUN_STATE_INMIGRATE)) {
687 bdrv_flags |= BDRV_O_INACTIVE;
688 }
689
5b363937
HR
690 bs = bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
691 if (!bs) {
bd745e23
HR
692 goto fail_no_bs_opts;
693 }
694
695 bs->detect_zeroes = detect_zeroes;
696
697fail_no_bs_opts:
698 qemu_opts_del(opts);
699 return bs;
700
701fail:
702 qemu_opts_del(opts);
703 QDECREF(bs_opts);
704 return NULL;
705}
706
9c4218e9
HR
707void blockdev_close_all_bdrv_states(void)
708{
709 BlockDriverState *bs, *next_bs;
710
711 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
712 AioContext *ctx = bdrv_get_aio_context(bs);
713
714 aio_context_acquire(ctx);
715 bdrv_unref(bs);
716 aio_context_release(ctx);
717 }
718}
719
262b4e8f
HR
720/* Iterates over the list of monitor-owned BlockDriverStates */
721BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
722{
723 return bs ? QTAILQ_NEXT(bs, monitor_list)
724 : QTAILQ_FIRST(&monitor_bdrv_states);
725}
726
5abbf0ee
KW
727static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
728 Error **errp)
57975222
KW
729{
730 const char *value;
731
732 value = qemu_opt_get(opts, from);
733 if (value) {
5abbf0ee
KW
734 if (qemu_opt_find(opts, to)) {
735 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
736 "same time", to, from);
737 return;
738 }
20d6cd47
JL
739 }
740
741 /* rename all items in opts */
742 while ((value = qemu_opt_get(opts, from))) {
f43e47db 743 qemu_opt_set(opts, to, value, &error_abort);
57975222
KW
744 qemu_opt_unset(opts, from);
745 }
746}
747
33cb7dc8
KW
748QemuOptsList qemu_legacy_drive_opts = {
749 .name = "drive",
750 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
751 .desc = {
752 {
87a899c5
KW
753 .name = "bus",
754 .type = QEMU_OPT_NUMBER,
755 .help = "bus number",
756 },{
757 .name = "unit",
758 .type = QEMU_OPT_NUMBER,
759 .help = "unit number (i.e. lun for scsi)",
760 },{
761 .name = "index",
762 .type = QEMU_OPT_NUMBER,
763 .help = "index number",
764 },{
33cb7dc8
KW
765 .name = "media",
766 .type = QEMU_OPT_STRING,
767 .help = "media type (disk, cdrom)",
593d464b
KW
768 },{
769 .name = "if",
770 .type = QEMU_OPT_STRING,
771 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
b41a7338
KW
772 },{
773 .name = "cyls",
774 .type = QEMU_OPT_NUMBER,
775 .help = "number of cylinders (ide disk geometry)",
776 },{
777 .name = "heads",
778 .type = QEMU_OPT_NUMBER,
779 .help = "number of heads (ide disk geometry)",
780 },{
781 .name = "secs",
782 .type = QEMU_OPT_NUMBER,
783 .help = "number of sectors (ide disk geometry)",
784 },{
785 .name = "trans",
786 .type = QEMU_OPT_STRING,
787 .help = "chs translation (auto, lba, none)",
26929298
KW
788 },{
789 .name = "boot",
790 .type = QEMU_OPT_BOOL,
791 .help = "(deprecated, ignored)",
394c7d4d
KW
792 },{
793 .name = "addr",
794 .type = QEMU_OPT_STRING,
795 .help = "pci address (virtio only)",
bcf83158
KW
796 },{
797 .name = "serial",
798 .type = QEMU_OPT_STRING,
799 .help = "disk serial number",
d095b465
HR
800 },{
801 .name = "file",
802 .type = QEMU_OPT_STRING,
803 .help = "file name",
33cb7dc8 804 },
0ebd24e0
KW
805
806 /* Options that are passed on, but have special semantics with -drive */
807 {
808 .name = "read-only",
809 .type = QEMU_OPT_BOOL,
810 .help = "open drive file as read-only",
ee13ed1c
KW
811 },{
812 .name = "rerror",
813 .type = QEMU_OPT_STRING,
814 .help = "read error action",
815 },{
816 .name = "werror",
817 .type = QEMU_OPT_STRING,
818 .help = "write error action",
0ebd24e0
KW
819 },{
820 .name = "copy-on-read",
821 .type = QEMU_OPT_BOOL,
822 .help = "copy read data from backing file into image file",
823 },
824
33cb7dc8
KW
825 { /* end of list */ }
826 },
827};
828
60e19e06 829DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type)
57975222 830{
29c4e2b5 831 const char *value;
18e46a03 832 BlockBackend *blk;
33cb7dc8 833 DriveInfo *dinfo = NULL;
f298d071 834 QDict *bs_opts;
33cb7dc8
KW
835 QemuOpts *legacy_opts;
836 DriveMediaType media = MEDIA_DISK;
593d464b 837 BlockInterfaceType type;
b41a7338 838 int cyls, heads, secs, translation;
87a899c5 839 int max_devs, bus_id, unit_id, index;
394c7d4d 840 const char *devaddr;
ee13ed1c 841 const char *werror, *rerror;
a7fdbcf0
FZ
842 bool read_only = false;
843 bool copy_on_read;
bcf83158 844 const char *serial;
d095b465 845 const char *filename;
33cb7dc8 846 Error *local_err = NULL;
247147fb 847 int i;
29c4e2b5 848
57975222 849 /* Change legacy command line options into QMP ones */
247147fb
KW
850 static const struct {
851 const char *from;
852 const char *to;
853 } opt_renames[] = {
854 { "iops", "throttling.iops-total" },
855 { "iops_rd", "throttling.iops-read" },
856 { "iops_wr", "throttling.iops-write" },
57975222 857
247147fb
KW
858 { "bps", "throttling.bps-total" },
859 { "bps_rd", "throttling.bps-read" },
860 { "bps_wr", "throttling.bps-write" },
57975222 861
247147fb
KW
862 { "iops_max", "throttling.iops-total-max" },
863 { "iops_rd_max", "throttling.iops-read-max" },
864 { "iops_wr_max", "throttling.iops-write-max" },
3e9fab69 865
247147fb
KW
866 { "bps_max", "throttling.bps-total-max" },
867 { "bps_rd_max", "throttling.bps-read-max" },
868 { "bps_wr_max", "throttling.bps-write-max" },
3e9fab69 869
247147fb 870 { "iops_size", "throttling.iops-size" },
2024c1df 871
76f4afb4
AG
872 { "group", "throttling.group" },
873
247147fb
KW
874 { "readonly", "read-only" },
875 };
876
877 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
5abbf0ee
KW
878 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
879 &local_err);
880 if (local_err) {
565f65d2 881 error_report_err(local_err);
5abbf0ee
KW
882 return NULL;
883 }
247147fb 884 }
0f227a94 885
29c4e2b5
KW
886 value = qemu_opt_get(all_opts, "cache");
887 if (value) {
888 int flags = 0;
04feb4a5 889 bool writethrough;
29c4e2b5 890
04feb4a5 891 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
29c4e2b5
KW
892 error_report("invalid cache option");
893 return NULL;
894 }
895
896 /* Specific options take precedence */
54861b92
KW
897 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
898 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
04feb4a5 899 !writethrough, &error_abort);
29c4e2b5 900 }
54861b92
KW
901 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
902 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
cccb7967 903 !!(flags & BDRV_O_NOCACHE), &error_abort);
29c4e2b5 904 }
54861b92
KW
905 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
906 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
cccb7967 907 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
29c4e2b5
KW
908 }
909 qemu_opt_unset(all_opts, "cache");
910 }
911
f298d071
KW
912 /* Get a QDict for processing the options */
913 bs_opts = qdict_new();
914 qemu_opts_to_qdict(all_opts, bs_opts);
915
87ea75d5
PC
916 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
917 &error_abort);
33cb7dc8 918 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
84d18f06 919 if (local_err) {
565f65d2 920 error_report_err(local_err);
33cb7dc8
KW
921 goto fail;
922 }
923
26929298
KW
924 /* Deprecated option boot=[on|off] */
925 if (qemu_opt_get(legacy_opts, "boot") != NULL) {
926 fprintf(stderr, "qemu-kvm: boot=on|off is deprecated and will be "
927 "ignored. Future versions will reject this parameter. Please "
928 "update your scripts.\n");
929 }
930
33cb7dc8
KW
931 /* Media type */
932 value = qemu_opt_get(legacy_opts, "media");
933 if (value) {
934 if (!strcmp(value, "disk")) {
935 media = MEDIA_DISK;
936 } else if (!strcmp(value, "cdrom")) {
937 media = MEDIA_CDROM;
a7fdbcf0 938 read_only = true;
33cb7dc8
KW
939 } else {
940 error_report("'%s' invalid media", value);
941 goto fail;
942 }
943 }
944
0ebd24e0 945 /* copy-on-read is disabled with a warning for read-only devices */
a7fdbcf0 946 read_only |= qemu_opt_get_bool(legacy_opts, "read-only", false);
0ebd24e0
KW
947 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
948
949 if (read_only && copy_on_read) {
950 error_report("warning: disabling copy-on-read on read-only drive");
951 copy_on_read = false;
952 }
953
954 qdict_put(bs_opts, "read-only",
955 qstring_from_str(read_only ? "on" : "off"));
956 qdict_put(bs_opts, "copy-on-read",
957 qstring_from_str(copy_on_read ? "on" :"off"));
958
593d464b
KW
959 /* Controller type */
960 value = qemu_opt_get(legacy_opts, "if");
961 if (value) {
962 for (type = 0;
963 type < IF_COUNT && strcmp(value, if_name[type]);
964 type++) {
965 }
966 if (type == IF_COUNT) {
967 error_report("unsupported bus type '%s'", value);
968 goto fail;
969 }
970 } else {
971 type = block_default_type;
972 }
973
b41a7338
KW
974 /* Geometry */
975 cyls = qemu_opt_get_number(legacy_opts, "cyls", 0);
976 heads = qemu_opt_get_number(legacy_opts, "heads", 0);
977 secs = qemu_opt_get_number(legacy_opts, "secs", 0);
978
979 if (cyls || heads || secs) {
980 if (cyls < 1) {
981 error_report("invalid physical cyls number");
982 goto fail;
983 }
984 if (heads < 1) {
985 error_report("invalid physical heads number");
986 goto fail;
987 }
988 if (secs < 1) {
989 error_report("invalid physical secs number");
990 goto fail;
991 }
992 }
993
994 translation = BIOS_ATA_TRANSLATION_AUTO;
995 value = qemu_opt_get(legacy_opts, "trans");
996 if (value != NULL) {
997 if (!cyls) {
998 error_report("'%s' trans must be used with cyls, heads and secs",
999 value);
1000 goto fail;
1001 }
1002 if (!strcmp(value, "none")) {
1003 translation = BIOS_ATA_TRANSLATION_NONE;
1004 } else if (!strcmp(value, "lba")) {
1005 translation = BIOS_ATA_TRANSLATION_LBA;
f31c41ff
PB
1006 } else if (!strcmp(value, "large")) {
1007 translation = BIOS_ATA_TRANSLATION_LARGE;
1008 } else if (!strcmp(value, "rechs")) {
1009 translation = BIOS_ATA_TRANSLATION_RECHS;
b41a7338
KW
1010 } else if (!strcmp(value, "auto")) {
1011 translation = BIOS_ATA_TRANSLATION_AUTO;
1012 } else {
1013 error_report("'%s' invalid translation type", value);
1014 goto fail;
1015 }
1016 }
1017
1018 if (media == MEDIA_CDROM) {
1019 if (cyls || secs || heads) {
1020 error_report("CHS can't be set with media=cdrom");
1021 goto fail;
1022 }
1023 }
1024
87a899c5
KW
1025 /* Device address specified by bus/unit or index.
1026 * If none was specified, try to find the first free one. */
1027 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
1028 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
1029 index = qemu_opt_get_number(legacy_opts, "index", -1);
1030
1031 max_devs = if_max_devs[type];
1032
1033 if (index != -1) {
1034 if (bus_id != 0 || unit_id != -1) {
1035 error_report("index cannot be used with bus and unit");
1036 goto fail;
1037 }
1038 bus_id = drive_index_to_bus_id(type, index);
1039 unit_id = drive_index_to_unit_id(type, index);
1040 }
1041
1042 if (unit_id == -1) {
1043 unit_id = 0;
1044 while (drive_get(type, bus_id, unit_id) != NULL) {
1045 unit_id++;
1046 if (max_devs && unit_id >= max_devs) {
1047 unit_id -= max_devs;
1048 bus_id++;
1049 }
1050 }
1051 }
1052
1053 if (max_devs && unit_id >= max_devs) {
1054 error_report("unit %d too big (max is %d)", unit_id, max_devs - 1);
1055 goto fail;
1056 }
1057
1058 if (drive_get(type, bus_id, unit_id) != NULL) {
1059 error_report("drive with bus=%d, unit=%d (index=%d) exists",
1060 bus_id, unit_id, index);
1061 goto fail;
1062 }
1063
bcf83158
KW
1064 /* Serial number */
1065 serial = qemu_opt_get(legacy_opts, "serial");
1066
87a899c5
KW
1067 /* no id supplied -> create one */
1068 if (qemu_opts_id(all_opts) == NULL) {
1069 char *new_id;
1070 const char *mediastr = "";
1071 if (type == IF_IDE || type == IF_SCSI) {
1072 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
1073 }
1074 if (max_devs) {
1075 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
1076 mediastr, unit_id);
1077 } else {
1078 new_id = g_strdup_printf("%s%s%i", if_name[type],
1079 mediastr, unit_id);
1080 }
1081 qdict_put(bs_opts, "id", qstring_from_str(new_id));
1082 g_free(new_id);
1083 }
1084
394c7d4d
KW
1085 /* Add virtio block device */
1086 devaddr = qemu_opt_get(legacy_opts, "addr");
1087 if (devaddr && type != IF_VIRTIO) {
1088 error_report("addr is not supported by this bus type");
1089 goto fail;
1090 }
1091
1092 if (type == IF_VIRTIO) {
1093 QemuOpts *devopts;
87ea75d5
PC
1094 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
1095 &error_abort);
394c7d4d 1096 if (arch_type == QEMU_ARCH_S390X) {
1f68f1d3 1097 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
394c7d4d 1098 } else {
f43e47db 1099 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
394c7d4d 1100 }
f43e47db
MA
1101 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
1102 &error_abort);
394c7d4d 1103 if (devaddr) {
f43e47db 1104 qemu_opt_set(devopts, "addr", devaddr, &error_abort);
394c7d4d
KW
1105 }
1106 }
1107
d095b465
HR
1108 filename = qemu_opt_get(legacy_opts, "file");
1109
ee13ed1c
KW
1110 /* Check werror/rerror compatibility with if=... */
1111 werror = qemu_opt_get(legacy_opts, "werror");
1112 if (werror != NULL) {
1113 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
1114 type != IF_NONE) {
1115 error_report("werror is not supported by this bus type");
1116 goto fail;
1117 }
1118 qdict_put(bs_opts, "werror", qstring_from_str(werror));
1119 }
1120
1121 rerror = qemu_opt_get(legacy_opts, "rerror");
1122 if (rerror != NULL) {
1123 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
1124 type != IF_NONE) {
1125 error_report("rerror is not supported by this bus type");
1126 goto fail;
1127 }
1128 qdict_put(bs_opts, "rerror", qstring_from_str(rerror));
1129 }
1130
2d246f01 1131 /* Actual block device init: Functionality shared with blockdev-add */
18e46a03 1132 blk = blockdev_init(filename, bs_opts, &local_err);
3cb0e25c 1133 bs_opts = NULL;
18e46a03 1134 if (!blk) {
84d18f06 1135 if (local_err) {
565f65d2 1136 error_report_err(local_err);
b681072d 1137 }
2d246f01 1138 goto fail;
b681072d 1139 } else {
84d18f06 1140 assert(!local_err);
2d246f01
KW
1141 }
1142
26f8b3a8
MA
1143 /* Create legacy DriveInfo */
1144 dinfo = g_malloc0(sizeof(*dinfo));
f298d071 1145 dinfo->opts = all_opts;
2d246f01 1146
b41a7338
KW
1147 dinfo->cyls = cyls;
1148 dinfo->heads = heads;
1149 dinfo->secs = secs;
1150 dinfo->trans = translation;
1151
ee13ed1c 1152 dinfo->type = type;
87a899c5
KW
1153 dinfo->bus = bus_id;
1154 dinfo->unit = unit_id;
394c7d4d 1155 dinfo->devaddr = devaddr;
bcf83158
KW
1156 dinfo->serial = g_strdup(serial);
1157
26f8b3a8
MA
1158 blk_set_legacy_dinfo(blk, dinfo);
1159
e34ef046
KW
1160 switch(type) {
1161 case IF_IDE:
1162 case IF_SCSI:
1163 case IF_XEN:
1164 case IF_NONE:
1165 dinfo->media_cd = media == MEDIA_CDROM;
1166 break;
1167 default:
1168 break;
1169 }
1170
2d246f01 1171fail:
33cb7dc8 1172 qemu_opts_del(legacy_opts);
3cb0e25c 1173 QDECREF(bs_opts);
2d246f01 1174 return dinfo;
57975222
KW
1175}
1176
b6c1bae5
KW
1177static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1178{
1179 BlockDriverState *bs;
1180
1181 bs = bdrv_lookup_bs(name, name, errp);
1182 if (bs == NULL) {
1183 return NULL;
1184 }
1185
1186 if (!bdrv_is_root_node(bs)) {
1187 error_setg(errp, "Need a root block node");
1188 return NULL;
1189 }
1190
1191 if (!bdrv_is_inserted(bs)) {
1192 error_setg(errp, "Device has no medium");
1193 return NULL;
1194 }
1195
1196 return bs;
1197}
1198
3e5a50d6 1199void hmp_commit(Monitor *mon, const QDict *qdict)
666daa68 1200{
666daa68 1201 const char *device = qdict_get_str(qdict, "device");
a0e8544c 1202 BlockBackend *blk;
e8877497 1203 int ret;
666daa68 1204
6ab4b5ab 1205 if (!strcmp(device, "all")) {
da31d594 1206 ret = blk_commit_all();
6ab4b5ab 1207 } else {
84aa0140
SH
1208 BlockDriverState *bs;
1209 AioContext *aio_context;
1210
a0e8544c
FZ
1211 blk = blk_by_name(device);
1212 if (!blk) {
58513bde 1213 monitor_printf(mon, "Device '%s' not found\n", device);
ac59eb95 1214 return;
6ab4b5ab 1215 }
5433c24f
HR
1216 if (!blk_is_available(blk)) {
1217 monitor_printf(mon, "Device '%s' has no medium\n", device);
1218 return;
1219 }
84aa0140
SH
1220
1221 bs = blk_bs(blk);
1222 aio_context = bdrv_get_aio_context(bs);
1223 aio_context_acquire(aio_context);
1224
1225 ret = bdrv_commit(bs);
1226
1227 aio_context_release(aio_context);
58513bde
JC
1228 }
1229 if (ret < 0) {
1230 monitor_printf(mon, "'commit' error for '%s': %s\n", device,
1231 strerror(-ret));
666daa68
MA
1232 }
1233}
1234
10f75907 1235static void blockdev_do_action(TransactionAction *action, Error **errp)
6cc2a415 1236{
c8a83e85 1237 TransactionActionList list;
6cc2a415 1238
10f75907 1239 list.value = action;
6cc2a415 1240 list.next = NULL;
94d16a64 1241 qmp_transaction(&list, false, NULL, errp);
6cc2a415
PB
1242}
1243
0901f67e
BC
1244void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1245 bool has_node_name, const char *node_name,
1246 const char *snapshot_file,
1247 bool has_snapshot_node_name,
1248 const char *snapshot_node_name,
6106e249 1249 bool has_format, const char *format,
0901f67e 1250 bool has_mode, NewImageMode mode, Error **errp)
f8882568 1251{
a911e6ae 1252 BlockdevSnapshotSync snapshot = {
0901f67e 1253 .has_device = has_device,
6cc2a415 1254 .device = (char *) device,
0901f67e
BC
1255 .has_node_name = has_node_name,
1256 .node_name = (char *) node_name,
6cc2a415 1257 .snapshot_file = (char *) snapshot_file,
0901f67e
BC
1258 .has_snapshot_node_name = has_snapshot_node_name,
1259 .snapshot_node_name = (char *) snapshot_node_name,
6cc2a415
PB
1260 .has_format = has_format,
1261 .format = (char *) format,
1262 .has_mode = has_mode,
1263 .mode = mode,
1264 };
10f75907
EB
1265 TransactionAction action = {
1266 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
32bafa8f 1267 .u.blockdev_snapshot_sync.data = &snapshot,
10f75907
EB
1268 };
1269 blockdev_do_action(&action, errp);
f8882568
JS
1270}
1271
43de7e2d
AG
1272void qmp_blockdev_snapshot(const char *node, const char *overlay,
1273 Error **errp)
1274{
1275 BlockdevSnapshot snapshot_data = {
1276 .node = (char *) node,
1277 .overlay = (char *) overlay
1278 };
10f75907
EB
1279 TransactionAction action = {
1280 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
32bafa8f 1281 .u.blockdev_snapshot.data = &snapshot_data,
10f75907
EB
1282 };
1283 blockdev_do_action(&action, errp);
43de7e2d
AG
1284}
1285
f323bc9e
WX
1286void qmp_blockdev_snapshot_internal_sync(const char *device,
1287 const char *name,
1288 Error **errp)
1289{
1290 BlockdevSnapshotInternal snapshot = {
1291 .device = (char *) device,
1292 .name = (char *) name
1293 };
10f75907
EB
1294 TransactionAction action = {
1295 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
32bafa8f 1296 .u.blockdev_snapshot_internal_sync.data = &snapshot,
10f75907
EB
1297 };
1298 blockdev_do_action(&action, errp);
f323bc9e
WX
1299}
1300
44e3e053
WX
1301SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1302 bool has_id,
1303 const char *id,
1304 bool has_name,
1305 const char *name,
1306 Error **errp)
1307{
a0e8544c
FZ
1308 BlockDriverState *bs;
1309 BlockBackend *blk;
4ef3982a 1310 AioContext *aio_context;
44e3e053
WX
1311 QEMUSnapshotInfo sn;
1312 Error *local_err = NULL;
1313 SnapshotInfo *info = NULL;
1314 int ret;
1315
a0e8544c
FZ
1316 blk = blk_by_name(device);
1317 if (!blk) {
75158ebb
MA
1318 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1319 "Device '%s' not found", device);
44e3e053
WX
1320 return NULL;
1321 }
5433c24f
HR
1322
1323 aio_context = blk_get_aio_context(blk);
1324 aio_context_acquire(aio_context);
44e3e053
WX
1325
1326 if (!has_id) {
1327 id = NULL;
1328 }
1329
1330 if (!has_name) {
1331 name = NULL;
1332 }
1333
1334 if (!id && !name) {
1335 error_setg(errp, "Name or id must be provided");
5433c24f 1336 goto out_aio_context;
44e3e053
WX
1337 }
1338
5433c24f
HR
1339 if (!blk_is_available(blk)) {
1340 error_setg(errp, "Device '%s' has no medium", device);
1341 goto out_aio_context;
1342 }
1343 bs = blk_bs(blk);
4ef3982a 1344
0b928854
SH
1345 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1346 goto out_aio_context;
1347 }
1348
44e3e053 1349 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
84d18f06 1350 if (local_err) {
44e3e053 1351 error_propagate(errp, local_err);
4ef3982a 1352 goto out_aio_context;
44e3e053
WX
1353 }
1354 if (!ret) {
1355 error_setg(errp,
1356 "Snapshot with id '%s' and name '%s' does not exist on "
1357 "device '%s'",
1358 STR_OR_NULL(id), STR_OR_NULL(name), device);
4ef3982a 1359 goto out_aio_context;
44e3e053
WX
1360 }
1361
1362 bdrv_snapshot_delete(bs, id, name, &local_err);
84d18f06 1363 if (local_err) {
44e3e053 1364 error_propagate(errp, local_err);
4ef3982a 1365 goto out_aio_context;
44e3e053
WX
1366 }
1367
4ef3982a
SH
1368 aio_context_release(aio_context);
1369
5839e53b 1370 info = g_new0(SnapshotInfo, 1);
44e3e053
WX
1371 info->id = g_strdup(sn.id_str);
1372 info->name = g_strdup(sn.name);
1373 info->date_nsec = sn.date_nsec;
1374 info->date_sec = sn.date_sec;
1375 info->vm_state_size = sn.vm_state_size;
1376 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1377 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1378
1379 return info;
4ef3982a
SH
1380
1381out_aio_context:
1382 aio_context_release(aio_context);
1383 return NULL;
44e3e053 1384}
8802d1fd 1385
341ebc2f
JS
1386/**
1387 * block_dirty_bitmap_lookup:
1388 * Return a dirty bitmap (if present), after validating
1389 * the node reference and bitmap names.
1390 *
1391 * @node: The name of the BDS node to search for bitmaps
1392 * @name: The name of the bitmap to search for
1393 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1394 * @paio: Output pointer for aio_context acquisition, if desired. Can be NULL.
1395 * @errp: Output pointer for error information. Can be NULL.
1396 *
1397 * @return: A bitmap object on success, or NULL on failure.
1398 */
1399static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1400 const char *name,
1401 BlockDriverState **pbs,
1402 AioContext **paio,
1403 Error **errp)
1404{
1405 BlockDriverState *bs;
1406 BdrvDirtyBitmap *bitmap;
1407 AioContext *aio_context;
1408
1409 if (!node) {
1410 error_setg(errp, "Node cannot be NULL");
1411 return NULL;
1412 }
1413 if (!name) {
1414 error_setg(errp, "Bitmap name cannot be NULL");
1415 return NULL;
1416 }
1417 bs = bdrv_lookup_bs(node, node, NULL);
1418 if (!bs) {
1419 error_setg(errp, "Node '%s' not found", node);
1420 return NULL;
1421 }
1422
1423 aio_context = bdrv_get_aio_context(bs);
1424 aio_context_acquire(aio_context);
1425
1426 bitmap = bdrv_find_dirty_bitmap(bs, name);
1427 if (!bitmap) {
1428 error_setg(errp, "Dirty bitmap '%s' not found", name);
1429 goto fail;
1430 }
1431
1432 if (pbs) {
1433 *pbs = bs;
1434 }
1435 if (paio) {
1436 *paio = aio_context;
1437 } else {
1438 aio_context_release(aio_context);
1439 }
1440
1441 return bitmap;
1442
1443 fail:
1444 aio_context_release(aio_context);
1445 return NULL;
1446}
1447
b756b9ce 1448/* New and old BlockDriverState structs for atomic group operations */
ba0c86a3 1449
50f43f0f 1450typedef struct BlkActionState BlkActionState;
ba0c86a3 1451
50f43f0f
JS
1452/**
1453 * BlkActionOps:
1454 * Table of operations that define an Action.
1455 *
1456 * @instance_size: Size of state struct, in bytes.
1457 * @prepare: Prepare the work, must NOT be NULL.
1458 * @commit: Commit the changes, can be NULL.
1459 * @abort: Abort the changes on fail, can be NULL.
1460 * @clean: Clean up resources after all transaction actions have called
1461 * commit() or abort(). Can be NULL.
1462 *
1463 * Only prepare() may fail. In a single transaction, only one of commit() or
1464 * abort() will be called. clean() will always be called if it is present.
1465 */
1466typedef struct BlkActionOps {
ba0c86a3 1467 size_t instance_size;
50f43f0f
JS
1468 void (*prepare)(BlkActionState *common, Error **errp);
1469 void (*commit)(BlkActionState *common);
1470 void (*abort)(BlkActionState *common);
1471 void (*clean)(BlkActionState *common);
1472} BlkActionOps;
ba0c86a3 1473
50f43f0f
JS
1474/**
1475 * BlkActionState:
1476 * Describes one Action's state within a Transaction.
1477 *
1478 * @action: QAPI-defined enum identifying which Action to perform.
1479 * @ops: Table of ActionOps this Action can perform.
94d16a64 1480 * @block_job_txn: Transaction which this action belongs to.
50f43f0f
JS
1481 * @entry: List membership for all Actions in this Transaction.
1482 *
1483 * This structure must be arranged as first member in a subclassed type,
1484 * assuming that the compiler will also arrange it to the same offsets as the
1485 * base class.
ba0c86a3 1486 */
50f43f0f 1487struct BlkActionState {
c8a83e85 1488 TransactionAction *action;
50f43f0f 1489 const BlkActionOps *ops;
94d16a64
JS
1490 BlockJobTxn *block_job_txn;
1491 TransactionProperties *txn_props;
50f43f0f 1492 QSIMPLEQ_ENTRY(BlkActionState) entry;
ba0c86a3
WX
1493};
1494
bbe86010
WX
1495/* internal snapshot private data */
1496typedef struct InternalSnapshotState {
50f43f0f 1497 BlkActionState common;
bbe86010 1498 BlockDriverState *bs;
5d6e96ef 1499 AioContext *aio_context;
bbe86010 1500 QEMUSnapshotInfo sn;
507306cc 1501 bool created;
bbe86010
WX
1502} InternalSnapshotState;
1503
94d16a64
JS
1504
1505static int action_check_completion_mode(BlkActionState *s, Error **errp)
1506{
1507 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1508 error_setg(errp,
1509 "Action '%s' does not support Transaction property "
1510 "completion-mode = %s",
1511 TransactionActionKind_lookup[s->action->type],
1512 ActionCompletionMode_lookup[s->txn_props->completion_mode]);
1513 return -1;
1514 }
1515 return 0;
1516}
1517
50f43f0f 1518static void internal_snapshot_prepare(BlkActionState *common,
bbe86010
WX
1519 Error **errp)
1520{
f70edf99 1521 Error *local_err = NULL;
bbe86010
WX
1522 const char *device;
1523 const char *name;
a0e8544c 1524 BlockBackend *blk;
bbe86010
WX
1525 BlockDriverState *bs;
1526 QEMUSnapshotInfo old_sn, *sn;
1527 bool ret;
1528 qemu_timeval tv;
1529 BlockdevSnapshotInternal *internal;
1530 InternalSnapshotState *state;
1531 int ret1;
1532
6a8f9661 1533 g_assert(common->action->type ==
bbe86010 1534 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
32bafa8f 1535 internal = common->action->u.blockdev_snapshot_internal_sync.data;
bbe86010
WX
1536 state = DO_UPCAST(InternalSnapshotState, common, common);
1537
1538 /* 1. parse input */
1539 device = internal->device;
1540 name = internal->name;
1541
1542 /* 2. check for validation */
94d16a64
JS
1543 if (action_check_completion_mode(common, errp) < 0) {
1544 return;
1545 }
1546
a0e8544c
FZ
1547 blk = blk_by_name(device);
1548 if (!blk) {
75158ebb
MA
1549 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1550 "Device '%s' not found", device);
bbe86010
WX
1551 return;
1552 }
1553
5d6e96ef 1554 /* AioContext is released in .clean() */
5433c24f 1555 state->aio_context = blk_get_aio_context(blk);
5d6e96ef
SH
1556 aio_context_acquire(state->aio_context);
1557
5433c24f 1558 if (!blk_is_available(blk)) {
c6bd8c70 1559 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
bbe86010
WX
1560 return;
1561 }
5433c24f 1562 bs = blk_bs(blk);
bbe86010 1563
507306cc
FZ
1564 state->bs = bs;
1565 bdrv_drained_begin(bs);
1566
3dc7ca3c
SH
1567 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1568 return;
1569 }
1570
bbe86010 1571 if (bdrv_is_read_only(bs)) {
81e5f78a 1572 error_setg(errp, "Device '%s' is read only", device);
bbe86010
WX
1573 return;
1574 }
1575
1576 if (!bdrv_can_snapshot(bs)) {
81e5f78a
AG
1577 error_setg(errp, "Block format '%s' used by device '%s' "
1578 "does not support internal snapshots",
1579 bs->drv->format_name, device);
bbe86010
WX
1580 return;
1581 }
1582
1583 if (!strlen(name)) {
1584 error_setg(errp, "Name is empty");
1585 return;
1586 }
1587
1588 /* check whether a snapshot with name exist */
f70edf99
MA
1589 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1590 &local_err);
1591 if (local_err) {
1592 error_propagate(errp, local_err);
bbe86010
WX
1593 return;
1594 } else if (ret) {
1595 error_setg(errp,
1596 "Snapshot with name '%s' already exists on device '%s'",
1597 name, device);
1598 return;
1599 }
1600
1601 /* 3. take the snapshot */
1602 sn = &state->sn;
1603 pstrcpy(sn->name, sizeof(sn->name), name);
1604 qemu_gettimeofday(&tv);
1605 sn->date_sec = tv.tv_sec;
1606 sn->date_nsec = tv.tv_usec * 1000;
1607 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1608
1609 ret1 = bdrv_snapshot_create(bs, sn);
1610 if (ret1 < 0) {
1611 error_setg_errno(errp, -ret1,
1612 "Failed to create snapshot '%s' on device '%s'",
1613 name, device);
1614 return;
1615 }
1616
1617 /* 4. succeed, mark a snapshot is created */
507306cc 1618 state->created = true;
bbe86010
WX
1619}
1620
50f43f0f 1621static void internal_snapshot_abort(BlkActionState *common)
bbe86010
WX
1622{
1623 InternalSnapshotState *state =
1624 DO_UPCAST(InternalSnapshotState, common, common);
1625 BlockDriverState *bs = state->bs;
1626 QEMUSnapshotInfo *sn = &state->sn;
1627 Error *local_error = NULL;
1628
507306cc 1629 if (!state->created) {
bbe86010
WX
1630 return;
1631 }
1632
1633 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
c29b77f9
MA
1634 error_reportf_err(local_error,
1635 "Failed to delete snapshot with id '%s' and "
1636 "name '%s' on device '%s' in abort: ",
1637 sn->id_str, sn->name,
1638 bdrv_get_device_name(bs));
bbe86010
WX
1639 }
1640}
1641
50f43f0f 1642static void internal_snapshot_clean(BlkActionState *common)
5d6e96ef
SH
1643{
1644 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1645 common, common);
1646
1647 if (state->aio_context) {
507306cc
FZ
1648 if (state->bs) {
1649 bdrv_drained_end(state->bs);
1650 }
5d6e96ef
SH
1651 aio_context_release(state->aio_context);
1652 }
1653}
1654
ba0c86a3 1655/* external snapshot private data */
ba5d6ab6 1656typedef struct ExternalSnapshotState {
50f43f0f 1657 BlkActionState common;
8802d1fd
JC
1658 BlockDriverState *old_bs;
1659 BlockDriverState *new_bs;
5d6e96ef 1660 AioContext *aio_context;
ba5d6ab6 1661} ExternalSnapshotState;
8802d1fd 1662
50f43f0f 1663static void external_snapshot_prepare(BlkActionState *common,
9b9877ee
WX
1664 Error **errp)
1665{
5b363937 1666 int flags = 0;
43de7e2d 1667 QDict *options = NULL;
9b9877ee 1668 Error *local_err = NULL;
43de7e2d 1669 /* Device and node name of the image to generate the snapshot from */
e2a31e87 1670 const char *device;
0901f67e 1671 const char *node_name;
43de7e2d
AG
1672 /* Reference to the new image (for 'blockdev-snapshot') */
1673 const char *snapshot_ref;
1674 /* File name of the new image (for 'blockdev-snapshot-sync') */
e2a31e87 1675 const char *new_image_file;
ba5d6ab6
SH
1676 ExternalSnapshotState *state =
1677 DO_UPCAST(ExternalSnapshotState, common, common);
c8a83e85 1678 TransactionAction *action = common->action;
9b9877ee 1679
43de7e2d
AG
1680 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1681 * purpose but a different set of parameters */
1682 switch (action->type) {
1683 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1684 {
32bafa8f 1685 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
43de7e2d
AG
1686 device = s->node;
1687 node_name = s->node;
1688 new_image_file = NULL;
1689 snapshot_ref = s->overlay;
1690 }
1691 break;
1692 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1693 {
32bafa8f 1694 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
43de7e2d
AG
1695 device = s->has_device ? s->device : NULL;
1696 node_name = s->has_node_name ? s->node_name : NULL;
1697 new_image_file = s->snapshot_file;
1698 snapshot_ref = NULL;
1699 }
1700 break;
1701 default:
1702 g_assert_not_reached();
e2a31e87
WX
1703 }
1704
1705 /* start processing */
94d16a64
JS
1706 if (action_check_completion_mode(common, errp) < 0) {
1707 return;
1708 }
1709
43de7e2d
AG
1710 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1711 if (!state->old_bs) {
9b9877ee
WX
1712 return;
1713 }
1714
5d6e96ef
SH
1715 /* Acquire AioContext now so any threads operating on old_bs stop */
1716 state->aio_context = bdrv_get_aio_context(state->old_bs);
1717 aio_context_acquire(state->aio_context);
da763e83 1718 bdrv_drained_begin(state->old_bs);
5d6e96ef 1719
ba5d6ab6 1720 if (!bdrv_is_inserted(state->old_bs)) {
c6bd8c70 1721 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
9b9877ee
WX
1722 return;
1723 }
1724
3718d8ab
FZ
1725 if (bdrv_op_is_blocked(state->old_bs,
1726 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
9b9877ee
WX
1727 return;
1728 }
1729
ba5d6ab6
SH
1730 if (!bdrv_is_read_only(state->old_bs)) {
1731 if (bdrv_flush(state->old_bs)) {
c6bd8c70 1732 error_setg(errp, QERR_IO_ERROR);
9b9877ee
WX
1733 return;
1734 }
1735 }
1736
212a5a8f 1737 if (!bdrv_is_first_non_filter(state->old_bs)) {
c6bd8c70 1738 error_setg(errp, QERR_FEATURE_DISABLED, "snapshot");
f6186f49
BC
1739 return;
1740 }
1741
43de7e2d 1742 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
32bafa8f 1743 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
43de7e2d
AG
1744 const char *format = s->has_format ? s->format : "qcow2";
1745 enum NewImageMode mode;
1746 const char *snapshot_node_name =
1747 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
9b9877ee 1748
43de7e2d
AG
1749 if (node_name && !snapshot_node_name) {
1750 error_setg(errp, "New snapshot node name missing");
9b9877ee
WX
1751 return;
1752 }
9b9877ee 1753
43de7e2d
AG
1754 if (snapshot_node_name &&
1755 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1756 error_setg(errp, "New snapshot node name already in use");
1757 return;
1758 }
1759
1760 flags = state->old_bs->open_flags;
4c844983 1761 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
43de7e2d
AG
1762
1763 /* create new image w/backing file */
1764 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1765 if (mode != NEW_IMAGE_MODE_EXISTING) {
f86b8b58
KW
1766 int64_t size = bdrv_getlength(state->old_bs);
1767 if (size < 0) {
1768 error_setg_errno(errp, -size, "bdrv_getlength failed");
1769 return;
1770 }
43de7e2d
AG
1771 bdrv_img_create(new_image_file, format,
1772 state->old_bs->filename,
1773 state->old_bs->drv->format_name,
f86b8b58 1774 NULL, size, flags, &local_err, false);
43de7e2d
AG
1775 if (local_err) {
1776 error_propagate(errp, local_err);
1777 return;
1778 }
1779 }
1780
1781 options = qdict_new();
1782 if (s->has_snapshot_node_name) {
1783 qdict_put(options, "node-name",
1784 qstring_from_str(snapshot_node_name));
1785 }
1786 qdict_put(options, "driver", qstring_from_str(format));
1787
1788 flags |= BDRV_O_NO_BACKING;
0901f67e
BC
1789 }
1790
5b363937
HR
1791 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1792 errp);
f67503e5 1793 /* We will manually add the backing_hd field to the bs later */
5b363937 1794 if (!state->new_bs) {
43de7e2d
AG
1795 return;
1796 }
1797
1f0c461b 1798 if (bdrv_has_blk(state->new_bs)) {
43de7e2d 1799 error_setg(errp, "The snapshot is already in use by %s",
1f0c461b 1800 bdrv_get_parent_name(state->new_bs));
43de7e2d
AG
1801 return;
1802 }
1803
1804 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1805 errp)) {
1806 return;
1807 }
1808
1809 if (state->new_bs->backing != NULL) {
1810 error_setg(errp, "The snapshot already has a backing image");
08b24cfe
AG
1811 return;
1812 }
1813
1814 if (!state->new_bs->drv->supports_backing) {
1815 error_setg(errp, "The snapshot does not support backing images");
9b9877ee
WX
1816 }
1817}
1818
50f43f0f 1819static void external_snapshot_commit(BlkActionState *common)
3b0047e8 1820{
ba5d6ab6
SH
1821 ExternalSnapshotState *state =
1822 DO_UPCAST(ExternalSnapshotState, common, common);
ba0c86a3 1823
5d6e96ef
SH
1824 bdrv_set_aio_context(state->new_bs, state->aio_context);
1825
ba5d6ab6
SH
1826 /* This removes our old bs and adds the new bs */
1827 bdrv_append(state->new_bs, state->old_bs);
3b0047e8
WX
1828 /* We don't need (or want) to use the transactional
1829 * bdrv_reopen_multiple() across all the entries at once, because we
1830 * don't want to abort all of them if one of them fails the reopen */
4c844983
KW
1831 if (!state->old_bs->copy_on_read) {
1832 bdrv_reopen(state->old_bs, state->old_bs->open_flags & ~BDRV_O_RDWR,
1833 NULL);
1834 }
3b0047e8
WX
1835}
1836
50f43f0f 1837static void external_snapshot_abort(BlkActionState *common)
96b86bf7 1838{
ba5d6ab6
SH
1839 ExternalSnapshotState *state =
1840 DO_UPCAST(ExternalSnapshotState, common, common);
1841 if (state->new_bs) {
4f6fd349 1842 bdrv_unref(state->new_bs);
96b86bf7 1843 }
da763e83
FZ
1844}
1845
50f43f0f 1846static void external_snapshot_clean(BlkActionState *common)
da763e83
FZ
1847{
1848 ExternalSnapshotState *state =
1849 DO_UPCAST(ExternalSnapshotState, common, common);
5d6e96ef 1850 if (state->aio_context) {
da763e83 1851 bdrv_drained_end(state->old_bs);
5d6e96ef
SH
1852 aio_context_release(state->aio_context);
1853 }
96b86bf7
WX
1854}
1855
3037f364 1856typedef struct DriveBackupState {
50f43f0f 1857 BlkActionState common;
3037f364 1858 BlockDriverState *bs;
5d6e96ef 1859 AioContext *aio_context;
3037f364
SH
1860 BlockJob *job;
1861} DriveBackupState;
1862
70559d49
AG
1863static void do_drive_backup(const char *job_id, const char *device,
1864 const char *target, bool has_format,
1865 const char *format, enum MirrorSyncMode sync,
78f51fde
JS
1866 bool has_mode, enum NewImageMode mode,
1867 bool has_speed, int64_t speed,
1868 bool has_bitmap, const char *bitmap,
1869 bool has_on_source_error,
1870 BlockdevOnError on_source_error,
1871 bool has_on_target_error,
1872 BlockdevOnError on_target_error,
1873 BlockJobTxn *txn, Error **errp);
1874
50f43f0f 1875static void drive_backup_prepare(BlkActionState *common, Error **errp)
3037f364
SH
1876{
1877 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
a0e8544c 1878 BlockBackend *blk;
3037f364
SH
1879 DriveBackup *backup;
1880 Error *local_err = NULL;
1881
6a8f9661 1882 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
32bafa8f 1883 backup = common->action->u.drive_backup.data;
3037f364 1884
a0e8544c
FZ
1885 blk = blk_by_name(backup->device);
1886 if (!blk) {
75158ebb
MA
1887 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1888 "Device '%s' not found", backup->device);
5d6e96ef
SH
1889 return;
1890 }
1891
1fdd4b7b
FZ
1892 if (!blk_is_available(blk)) {
1893 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1894 return;
1895 }
1896
5d6e96ef 1897 /* AioContext is released in .clean() */
5433c24f 1898 state->aio_context = blk_get_aio_context(blk);
5d6e96ef 1899 aio_context_acquire(state->aio_context);
1fdd4b7b
FZ
1900 bdrv_drained_begin(blk_bs(blk));
1901 state->bs = blk_bs(blk);
5d6e96ef 1902
70559d49
AG
1903 do_drive_backup(backup->has_job_id ? backup->job_id : NULL,
1904 backup->device, backup->target,
78f51fde
JS
1905 backup->has_format, backup->format,
1906 backup->sync,
1907 backup->has_mode, backup->mode,
1908 backup->has_speed, backup->speed,
1909 backup->has_bitmap, backup->bitmap,
1910 backup->has_on_source_error, backup->on_source_error,
1911 backup->has_on_target_error, backup->on_target_error,
94d16a64 1912 common->block_job_txn, &local_err);
84d18f06 1913 if (local_err) {
3037f364 1914 error_propagate(errp, local_err);
3037f364
SH
1915 return;
1916 }
1917
3037f364
SH
1918 state->job = state->bs->job;
1919}
1920
50f43f0f 1921static void drive_backup_abort(BlkActionState *common)
3037f364
SH
1922{
1923 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1924 BlockDriverState *bs = state->bs;
1925
1926 /* Only cancel if it's the job we started */
1927 if (bs && bs->job && bs->job == state->job) {
1928 block_job_cancel_sync(bs->job);
1929 }
1930}
1931
50f43f0f 1932static void drive_backup_clean(BlkActionState *common)
5d6e96ef
SH
1933{
1934 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1935
1936 if (state->aio_context) {
1fdd4b7b 1937 bdrv_drained_end(state->bs);
5d6e96ef
SH
1938 aio_context_release(state->aio_context);
1939 }
1940}
1941
bd8baecd 1942typedef struct BlockdevBackupState {
50f43f0f 1943 BlkActionState common;
bd8baecd
FZ
1944 BlockDriverState *bs;
1945 BlockJob *job;
1946 AioContext *aio_context;
1947} BlockdevBackupState;
1948
70559d49
AG
1949static void do_blockdev_backup(const char *job_id, const char *device,
1950 const char *target, enum MirrorSyncMode sync,
78f51fde
JS
1951 bool has_speed, int64_t speed,
1952 bool has_on_source_error,
1953 BlockdevOnError on_source_error,
1954 bool has_on_target_error,
1955 BlockdevOnError on_target_error,
1956 BlockJobTxn *txn, Error **errp);
1957
50f43f0f 1958static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
bd8baecd
FZ
1959{
1960 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1961 BlockdevBackup *backup;
39d990ac
KW
1962 BlockBackend *blk;
1963 BlockDriverState *target;
bd8baecd
FZ
1964 Error *local_err = NULL;
1965
6a8f9661 1966 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
32bafa8f 1967 backup = common->action->u.blockdev_backup.data;
bd8baecd 1968
a0e8544c
FZ
1969 blk = blk_by_name(backup->device);
1970 if (!blk) {
5b347c54 1971 error_setg(errp, "Device '%s' not found", backup->device);
bd8baecd
FZ
1972 return;
1973 }
1974
ff52bf36
FZ
1975 if (!blk_is_available(blk)) {
1976 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);
1977 return;
1978 }
1979
39d990ac 1980 target = bdrv_lookup_bs(backup->target, backup->target, errp);
5433c24f 1981 if (!target) {
bd8baecd
FZ
1982 return;
1983 }
1984
1985 /* AioContext is released in .clean() */
5433c24f 1986 state->aio_context = blk_get_aio_context(blk);
39d990ac 1987 if (state->aio_context != bdrv_get_aio_context(target)) {
bd8baecd
FZ
1988 state->aio_context = NULL;
1989 error_setg(errp, "Backup between two IO threads is not implemented");
1990 return;
1991 }
1992 aio_context_acquire(state->aio_context);
ff52bf36
FZ
1993 state->bs = blk_bs(blk);
1994 bdrv_drained_begin(state->bs);
bd8baecd 1995
70559d49
AG
1996 do_blockdev_backup(backup->has_job_id ? backup->job_id : NULL,
1997 backup->device, backup->target, backup->sync,
78f51fde
JS
1998 backup->has_speed, backup->speed,
1999 backup->has_on_source_error, backup->on_source_error,
2000 backup->has_on_target_error, backup->on_target_error,
94d16a64 2001 common->block_job_txn, &local_err);
bd8baecd
FZ
2002 if (local_err) {
2003 error_propagate(errp, local_err);
2004 return;
2005 }
2006
bd8baecd
FZ
2007 state->job = state->bs->job;
2008}
2009
50f43f0f 2010static void blockdev_backup_abort(BlkActionState *common)
bd8baecd
FZ
2011{
2012 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2013 BlockDriverState *bs = state->bs;
2014
2015 /* Only cancel if it's the job we started */
2016 if (bs && bs->job && bs->job == state->job) {
2017 block_job_cancel_sync(bs->job);
2018 }
2019}
2020
50f43f0f 2021static void blockdev_backup_clean(BlkActionState *common)
bd8baecd
FZ
2022{
2023 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2024
2025 if (state->aio_context) {
ff52bf36 2026 bdrv_drained_end(state->bs);
bd8baecd
FZ
2027 aio_context_release(state->aio_context);
2028 }
2029}
2030
df9a681d 2031typedef struct BlockDirtyBitmapState {
50f43f0f 2032 BlkActionState common;
df9a681d
FZ
2033 BdrvDirtyBitmap *bitmap;
2034 BlockDriverState *bs;
2035 AioContext *aio_context;
2036 HBitmap *backup;
2037 bool prepared;
2038} BlockDirtyBitmapState;
2039
50f43f0f 2040static void block_dirty_bitmap_add_prepare(BlkActionState *common,
df9a681d
FZ
2041 Error **errp)
2042{
2043 Error *local_err = NULL;
2044 BlockDirtyBitmapAdd *action;
2045 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2046 common, common);
2047
94d16a64
JS
2048 if (action_check_completion_mode(common, errp) < 0) {
2049 return;
2050 }
2051
32bafa8f 2052 action = common->action->u.block_dirty_bitmap_add.data;
df9a681d
FZ
2053 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2054 qmp_block_dirty_bitmap_add(action->node, action->name,
2055 action->has_granularity, action->granularity,
2056 &local_err);
2057
2058 if (!local_err) {
2059 state->prepared = true;
2060 } else {
2061 error_propagate(errp, local_err);
2062 }
2063}
2064
50f43f0f 2065static void block_dirty_bitmap_add_abort(BlkActionState *common)
df9a681d
FZ
2066{
2067 BlockDirtyBitmapAdd *action;
2068 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2069 common, common);
2070
32bafa8f 2071 action = common->action->u.block_dirty_bitmap_add.data;
df9a681d
FZ
2072 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2073 * then the node reference and bitmap name must have been valid.
2074 */
2075 if (state->prepared) {
2076 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2077 }
2078}
2079
50f43f0f 2080static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
df9a681d
FZ
2081 Error **errp)
2082{
2083 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2084 common, common);
2085 BlockDirtyBitmap *action;
2086
94d16a64
JS
2087 if (action_check_completion_mode(common, errp) < 0) {
2088 return;
2089 }
2090
32bafa8f 2091 action = common->action->u.block_dirty_bitmap_clear.data;
df9a681d
FZ
2092 state->bitmap = block_dirty_bitmap_lookup(action->node,
2093 action->name,
2094 &state->bs,
2095 &state->aio_context,
2096 errp);
2097 if (!state->bitmap) {
2098 return;
2099 }
2100
2101 if (bdrv_dirty_bitmap_frozen(state->bitmap)) {
2102 error_setg(errp, "Cannot modify a frozen bitmap");
2103 return;
2104 } else if (!bdrv_dirty_bitmap_enabled(state->bitmap)) {
2105 error_setg(errp, "Cannot clear a disabled bitmap");
2106 return;
2107 }
2108
2109 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2110 /* AioContext is released in .clean() */
2111}
2112
50f43f0f 2113static void block_dirty_bitmap_clear_abort(BlkActionState *common)
df9a681d
FZ
2114{
2115 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2116 common, common);
2117
2118 bdrv_undo_clear_dirty_bitmap(state->bitmap, state->backup);
2119}
2120
50f43f0f 2121static void block_dirty_bitmap_clear_commit(BlkActionState *common)
df9a681d
FZ
2122{
2123 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2124 common, common);
2125
2126 hbitmap_free(state->backup);
2127}
2128
50f43f0f 2129static void block_dirty_bitmap_clear_clean(BlkActionState *common)
df9a681d
FZ
2130{
2131 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2132 common, common);
2133
2134 if (state->aio_context) {
2135 aio_context_release(state->aio_context);
2136 }
2137}
2138
50f43f0f 2139static void abort_prepare(BlkActionState *common, Error **errp)
78b18b78
SH
2140{
2141 error_setg(errp, "Transaction aborted using Abort action");
2142}
2143
50f43f0f 2144static void abort_commit(BlkActionState *common)
78b18b78 2145{
dfc6f865 2146 g_assert_not_reached(); /* this action never succeeds */
78b18b78
SH
2147}
2148
50f43f0f 2149static const BlkActionOps actions[] = {
43de7e2d
AG
2150 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2151 .instance_size = sizeof(ExternalSnapshotState),
2152 .prepare = external_snapshot_prepare,
2153 .commit = external_snapshot_commit,
2154 .abort = external_snapshot_abort,
4ad6f3db 2155 .clean = external_snapshot_clean,
43de7e2d 2156 },
c8a83e85 2157 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
ba5d6ab6 2158 .instance_size = sizeof(ExternalSnapshotState),
ba0c86a3
WX
2159 .prepare = external_snapshot_prepare,
2160 .commit = external_snapshot_commit,
2161 .abort = external_snapshot_abort,
da763e83 2162 .clean = external_snapshot_clean,
ba0c86a3 2163 },
3037f364
SH
2164 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2165 .instance_size = sizeof(DriveBackupState),
2166 .prepare = drive_backup_prepare,
2167 .abort = drive_backup_abort,
5d6e96ef 2168 .clean = drive_backup_clean,
3037f364 2169 },
bd8baecd
FZ
2170 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2171 .instance_size = sizeof(BlockdevBackupState),
2172 .prepare = blockdev_backup_prepare,
2173 .abort = blockdev_backup_abort,
2174 .clean = blockdev_backup_clean,
2175 },
78b18b78 2176 [TRANSACTION_ACTION_KIND_ABORT] = {
50f43f0f 2177 .instance_size = sizeof(BlkActionState),
78b18b78
SH
2178 .prepare = abort_prepare,
2179 .commit = abort_commit,
2180 },
bbe86010
WX
2181 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2182 .instance_size = sizeof(InternalSnapshotState),
2183 .prepare = internal_snapshot_prepare,
2184 .abort = internal_snapshot_abort,
5d6e96ef 2185 .clean = internal_snapshot_clean,
bbe86010 2186 },
df9a681d
FZ
2187 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2188 .instance_size = sizeof(BlockDirtyBitmapState),
2189 .prepare = block_dirty_bitmap_add_prepare,
2190 .abort = block_dirty_bitmap_add_abort,
2191 },
2192 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2193 .instance_size = sizeof(BlockDirtyBitmapState),
2194 .prepare = block_dirty_bitmap_clear_prepare,
2195 .commit = block_dirty_bitmap_clear_commit,
2196 .abort = block_dirty_bitmap_clear_abort,
2197 .clean = block_dirty_bitmap_clear_clean,
2198 }
ba0c86a3
WX
2199};
2200
94d16a64
JS
2201/**
2202 * Allocate a TransactionProperties structure if necessary, and fill
2203 * that structure with desired defaults if they are unset.
2204 */
2205static TransactionProperties *get_transaction_properties(
2206 TransactionProperties *props)
2207{
2208 if (!props) {
2209 props = g_new0(TransactionProperties, 1);
2210 }
2211
2212 if (!props->has_completion_mode) {
2213 props->has_completion_mode = true;
2214 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2215 }
2216
2217 return props;
2218}
2219
8802d1fd 2220/*
b756b9ce
SH
2221 * 'Atomic' group operations. The operations are performed as a set, and if
2222 * any fail then we roll back all operations in the group.
8802d1fd 2223 */
94d16a64
JS
2224void qmp_transaction(TransactionActionList *dev_list,
2225 bool has_props,
2226 struct TransactionProperties *props,
2227 Error **errp)
8802d1fd 2228{
c8a83e85 2229 TransactionActionList *dev_entry = dev_list;
94d16a64 2230 BlockJobTxn *block_job_txn = NULL;
50f43f0f 2231 BlkActionState *state, *next;
43e17041 2232 Error *local_err = NULL;
8802d1fd 2233
50f43f0f 2234 QSIMPLEQ_HEAD(snap_bdrv_states, BlkActionState) snap_bdrv_states;
8802d1fd
JC
2235 QSIMPLEQ_INIT(&snap_bdrv_states);
2236
94d16a64
JS
2237 /* Does this transaction get canceled as a group on failure?
2238 * If not, we don't really need to make a BlockJobTxn.
2239 */
2240 props = get_transaction_properties(props);
2241 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2242 block_job_txn = block_job_txn_new();
2243 }
2244
b756b9ce 2245 /* drain all i/o before any operations */
8802d1fd
JC
2246 bdrv_drain_all();
2247
b756b9ce 2248 /* We don't do anything in this loop that commits us to the operations */
8802d1fd 2249 while (NULL != dev_entry) {
c8a83e85 2250 TransactionAction *dev_info = NULL;
50f43f0f 2251 const BlkActionOps *ops;
52e7c241 2252
8802d1fd
JC
2253 dev_info = dev_entry->value;
2254 dev_entry = dev_entry->next;
2255
6a8f9661 2256 assert(dev_info->type < ARRAY_SIZE(actions));
ba0c86a3 2257
6a8f9661 2258 ops = &actions[dev_info->type];
aa3fe714
HR
2259 assert(ops->instance_size > 0);
2260
ba5d6ab6
SH
2261 state = g_malloc0(ops->instance_size);
2262 state->ops = ops;
2263 state->action = dev_info;
94d16a64
JS
2264 state->block_job_txn = block_job_txn;
2265 state->txn_props = props;
ba5d6ab6 2266 QSIMPLEQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
8802d1fd 2267
ba5d6ab6 2268 state->ops->prepare(state, &local_err);
84d18f06 2269 if (local_err) {
ba0c86a3
WX
2270 error_propagate(errp, local_err);
2271 goto delete_and_fail;
8802d1fd 2272 }
8802d1fd
JC
2273 }
2274
ba5d6ab6 2275 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
f9ea81e8
SH
2276 if (state->ops->commit) {
2277 state->ops->commit(state);
2278 }
8802d1fd
JC
2279 }
2280
2281 /* success */
2282 goto exit;
2283
2284delete_and_fail:
b756b9ce 2285 /* failure, and it is all-or-none; roll back all operations */
ba5d6ab6
SH
2286 QSIMPLEQ_FOREACH(state, &snap_bdrv_states, entry) {
2287 if (state->ops->abort) {
2288 state->ops->abort(state);
ba0c86a3 2289 }
8802d1fd
JC
2290 }
2291exit:
ba5d6ab6
SH
2292 QSIMPLEQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2293 if (state->ops->clean) {
2294 state->ops->clean(state);
ba0c86a3 2295 }
ba5d6ab6 2296 g_free(state);
8802d1fd 2297 }
94d16a64
JS
2298 if (!has_props) {
2299 qapi_free_TransactionProperties(props);
2300 }
2301 block_job_txn_unref(block_job_txn);
8802d1fd
JC
2302}
2303
c245b6a3 2304void qmp_eject(const char *device, bool has_force, bool force, Error **errp)
666daa68 2305{
38f54bd1 2306 Error *local_err = NULL;
3a3086b7
JS
2307 int rc;
2308
2309 if (!has_force) {
2310 force = false;
2311 }
666daa68 2312
3a3086b7 2313 rc = do_open_tray(device, force, &local_err);
bf18bee5 2314 if (rc && rc != -ENOSYS) {
38f54bd1 2315 error_propagate(errp, local_err);
c245b6a3 2316 return;
92d48558 2317 }
bf18bee5 2318 error_free(local_err);
3a3086b7 2319
6e0abc25 2320 qmp_x_blockdev_remove_medium(device, errp);
666daa68
MA
2321}
2322
12d3ba82
BC
2323void qmp_block_passwd(bool has_device, const char *device,
2324 bool has_node_name, const char *node_name,
2325 const char *password, Error **errp)
666daa68 2326{
12d3ba82 2327 Error *local_err = NULL;
666daa68 2328 BlockDriverState *bs;
e3442099 2329 AioContext *aio_context;
666daa68 2330
12d3ba82
BC
2331 bs = bdrv_lookup_bs(has_device ? device : NULL,
2332 has_node_name ? node_name : NULL,
2333 &local_err);
84d18f06 2334 if (local_err) {
12d3ba82 2335 error_propagate(errp, local_err);
a4dea8a9 2336 return;
666daa68
MA
2337 }
2338
e3442099
SH
2339 aio_context = bdrv_get_aio_context(bs);
2340 aio_context_acquire(aio_context);
2341
4d2855a3 2342 bdrv_add_key(bs, password, errp);
e3442099 2343
e3442099 2344 aio_context_release(aio_context);
666daa68
MA
2345}
2346
bf18bee5
CL
2347/*
2348 * Attempt to open the tray of @device.
2349 * If @force, ignore its tray lock.
2350 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2351 * On error, store an error through @errp and return -errno.
2352 * If @device does not exist, return -ENODEV.
2353 * If it has no removable media, return -ENOTSUP.
2354 * If it has no tray, return -ENOSYS.
2355 * If the guest was asked to open the tray, return -EINPROGRESS.
2356 * Else, return 0.
3a3086b7
JS
2357 */
2358static int do_open_tray(const char *device, bool force, Error **errp)
7d8a9f71
HR
2359{
2360 BlockBackend *blk;
2361 bool locked;
2362
7d8a9f71
HR
2363 blk = blk_by_name(device);
2364 if (!blk) {
2365 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2366 "Device '%s' not found", device);
3a3086b7 2367 return -ENODEV;
7d8a9f71
HR
2368 }
2369
2370 if (!blk_dev_has_removable_media(blk)) {
2371 error_setg(errp, "Device '%s' is not removable", device);
3a3086b7 2372 return -ENOTSUP;
7d8a9f71
HR
2373 }
2374
12c7ec87 2375 if (!blk_dev_has_tray(blk)) {
bf18bee5
CL
2376 error_setg(errp, "Device '%s' does not have a tray", device);
2377 return -ENOSYS;
12c7ec87
HR
2378 }
2379
7d8a9f71 2380 if (blk_dev_is_tray_open(blk)) {
3a3086b7 2381 return 0;
7d8a9f71
HR
2382 }
2383
2384 locked = blk_dev_is_medium_locked(blk);
2385 if (locked) {
2386 blk_dev_eject_request(blk, force);
2387 }
2388
2389 if (!locked || force) {
2390 blk_dev_change_media_cb(blk, false);
2391 }
3a3086b7
JS
2392
2393 if (locked && !force) {
bf18bee5
CL
2394 error_setg(errp, "Device '%s' is locked and force was not specified, "
2395 "wait for tray to open and try again", device);
2396 return -EINPROGRESS;
3a3086b7
JS
2397 }
2398
2399 return 0;
2400}
2401
2402void qmp_blockdev_open_tray(const char *device, bool has_force, bool force,
2403 Error **errp)
2404{
bf18bee5
CL
2405 Error *local_err = NULL;
2406 int rc;
2407
3a3086b7
JS
2408 if (!has_force) {
2409 force = false;
2410 }
bf18bee5
CL
2411 rc = do_open_tray(device, force, &local_err);
2412 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2413 error_propagate(errp, local_err);
2414 return;
2415 }
2416 error_free(local_err);
7d8a9f71
HR
2417}
2418
abaaf59d
HR
2419void qmp_blockdev_close_tray(const char *device, Error **errp)
2420{
2421 BlockBackend *blk;
2422
2423 blk = blk_by_name(device);
2424 if (!blk) {
2425 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2426 "Device '%s' not found", device);
2427 return;
2428 }
2429
2430 if (!blk_dev_has_removable_media(blk)) {
2431 error_setg(errp, "Device '%s' is not removable", device);
2432 return;
2433 }
2434
12c7ec87
HR
2435 if (!blk_dev_has_tray(blk)) {
2436 /* Ignore this command on tray-less devices */
2437 return;
2438 }
2439
abaaf59d
HR
2440 if (!blk_dev_is_tray_open(blk)) {
2441 return;
2442 }
2443
2444 blk_dev_change_media_cb(blk, true);
2445}
2446
6e0abc25 2447void qmp_x_blockdev_remove_medium(const char *device, Error **errp)
2814f672
HR
2448{
2449 BlockBackend *blk;
2450 BlockDriverState *bs;
2451 AioContext *aio_context;
2452 bool has_device;
2453
2454 blk = blk_by_name(device);
2455 if (!blk) {
2456 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2457 "Device '%s' not found", device);
2458 return;
2459 }
2460
2461 /* For BBs without a device, we can exchange the BDS tree at will */
2462 has_device = blk_get_attached_dev(blk);
2463
2464 if (has_device && !blk_dev_has_removable_media(blk)) {
2465 error_setg(errp, "Device '%s' is not removable", device);
2466 return;
2467 }
2468
12c7ec87 2469 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2814f672
HR
2470 error_setg(errp, "Tray of device '%s' is not open", device);
2471 return;
2472 }
2473
2474 bs = blk_bs(blk);
2475 if (!bs) {
2476 return;
2477 }
2478
2479 aio_context = bdrv_get_aio_context(bs);
2480 aio_context_acquire(aio_context);
2481
2482 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2483 goto out;
2484 }
2485
2814f672
HR
2486 blk_remove_bs(blk);
2487
12c7ec87
HR
2488 if (!blk_dev_has_tray(blk)) {
2489 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2490 * called at all); therefore, the medium needs to be ejected here.
2491 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2492 * value passed here (i.e. false). */
2493 blk_dev_change_media_cb(blk, false);
2494 }
2495
2814f672
HR
2496out:
2497 aio_context_release(aio_context);
2498}
2499
d1299882
HR
2500static void qmp_blockdev_insert_anon_medium(const char *device,
2501 BlockDriverState *bs, Error **errp)
2502{
2503 BlockBackend *blk;
2504 bool has_device;
2505
2506 blk = blk_by_name(device);
2507 if (!blk) {
2508 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2509 "Device '%s' not found", device);
2510 return;
2511 }
2512
2513 /* For BBs without a device, we can exchange the BDS tree at will */
2514 has_device = blk_get_attached_dev(blk);
2515
2516 if (has_device && !blk_dev_has_removable_media(blk)) {
2517 error_setg(errp, "Device '%s' is not removable", device);
2518 return;
2519 }
2520
12c7ec87 2521 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
d1299882
HR
2522 error_setg(errp, "Tray of device '%s' is not open", device);
2523 return;
2524 }
2525
2526 if (blk_bs(blk)) {
2527 error_setg(errp, "There already is a medium in device '%s'", device);
2528 return;
2529 }
2530
2531 blk_insert_bs(blk, bs);
2532
12c7ec87
HR
2533 if (!blk_dev_has_tray(blk)) {
2534 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2535 * called at all); therefore, the medium needs to be pushed into the
2536 * slot here.
2537 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2538 * value passed here (i.e. true). */
2539 blk_dev_change_media_cb(blk, true);
2540 }
d1299882
HR
2541}
2542
6e0abc25
HR
2543void qmp_x_blockdev_insert_medium(const char *device, const char *node_name,
2544 Error **errp)
d1299882
HR
2545{
2546 BlockDriverState *bs;
2547
2548 bs = bdrv_find_node(node_name);
2549 if (!bs) {
2550 error_setg(errp, "Node '%s' not found", node_name);
2551 return;
2552 }
2553
1f0c461b 2554 if (bdrv_has_blk(bs)) {
d1299882 2555 error_setg(errp, "Node '%s' is already in use by '%s'", node_name,
1f0c461b 2556 bdrv_get_parent_name(bs));
d1299882
HR
2557 return;
2558 }
2559
2560 qmp_blockdev_insert_anon_medium(device, bs, errp);
2561}
2562
24fb4133
HR
2563void qmp_blockdev_change_medium(const char *device, const char *filename,
2564 bool has_format, const char *format,
39ff43d9
HR
2565 bool has_read_only,
2566 BlockdevChangeReadOnlyMode read_only,
24fb4133 2567 Error **errp)
de2c6c05
HR
2568{
2569 BlockBackend *blk;
2570 BlockDriverState *medium_bs = NULL;
5b363937 2571 int bdrv_flags;
38a53d50 2572 int rc;
de2c6c05
HR
2573 QDict *options = NULL;
2574 Error *err = NULL;
2575
2576 blk = blk_by_name(device);
2577 if (!blk) {
2578 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
2579 "Device '%s' not found", device);
2580 goto fail;
2581 }
2582
2583 if (blk_bs(blk)) {
2584 blk_update_root_state(blk);
2585 }
2586
2587 bdrv_flags = blk_get_open_flags_from_root_state(blk);
156abc2f
AM
2588 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2589 BDRV_O_PROTOCOL);
de2c6c05 2590
39ff43d9
HR
2591 if (!has_read_only) {
2592 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2593 }
2594
2595 switch (read_only) {
2596 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2597 break;
2598
2599 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2600 bdrv_flags &= ~BDRV_O_RDWR;
2601 break;
2602
2603 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2604 bdrv_flags |= BDRV_O_RDWR;
2605 break;
2606
2607 default:
2608 abort();
2609 }
2610
24fb4133 2611 if (has_format) {
de2c6c05
HR
2612 options = qdict_new();
2613 qdict_put(options, "driver", qstring_from_str(format));
2614 }
2615
5b363937
HR
2616 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2617 if (!medium_bs) {
de2c6c05
HR
2618 goto fail;
2619 }
2620
de2c6c05
HR
2621 bdrv_add_key(medium_bs, NULL, &err);
2622 if (err) {
2623 error_propagate(errp, err);
2624 goto fail;
2625 }
2626
38a53d50
CL
2627 rc = do_open_tray(device, false, &err);
2628 if (rc && rc != -ENOSYS) {
de2c6c05
HR
2629 error_propagate(errp, err);
2630 goto fail;
2631 }
38a53d50
CL
2632 error_free(err);
2633 err = NULL;
de2c6c05 2634
6e0abc25 2635 qmp_x_blockdev_remove_medium(device, &err);
de2c6c05
HR
2636 if (err) {
2637 error_propagate(errp, err);
2638 goto fail;
2639 }
2640
2641 qmp_blockdev_insert_anon_medium(device, medium_bs, &err);
2642 if (err) {
2643 error_propagate(errp, err);
2644 goto fail;
2645 }
2646
a5614993
KW
2647 blk_apply_root_state(blk, medium_bs);
2648
de2c6c05
HR
2649 qmp_blockdev_close_tray(device, errp);
2650
2651fail:
2652 /* If the medium has been inserted, the device has its own reference, so
2653 * ours must be relinquished; and if it has not been inserted successfully,
2654 * the reference must be relinquished anyway */
2655 bdrv_unref(medium_bs);
2656}
2657
727f005e 2658/* throttling disk I/O limits */
4dc9397b 2659void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
727f005e 2660{
cc0681c4 2661 ThrottleConfig cfg;
727f005e 2662 BlockDriverState *bs;
a0e8544c 2663 BlockBackend *blk;
b15446fd 2664 AioContext *aio_context;
727f005e 2665
4dc9397b 2666 blk = blk_by_name(arg->device);
a0e8544c 2667 if (!blk) {
75158ebb 2668 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
4dc9397b 2669 "Device '%s' not found", arg->device);
80047da5 2670 return;
727f005e 2671 }
5433c24f
HR
2672
2673 aio_context = blk_get_aio_context(blk);
2674 aio_context_acquire(aio_context);
2675
a0e8544c 2676 bs = blk_bs(blk);
5433c24f 2677 if (!bs) {
4dc9397b 2678 error_setg(errp, "Device '%s' has no medium", arg->device);
5433c24f
HR
2679 goto out;
2680 }
727f005e 2681
1588ab5d 2682 throttle_config_init(&cfg);
4dc9397b
EB
2683 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2684 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2685 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
cc0681c4 2686
4dc9397b
EB
2687 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2688 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2689 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
cc0681c4 2690
4dc9397b
EB
2691 if (arg->has_bps_max) {
2692 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
3e9fab69 2693 }
4dc9397b
EB
2694 if (arg->has_bps_rd_max) {
2695 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
3e9fab69 2696 }
4dc9397b
EB
2697 if (arg->has_bps_wr_max) {
2698 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
3e9fab69 2699 }
4dc9397b
EB
2700 if (arg->has_iops_max) {
2701 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
3e9fab69 2702 }
4dc9397b
EB
2703 if (arg->has_iops_rd_max) {
2704 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
3e9fab69 2705 }
4dc9397b
EB
2706 if (arg->has_iops_wr_max) {
2707 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
3e9fab69 2708 }
727f005e 2709
4dc9397b
EB
2710 if (arg->has_bps_max_length) {
2711 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
dce13204 2712 }
4dc9397b
EB
2713 if (arg->has_bps_rd_max_length) {
2714 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
dce13204 2715 }
4dc9397b
EB
2716 if (arg->has_bps_wr_max_length) {
2717 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
dce13204 2718 }
4dc9397b
EB
2719 if (arg->has_iops_max_length) {
2720 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
dce13204 2721 }
4dc9397b
EB
2722 if (arg->has_iops_rd_max_length) {
2723 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
dce13204 2724 }
4dc9397b
EB
2725 if (arg->has_iops_wr_max_length) {
2726 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
dce13204
AG
2727 }
2728
4dc9397b
EB
2729 if (arg->has_iops_size) {
2730 cfg.op_size = arg->iops_size;
2024c1df 2731 }
cc0681c4 2732
d5851089 2733 if (!throttle_is_valid(&cfg, errp)) {
5433c24f 2734 goto out;
727f005e
ZYW
2735 }
2736
76f4afb4
AG
2737 if (throttle_enabled(&cfg)) {
2738 /* Enable I/O limits if they're not enabled yet, otherwise
2739 * just update the throttling group. */
97148076 2740 if (!blk_get_public(blk)->throttle_state) {
4dc9397b
EB
2741 blk_io_limits_enable(blk,
2742 arg->has_group ? arg->group : arg->device);
2743 } else if (arg->has_group) {
2744 blk_io_limits_update_group(blk, arg->group);
76f4afb4
AG
2745 }
2746 /* Set the new throttling configuration */
97148076
KW
2747 blk_set_io_limits(blk, &cfg);
2748 } else if (blk_get_public(blk)->throttle_state) {
76f4afb4 2749 /* If all throttling settings are set to 0, disable I/O limits */
97148076 2750 blk_io_limits_disable(blk);
727f005e 2751 }
b15446fd 2752
5433c24f 2753out:
b15446fd 2754 aio_context_release(aio_context);
727f005e
ZYW
2755}
2756
341ebc2f
JS
2757void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2758 bool has_granularity, uint32_t granularity,
2759 Error **errp)
2760{
2761 AioContext *aio_context;
2762 BlockDriverState *bs;
2763
2764 if (!name || name[0] == '\0') {
2765 error_setg(errp, "Bitmap name cannot be empty");
2766 return;
2767 }
2768
2769 bs = bdrv_lookup_bs(node, node, errp);
2770 if (!bs) {
2771 return;
2772 }
2773
2774 aio_context = bdrv_get_aio_context(bs);
2775 aio_context_acquire(aio_context);
2776
2777 if (has_granularity) {
2778 if (granularity < 512 || !is_power_of_2(granularity)) {
2779 error_setg(errp, "Granularity must be power of 2 "
2780 "and at least 512");
2781 goto out;
2782 }
2783 } else {
2784 /* Default to cluster size, if available: */
2785 granularity = bdrv_get_default_bitmap_granularity(bs);
2786 }
2787
2788 bdrv_create_dirty_bitmap(bs, granularity, name, errp);
2789
2790 out:
2791 aio_context_release(aio_context);
2792}
2793
2794void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
2795 Error **errp)
2796{
2797 AioContext *aio_context;
2798 BlockDriverState *bs;
2799 BdrvDirtyBitmap *bitmap;
2800
2801 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2802 if (!bitmap || !bs) {
2803 return;
2804 }
2805
9bd2b08f
JS
2806 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2807 error_setg(errp,
2808 "Bitmap '%s' is currently frozen and cannot be removed",
2809 name);
2810 goto out;
2811 }
20dca810 2812 bdrv_dirty_bitmap_make_anon(bitmap);
341ebc2f
JS
2813 bdrv_release_dirty_bitmap(bs, bitmap);
2814
9bd2b08f 2815 out:
341ebc2f
JS
2816 aio_context_release(aio_context);
2817}
2818
e74e6b78
JS
2819/**
2820 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
2821 * immediately after a full backup operation.
2822 */
2823void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
2824 Error **errp)
2825{
2826 AioContext *aio_context;
2827 BdrvDirtyBitmap *bitmap;
2828 BlockDriverState *bs;
2829
2830 bitmap = block_dirty_bitmap_lookup(node, name, &bs, &aio_context, errp);
2831 if (!bitmap || !bs) {
2832 return;
2833 }
2834
2835 if (bdrv_dirty_bitmap_frozen(bitmap)) {
2836 error_setg(errp,
2837 "Bitmap '%s' is currently frozen and cannot be modified",
2838 name);
2839 goto out;
2840 } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
2841 error_setg(errp,
2842 "Bitmap '%s' is currently disabled and cannot be cleared",
2843 name);
2844 goto out;
2845 }
2846
df9a681d 2847 bdrv_clear_dirty_bitmap(bitmap, NULL);
e74e6b78
JS
2848
2849 out:
2850 aio_context_release(aio_context);
2851}
2852
072ebe6b 2853void hmp_drive_del(Monitor *mon, const QDict *qdict)
9063f814
RH
2854{
2855 const char *id = qdict_get_str(qdict, "id");
7e7d56d9 2856 BlockBackend *blk;
9063f814 2857 BlockDriverState *bs;
8ad4202b 2858 AioContext *aio_context;
3718d8ab 2859 Error *local_err = NULL;
9063f814 2860
2073d410
KW
2861 bs = bdrv_find_node(id);
2862 if (bs) {
2863 qmp_x_blockdev_del(false, NULL, true, id, &local_err);
2864 if (local_err) {
2865 error_report_err(local_err);
2866 }
2867 return;
2868 }
2869
7e7d56d9
MA
2870 blk = blk_by_name(id);
2871 if (!blk) {
b1422f20 2872 error_report("Device '%s' not found", id);
072ebe6b 2873 return;
9063f814 2874 }
8ad4202b 2875
26f8b3a8 2876 if (!blk_legacy_dinfo(blk)) {
48f364dd
MA
2877 error_report("Deleting device added with blockdev-add"
2878 " is not supported");
072ebe6b 2879 return;
48f364dd
MA
2880 }
2881
5433c24f 2882 aio_context = blk_get_aio_context(blk);
8ad4202b
SH
2883 aio_context_acquire(aio_context);
2884
5433c24f
HR
2885 bs = blk_bs(blk);
2886 if (bs) {
2887 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
2888 error_report_err(local_err);
2889 aio_context_release(aio_context);
2890 return;
2891 }
9063f814 2892
938abd43 2893 blk_remove_bs(blk);
5433c24f 2894 }
9063f814 2895
7c735873 2896 /* Make the BlockBackend and the attached BlockDriverState anonymous */
efaa7c4e
HR
2897 monitor_remove_blk(blk);
2898
7c735873
HR
2899 /* If this BlockBackend has a device attached to it, its refcount will be
2900 * decremented when the device is removed; otherwise we have to do so here.
d22b2f41 2901 */
a7f53e26 2902 if (blk_get_attached_dev(blk)) {
293c51a6 2903 /* Further I/O must not pause the guest */
373340b2
HR
2904 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
2905 BLOCKDEV_ON_ERROR_REPORT);
d22b2f41 2906 } else {
b9fe8a7a 2907 blk_unref(blk);
9063f814
RH
2908 }
2909
8ad4202b 2910 aio_context_release(aio_context);
9063f814 2911}
6d4a2b3a 2912
3b1dbd11
BC
2913void qmp_block_resize(bool has_device, const char *device,
2914 bool has_node_name, const char *node_name,
2915 int64_t size, Error **errp)
6d4a2b3a 2916{
3b1dbd11 2917 Error *local_err = NULL;
6d4a2b3a 2918 BlockDriverState *bs;
927e0e76 2919 AioContext *aio_context;
8732901e 2920 int ret;
6d4a2b3a 2921
3b1dbd11
BC
2922 bs = bdrv_lookup_bs(has_device ? device : NULL,
2923 has_node_name ? node_name : NULL,
2924 &local_err);
84d18f06 2925 if (local_err) {
3b1dbd11
BC
2926 error_propagate(errp, local_err);
2927 return;
2928 }
2929
927e0e76
SH
2930 aio_context = bdrv_get_aio_context(bs);
2931 aio_context_acquire(aio_context);
2932
3b1dbd11 2933 if (!bdrv_is_first_non_filter(bs)) {
c6bd8c70 2934 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
927e0e76 2935 goto out;
6d4a2b3a
CH
2936 }
2937
2938 if (size < 0) {
c6bd8c70 2939 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
927e0e76 2940 goto out;
6d4a2b3a
CH
2941 }
2942
9c75e168 2943 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
c6bd8c70 2944 error_setg(errp, QERR_DEVICE_IN_USE, device);
927e0e76 2945 goto out;
9c75e168
JC
2946 }
2947
92b7a08d
PL
2948 /* complete all in-flight operations before resizing the device */
2949 bdrv_drain_all();
2950
8732901e
KW
2951 ret = bdrv_truncate(bs, size);
2952 switch (ret) {
939a1cc3
SH
2953 case 0:
2954 break;
2955 case -ENOMEDIUM:
c6bd8c70 2956 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
939a1cc3
SH
2957 break;
2958 case -ENOTSUP:
c6bd8c70 2959 error_setg(errp, QERR_UNSUPPORTED);
939a1cc3
SH
2960 break;
2961 case -EACCES:
81e5f78a 2962 error_setg(errp, "Device '%s' is read only", device);
939a1cc3
SH
2963 break;
2964 case -EBUSY:
c6bd8c70 2965 error_setg(errp, QERR_DEVICE_IN_USE, device);
939a1cc3
SH
2966 break;
2967 default:
8732901e 2968 error_setg_errno(errp, -ret, "Could not resize");
939a1cc3 2969 break;
6d4a2b3a 2970 }
927e0e76
SH
2971
2972out:
2973 aio_context_release(aio_context);
6d4a2b3a 2974}
12bd451f 2975
9abf2dba 2976static void block_job_cb(void *opaque, int ret)
12bd451f 2977{
723c5d93
SH
2978 /* Note that this function may be executed from another AioContext besides
2979 * the QEMU main loop. If you need to access anything that assumes the
2980 * QEMU global mutex, use a BH or introduce a mutex.
2981 */
2982
12bd451f 2983 BlockDriverState *bs = opaque;
bcada37b 2984 const char *msg = NULL;
12bd451f 2985
9abf2dba 2986 trace_block_job_cb(bs, bs->job, ret);
12bd451f
SH
2987
2988 assert(bs->job);
bcada37b 2989
12bd451f 2990 if (ret < 0) {
bcada37b 2991 msg = strerror(-ret);
12bd451f
SH
2992 }
2993
370521a1 2994 if (block_job_is_cancelled(bs->job)) {
bcada37b 2995 block_job_event_cancelled(bs->job);
370521a1 2996 } else {
bcada37b 2997 block_job_event_completed(bs->job, msg);
370521a1 2998 }
12bd451f
SH
2999}
3000
2323322e 3001void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
13d8cc51
JC
3002 bool has_base, const char *base,
3003 bool has_backing_file, const char *backing_file,
3004 bool has_speed, int64_t speed,
1d809098
PB
3005 bool has_on_error, BlockdevOnError on_error,
3006 Error **errp)
12bd451f
SH
3007{
3008 BlockDriverState *bs;
c8c3080f 3009 BlockDriverState *base_bs = NULL;
f3e69beb 3010 AioContext *aio_context;
fd7f8c65 3011 Error *local_err = NULL;
13d8cc51 3012 const char *base_name = NULL;
12bd451f 3013
1d809098
PB
3014 if (!has_on_error) {
3015 on_error = BLOCKDEV_ON_ERROR_REPORT;
3016 }
3017
b6c1bae5
KW
3018 bs = qmp_get_root_bs(device, errp);
3019 if (!bs) {
12bd451f
SH
3020 return;
3021 }
3022
b6c1bae5 3023 aio_context = bdrv_get_aio_context(bs);
f3e69beb
SH
3024 aio_context_acquire(aio_context);
3025
628ff683 3026 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_STREAM, errp)) {
f3e69beb 3027 goto out;
628ff683
FZ
3028 }
3029
13d8cc51 3030 if (has_base) {
c8c3080f
MT
3031 base_bs = bdrv_find_backing_image(bs, base);
3032 if (base_bs == NULL) {
c6bd8c70 3033 error_setg(errp, QERR_BASE_NOT_FOUND, base);
f3e69beb 3034 goto out;
c8c3080f 3035 }
f3e69beb 3036 assert(bdrv_get_aio_context(base_bs) == aio_context);
13d8cc51 3037 base_name = base;
12bd451f
SH
3038 }
3039
13d8cc51
JC
3040 /* if we are streaming the entire chain, the result will have no backing
3041 * file, and specifying one is therefore an error */
3042 if (base_bs == NULL && has_backing_file) {
3043 error_setg(errp, "backing file specified, but streaming the "
3044 "entire chain");
f3e69beb 3045 goto out;
13d8cc51
JC
3046 }
3047
3048 /* backing_file string overrides base bs filename */
3049 base_name = has_backing_file ? backing_file : base_name;
3050
2323322e
AG
3051 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3052 has_speed ? speed : 0, on_error, block_job_cb, bs, &local_err);
84d18f06 3053 if (local_err) {
fd7f8c65 3054 error_propagate(errp, local_err);
f3e69beb 3055 goto out;
12bd451f
SH
3056 }
3057
3058 trace_qmp_block_stream(bs, bs->job);
f3e69beb
SH
3059
3060out:
3061 aio_context_release(aio_context);
12bd451f 3062}
2d47c6e9 3063
fd62c609 3064void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
7676e2c5
JC
3065 bool has_base, const char *base,
3066 bool has_top, const char *top,
54e26900 3067 bool has_backing_file, const char *backing_file,
ed61fc10
JC
3068 bool has_speed, int64_t speed,
3069 Error **errp)
3070{
3071 BlockDriverState *bs;
3072 BlockDriverState *base_bs, *top_bs;
9e85cd5c 3073 AioContext *aio_context;
ed61fc10
JC
3074 Error *local_err = NULL;
3075 /* This will be part of the QMP command, if/when the
3076 * BlockdevOnError change for blkmirror makes it in
3077 */
92aa5c6d 3078 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
ed61fc10 3079
54504663
HR
3080 if (!has_speed) {
3081 speed = 0;
3082 }
3083
7676e2c5
JC
3084 /* Important Note:
3085 * libvirt relies on the DeviceNotFound error class in order to probe for
3086 * live commit feature versions; for this to work, we must make sure to
3087 * perform the device lookup before any generic errors that may occur in a
3088 * scenario in which all optional arguments are omitted. */
1d13b167
KW
3089 bs = qmp_get_root_bs(device, &local_err);
3090 if (!bs) {
3091 bs = bdrv_lookup_bs(device, device, NULL);
3092 if (!bs) {
3093 error_free(local_err);
3094 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3095 "Device '%s' not found", device);
3096 } else {
3097 error_propagate(errp, local_err);
3098 }
ed61fc10 3099 return;
628ff683
FZ
3100 }
3101
1d13b167 3102 aio_context = bdrv_get_aio_context(bs);
9e85cd5c
SH
3103 aio_context_acquire(aio_context);
3104
bb00021d 3105 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
9e85cd5c 3106 goto out;
ed61fc10 3107 }
ed61fc10
JC
3108
3109 /* default top_bs is the active layer */
3110 top_bs = bs;
3111
7676e2c5 3112 if (has_top && top) {
ed61fc10
JC
3113 if (strcmp(bs->filename, top) != 0) {
3114 top_bs = bdrv_find_backing_image(bs, top);
3115 }
3116 }
3117
3118 if (top_bs == NULL) {
3119 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
9e85cd5c 3120 goto out;
ed61fc10
JC
3121 }
3122
9e85cd5c
SH
3123 assert(bdrv_get_aio_context(top_bs) == aio_context);
3124
d5208c45
JC
3125 if (has_base && base) {
3126 base_bs = bdrv_find_backing_image(top_bs, base);
3127 } else {
3128 base_bs = bdrv_find_base(top_bs);
3129 }
3130
3131 if (base_bs == NULL) {
c6bd8c70 3132 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
9e85cd5c 3133 goto out;
d5208c45
JC
3134 }
3135
9e85cd5c
SH
3136 assert(bdrv_get_aio_context(base_bs) == aio_context);
3137
bb00021d
FZ
3138 if (bdrv_op_is_blocked(base_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3139 goto out;
3140 }
3141
7676e2c5
JC
3142 /* Do not allow attempts to commit an image into itself */
3143 if (top_bs == base_bs) {
3144 error_setg(errp, "cannot commit an image into itself");
9e85cd5c 3145 goto out;
7676e2c5
JC
3146 }
3147
20a63d2c 3148 if (top_bs == bs) {
54e26900
JC
3149 if (has_backing_file) {
3150 error_setg(errp, "'backing-file' specified,"
3151 " but 'top' is the active layer");
9e85cd5c 3152 goto out;
54e26900 3153 }
fd62c609
AG
3154 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs, speed,
3155 on_error, block_job_cb, bs, &local_err);
20a63d2c 3156 } else {
fd62c609
AG
3157 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, speed,
3158 on_error, block_job_cb, bs,
54e26900 3159 has_backing_file ? backing_file : NULL, &local_err);
20a63d2c 3160 }
ed61fc10
JC
3161 if (local_err != NULL) {
3162 error_propagate(errp, local_err);
9e85cd5c 3163 goto out;
ed61fc10 3164 }
9e85cd5c
SH
3165
3166out:
3167 aio_context_release(aio_context);
ed61fc10
JC
3168}
3169
70559d49
AG
3170static void do_drive_backup(const char *job_id, const char *device,
3171 const char *target, bool has_format,
3172 const char *format, enum MirrorSyncMode sync,
78f51fde
JS
3173 bool has_mode, enum NewImageMode mode,
3174 bool has_speed, int64_t speed,
3175 bool has_bitmap, const char *bitmap,
3176 bool has_on_source_error,
3177 BlockdevOnError on_source_error,
3178 bool has_on_target_error,
3179 BlockdevOnError on_target_error,
3180 BlockJobTxn *txn, Error **errp)
99a9addf 3181{
a0e8544c 3182 BlockBackend *blk;
99a9addf
SH
3183 BlockDriverState *bs;
3184 BlockDriverState *target_bs;
fc5d3f84 3185 BlockDriverState *source = NULL;
d58d8453 3186 BdrvDirtyBitmap *bmap = NULL;
761731b1 3187 AioContext *aio_context;
e6641719 3188 QDict *options = NULL;
99a9addf
SH
3189 Error *local_err = NULL;
3190 int flags;
3191 int64_t size;
99a9addf
SH
3192
3193 if (!has_speed) {
3194 speed = 0;
3195 }
3196 if (!has_on_source_error) {
3197 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3198 }
3199 if (!has_on_target_error) {
3200 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3201 }
3202 if (!has_mode) {
3203 mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3204 }
3205
a0e8544c
FZ
3206 blk = blk_by_name(device);
3207 if (!blk) {
75158ebb
MA
3208 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3209 "Device '%s' not found", device);
99a9addf
SH
3210 return;
3211 }
3212
5433c24f 3213 aio_context = blk_get_aio_context(blk);
761731b1
SH
3214 aio_context_acquire(aio_context);
3215
c29c1dd3
FZ
3216 /* Although backup_run has this check too, we need to use bs->drv below, so
3217 * do an early check redundantly. */
5433c24f 3218 if (!blk_is_available(blk)) {
c6bd8c70 3219 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
761731b1 3220 goto out;
99a9addf 3221 }
5433c24f 3222 bs = blk_bs(blk);
99a9addf
SH
3223
3224 if (!has_format) {
3225 format = mode == NEW_IMAGE_MODE_EXISTING ? NULL : bs->drv->format_name;
3226 }
99a9addf 3227
c29c1dd3 3228 /* Early check to avoid creating target */
3718d8ab 3229 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
761731b1 3230 goto out;
99a9addf
SH
3231 }
3232
61de4c68 3233 flags = bs->open_flags | BDRV_O_RDWR;
99a9addf 3234
fc5d3f84
IM
3235 /* See if we have a backing HD we can use to create our new image
3236 * on top of. */
3237 if (sync == MIRROR_SYNC_MODE_TOP) {
760e0063 3238 source = backing_bs(bs);
fc5d3f84
IM
3239 if (!source) {
3240 sync = MIRROR_SYNC_MODE_FULL;
3241 }
3242 }
3243 if (sync == MIRROR_SYNC_MODE_NONE) {
3244 source = bs;
3245 }
3246
99a9addf
SH
3247 size = bdrv_getlength(bs);
3248 if (size < 0) {
3249 error_setg_errno(errp, -size, "bdrv_getlength failed");
761731b1 3250 goto out;
99a9addf
SH
3251 }
3252
3253 if (mode != NEW_IMAGE_MODE_EXISTING) {
e6641719 3254 assert(format);
fc5d3f84
IM
3255 if (source) {
3256 bdrv_img_create(target, format, source->filename,
3257 source->drv->format_name, NULL,
3258 size, flags, &local_err, false);
3259 } else {
3260 bdrv_img_create(target, format, NULL, NULL, NULL,
3261 size, flags, &local_err, false);
3262 }
99a9addf
SH
3263 }
3264
84d18f06 3265 if (local_err) {
99a9addf 3266 error_propagate(errp, local_err);
761731b1 3267 goto out;
99a9addf
SH
3268 }
3269
e6641719
HR
3270 if (format) {
3271 options = qdict_new();
3272 qdict_put(options, "driver", qstring_from_str(format));
3273 }
3274
5b363937
HR
3275 target_bs = bdrv_open(target, NULL, options, flags, errp);
3276 if (!target_bs) {
761731b1 3277 goto out;
99a9addf
SH
3278 }
3279
761731b1
SH
3280 bdrv_set_aio_context(target_bs, aio_context);
3281
d58d8453
JS
3282 if (has_bitmap) {
3283 bmap = bdrv_find_dirty_bitmap(bs, bitmap);
3284 if (!bmap) {
3285 error_setg(errp, "Bitmap '%s' could not be found", bitmap);
0702d3d8 3286 bdrv_unref(target_bs);
d58d8453
JS
3287 goto out;
3288 }
3289 }
3290
70559d49 3291 backup_start(job_id, bs, target_bs, speed, sync, bmap,
d58d8453 3292 on_source_error, on_target_error,
78f51fde 3293 block_job_cb, bs, txn, &local_err);
5c438bc6 3294 bdrv_unref(target_bs);
99a9addf 3295 if (local_err != NULL) {
99a9addf 3296 error_propagate(errp, local_err);
761731b1 3297 goto out;
99a9addf 3298 }
761731b1
SH
3299
3300out:
3301 aio_context_release(aio_context);
99a9addf
SH
3302}
3303
70559d49
AG
3304void qmp_drive_backup(bool has_job_id, const char *job_id,
3305 const char *device, const char *target,
78f51fde
JS
3306 bool has_format, const char *format,
3307 enum MirrorSyncMode sync,
3308 bool has_mode, enum NewImageMode mode,
3309 bool has_speed, int64_t speed,
3310 bool has_bitmap, const char *bitmap,
3311 bool has_on_source_error, BlockdevOnError on_source_error,
3312 bool has_on_target_error, BlockdevOnError on_target_error,
3313 Error **errp)
3314{
70559d49
AG
3315 return do_drive_backup(has_job_id ? job_id : NULL, device, target,
3316 has_format, format, sync,
78f51fde
JS
3317 has_mode, mode, has_speed, speed,
3318 has_bitmap, bitmap,
3319 has_on_source_error, on_source_error,
3320 has_on_target_error, on_target_error,
3321 NULL, errp);
3322}
3323
c13163fb
BC
3324BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3325{
d5a8ee60 3326 return bdrv_named_nodes_list(errp);
c13163fb
BC
3327}
3328
70559d49
AG
3329void do_blockdev_backup(const char *job_id, const char *device,
3330 const char *target, enum MirrorSyncMode sync,
c29c1dd3
FZ
3331 bool has_speed, int64_t speed,
3332 bool has_on_source_error,
3333 BlockdevOnError on_source_error,
3334 bool has_on_target_error,
3335 BlockdevOnError on_target_error,
78f51fde 3336 BlockJobTxn *txn, Error **errp)
c29c1dd3 3337{
0d978913 3338 BlockBackend *blk;
c29c1dd3
FZ
3339 BlockDriverState *bs;
3340 BlockDriverState *target_bs;
3341 Error *local_err = NULL;
3342 AioContext *aio_context;
3343
3344 if (!has_speed) {
3345 speed = 0;
3346 }
3347 if (!has_on_source_error) {
3348 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3349 }
3350 if (!has_on_target_error) {
3351 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3352 }
3353
a0e8544c
FZ
3354 blk = blk_by_name(device);
3355 if (!blk) {
5b347c54 3356 error_setg(errp, "Device '%s' not found", device);
c29c1dd3
FZ
3357 return;
3358 }
3359
5433c24f 3360 aio_context = blk_get_aio_context(blk);
c29c1dd3
FZ
3361 aio_context_acquire(aio_context);
3362
5433c24f
HR
3363 if (!blk_is_available(blk)) {
3364 error_setg(errp, "Device '%s' has no medium", device);
3365 goto out;
3366 }
3367 bs = blk_bs(blk);
3368
0d978913
FZ
3369 target_bs = bdrv_lookup_bs(target, target, errp);
3370 if (!target_bs) {
5433c24f
HR
3371 goto out;
3372 }
c29c1dd3 3373
efd75567
FZ
3374 if (bdrv_get_aio_context(target_bs) != aio_context) {
3375 if (!bdrv_has_blk(target_bs)) {
3376 /* The target BDS is not attached, we can safely move it to another
3377 * AioContext. */
3378 bdrv_set_aio_context(target_bs, aio_context);
3379 } else {
3380 error_setg(errp, "Target is attached to a different thread from "
3381 "source.");
3382 goto out;
3383 }
3384 }
70559d49 3385 backup_start(job_id, bs, target_bs, speed, sync, NULL, on_source_error,
78f51fde 3386 on_target_error, block_job_cb, bs, txn, &local_err);
c29c1dd3 3387 if (local_err != NULL) {
c29c1dd3
FZ
3388 error_propagate(errp, local_err);
3389 }
3390out:
3391 aio_context_release(aio_context);
3392}
3393
70559d49
AG
3394void qmp_blockdev_backup(bool has_job_id, const char *job_id,
3395 const char *device, const char *target,
78f51fde
JS
3396 enum MirrorSyncMode sync,
3397 bool has_speed, int64_t speed,
3398 bool has_on_source_error,
3399 BlockdevOnError on_source_error,
3400 bool has_on_target_error,
3401 BlockdevOnError on_target_error,
3402 Error **errp)
3403{
70559d49
AG
3404 do_blockdev_backup(has_job_id ? job_id : NULL, device, target,
3405 sync, has_speed, speed,
78f51fde
JS
3406 has_on_source_error, on_source_error,
3407 has_on_target_error, on_target_error,
3408 NULL, errp);
3409}
3410
4193cdd7
FZ
3411/* Parameter check and block job starting for drive mirroring.
3412 * Caller should hold @device and @target's aio context (must be the same).
3413 **/
71aa9867 3414static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
4193cdd7
FZ
3415 BlockDriverState *target,
3416 bool has_replaces, const char *replaces,
3417 enum MirrorSyncMode sync,
274fccee 3418 BlockMirrorBackingMode backing_mode,
4193cdd7
FZ
3419 bool has_speed, int64_t speed,
3420 bool has_granularity, uint32_t granularity,
3421 bool has_buf_size, int64_t buf_size,
3422 bool has_on_source_error,
3423 BlockdevOnError on_source_error,
3424 bool has_on_target_error,
3425 BlockdevOnError on_target_error,
3426 bool has_unmap, bool unmap,
3427 Error **errp)
d9b902db 3428{
d9b902db
PB
3429
3430 if (!has_speed) {
3431 speed = 0;
3432 }
b952b558
PB
3433 if (!has_on_source_error) {
3434 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3435 }
3436 if (!has_on_target_error) {
3437 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3438 }
eee13dfe
PB
3439 if (!has_granularity) {
3440 granularity = 0;
3441 }
08e4ed6c 3442 if (!has_buf_size) {
48ac0a4d 3443 buf_size = 0;
08e4ed6c 3444 }
0fc9f8ea
FZ
3445 if (!has_unmap) {
3446 unmap = true;
3447 }
08e4ed6c 3448
eee13dfe 3449 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
c6bd8c70
MA
3450 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3451 "a value in range [512B, 64MB]");
eee13dfe
PB
3452 return;
3453 }
3454 if (granularity & (granularity - 1)) {
c6bd8c70
MA
3455 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3456 "power of 2");
eee13dfe
PB
3457 return;
3458 }
d9b902db 3459
4193cdd7
FZ
3460 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3461 return;
3462 }
e40e5027
FZ
3463 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3464 return;
3465 }
4193cdd7
FZ
3466
3467 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3468 sync = MIRROR_SYNC_MODE_FULL;
3469 }
3470
3471 /* pass the node name to replace to mirror start since it's loose coupling
3472 * and will allow to check whether the node still exist at mirror completion
3473 */
71aa9867 3474 mirror_start(job_id, bs, target,
4193cdd7 3475 has_replaces ? replaces : NULL,
274fccee 3476 speed, granularity, buf_size, sync, backing_mode,
4193cdd7
FZ
3477 on_source_error, on_target_error, unmap,
3478 block_job_cb, bs, errp);
3479}
3480
faecd40a 3481void qmp_drive_mirror(DriveMirror *arg, Error **errp)
4193cdd7
FZ
3482{
3483 BlockDriverState *bs;
3484 BlockBackend *blk;
3485 BlockDriverState *source, *target_bs;
3486 AioContext *aio_context;
274fccee 3487 BlockMirrorBackingMode backing_mode;
4193cdd7
FZ
3488 Error *local_err = NULL;
3489 QDict *options = NULL;
3490 int flags;
3491 int64_t size;
faecd40a 3492 const char *format = arg->format;
4193cdd7 3493
faecd40a 3494 blk = blk_by_name(arg->device);
a0e8544c 3495 if (!blk) {
75158ebb 3496 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
faecd40a 3497 "Device '%s' not found", arg->device);
d9b902db
PB
3498 return;
3499 }
3500
5433c24f 3501 aio_context = blk_get_aio_context(blk);
5a7e7a0b
SH
3502 aio_context_acquire(aio_context);
3503
5433c24f 3504 if (!blk_is_available(blk)) {
faecd40a 3505 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, arg->device);
5a7e7a0b 3506 goto out;
d9b902db 3507 }
5433c24f 3508 bs = blk_bs(blk);
faecd40a
EB
3509 if (!arg->has_mode) {
3510 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
4193cdd7 3511 }
d9b902db 3512
faecd40a
EB
3513 if (!arg->has_format) {
3514 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3515 ? NULL : bs->drv->format_name);
d9b902db 3516 }
d9b902db 3517
61de4c68 3518 flags = bs->open_flags | BDRV_O_RDWR;
760e0063 3519 source = backing_bs(bs);
faecd40a
EB
3520 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3521 arg->sync = MIRROR_SYNC_MODE_FULL;
d9b902db 3522 }
faecd40a 3523 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
117e0c82
HR
3524 source = bs;
3525 }
d9b902db 3526
ac3c5d83
SH
3527 size = bdrv_getlength(bs);
3528 if (size < 0) {
3529 error_setg_errno(errp, -size, "bdrv_getlength failed");
5a7e7a0b 3530 goto out;
ac3c5d83
SH
3531 }
3532
faecd40a 3533 if (arg->has_replaces) {
09158f00 3534 BlockDriverState *to_replace_bs;
5a7e7a0b
SH
3535 AioContext *replace_aio_context;
3536 int64_t replace_size;
09158f00 3537
faecd40a 3538 if (!arg->has_node_name) {
09158f00
BC
3539 error_setg(errp, "a node-name must be provided when replacing a"
3540 " named node of the graph");
5a7e7a0b 3541 goto out;
09158f00
BC
3542 }
3543
faecd40a 3544 to_replace_bs = check_to_replace_node(bs, arg->replaces, &local_err);
09158f00
BC
3545
3546 if (!to_replace_bs) {
3547 error_propagate(errp, local_err);
5a7e7a0b 3548 goto out;
09158f00
BC
3549 }
3550
5a7e7a0b
SH
3551 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3552 aio_context_acquire(replace_aio_context);
3553 replace_size = bdrv_getlength(to_replace_bs);
3554 aio_context_release(replace_aio_context);
3555
3556 if (size != replace_size) {
09158f00
BC
3557 error_setg(errp, "cannot replace image with a mirror image of "
3558 "different size");
5a7e7a0b 3559 goto out;
09158f00
BC
3560 }
3561 }
3562
faecd40a 3563 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
274fccee
HR
3564 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3565 } else {
3566 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3567 }
3568
faecd40a
EB
3569 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3570 && arg->mode != NEW_IMAGE_MODE_EXISTING)
14526864 3571 {
d9b902db 3572 /* create new image w/o backing file */
e6641719 3573 assert(format);
faecd40a 3574 bdrv_img_create(arg->target, format,
f382d43a 3575 NULL, NULL, NULL, size, flags, &local_err, false);
d9b902db 3576 } else {
faecd40a 3577 switch (arg->mode) {
d9b902db 3578 case NEW_IMAGE_MODE_EXISTING:
d9b902db
PB
3579 break;
3580 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3581 /* create new image with backing file */
faecd40a 3582 bdrv_img_create(arg->target, format,
cf8f2426
LC
3583 source->filename,
3584 source->drv->format_name,
f382d43a 3585 NULL, size, flags, &local_err, false);
d9b902db
PB
3586 break;
3587 default:
3588 abort();
3589 }
3590 }
3591
84d18f06 3592 if (local_err) {
cf8f2426 3593 error_propagate(errp, local_err);
5a7e7a0b 3594 goto out;
d9b902db
PB
3595 }
3596
e6641719 3597 options = qdict_new();
faecd40a
EB
3598 if (arg->has_node_name) {
3599 qdict_put(options, "node-name", qstring_from_str(arg->node_name));
4c828dc6 3600 }
e6641719
HR
3601 if (format) {
3602 qdict_put(options, "driver", qstring_from_str(format));
3603 }
4c828dc6 3604
b812f671
PB
3605 /* Mirroring takes care of copy-on-write using the source's backing
3606 * file.
3607 */
faecd40a
EB
3608 target_bs = bdrv_open(arg->target, NULL, options,
3609 flags | BDRV_O_NO_BACKING, errp);
5b363937 3610 if (!target_bs) {
5a7e7a0b 3611 goto out;
d9b902db
PB
3612 }
3613
5a7e7a0b
SH
3614 bdrv_set_aio_context(target_bs, aio_context);
3615
faecd40a
EB
3616 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
3617 arg->has_replaces, arg->replaces, arg->sync,
3618 backing_mode, arg->has_speed, arg->speed,
3619 arg->has_granularity, arg->granularity,
3620 arg->has_buf_size, arg->buf_size,
3621 arg->has_on_source_error, arg->on_source_error,
3622 arg->has_on_target_error, arg->on_target_error,
3623 arg->has_unmap, arg->unmap,
4193cdd7 3624 &local_err);
e253f4b8 3625 bdrv_unref(target_bs);
621ff94d 3626 error_propagate(errp, local_err);
5a7e7a0b
SH
3627out:
3628 aio_context_release(aio_context);
d9b902db
PB
3629}
3630
71aa9867
AG
3631void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
3632 const char *device, const char *target,
df92562e
FZ
3633 bool has_replaces, const char *replaces,
3634 MirrorSyncMode sync,
3635 bool has_speed, int64_t speed,
3636 bool has_granularity, uint32_t granularity,
3637 bool has_buf_size, int64_t buf_size,
3638 bool has_on_source_error,
3639 BlockdevOnError on_source_error,
3640 bool has_on_target_error,
3641 BlockdevOnError on_target_error,
3642 Error **errp)
3643{
3644 BlockDriverState *bs;
3645 BlockBackend *blk;
3646 BlockDriverState *target_bs;
3647 AioContext *aio_context;
274fccee 3648 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
df92562e
FZ
3649 Error *local_err = NULL;
3650
3651 blk = blk_by_name(device);
3652 if (!blk) {
3653 error_setg(errp, "Device '%s' not found", device);
3654 return;
3655 }
3656 bs = blk_bs(blk);
3657
3658 if (!bs) {
3659 error_setg(errp, "Device '%s' has no media", device);
3660 return;
3661 }
3662
3663 target_bs = bdrv_lookup_bs(target, target, errp);
3664 if (!target_bs) {
3665 return;
3666 }
3667
3668 aio_context = bdrv_get_aio_context(bs);
3669 aio_context_acquire(aio_context);
3670
df92562e
FZ
3671 bdrv_set_aio_context(target_bs, aio_context);
3672
71aa9867 3673 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
274fccee 3674 has_replaces, replaces, sync, backing_mode,
df92562e
FZ
3675 has_speed, speed,
3676 has_granularity, granularity,
3677 has_buf_size, buf_size,
3678 has_on_source_error, on_source_error,
3679 has_on_target_error, on_target_error,
3680 true, true,
3681 &local_err);
621ff94d 3682 error_propagate(errp, local_err);
df92562e
FZ
3683
3684 aio_context_release(aio_context);
3685}
3686
3ddf3efe
AG
3687/* Get a block job using its ID and acquire its AioContext */
3688static BlockJob *find_block_job(const char *id, AioContext **aio_context,
24d6bffe 3689 Error **errp)
2d47c6e9 3690{
3ddf3efe 3691 BlockJob *job;
2d47c6e9 3692
3ddf3efe 3693 assert(id != NULL);
5433c24f 3694
3ddf3efe 3695 *aio_context = NULL;
3d948cdf 3696
3ddf3efe 3697 job = block_job_get(id);
5433c24f 3698
3ddf3efe
AG
3699 if (!job) {
3700 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
3701 "Block job '%s' not found", id);
3702 return NULL;
2d47c6e9 3703 }
3d948cdf 3704
3ddf3efe
AG
3705 *aio_context = blk_get_aio_context(job->blk);
3706 aio_context_acquire(*aio_context);
3d948cdf 3707
3ddf3efe 3708 return job;
2d47c6e9
SH
3709}
3710
882ec7ce 3711void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
2d47c6e9 3712{
3d948cdf 3713 AioContext *aio_context;
24d6bffe 3714 BlockJob *job = find_block_job(device, &aio_context, errp);
2d47c6e9
SH
3715
3716 if (!job) {
2d47c6e9
SH
3717 return;
3718 }
3719
882ec7ce 3720 block_job_set_speed(job, speed, errp);
3d948cdf 3721 aio_context_release(aio_context);
2d47c6e9 3722}
370521a1 3723
6e37fb81
PB
3724void qmp_block_job_cancel(const char *device,
3725 bool has_force, bool force, Error **errp)
370521a1 3726{
3d948cdf 3727 AioContext *aio_context;
24d6bffe 3728 BlockJob *job = find_block_job(device, &aio_context, errp);
6e37fb81 3729
370521a1 3730 if (!job) {
370521a1
SH
3731 return;
3732 }
3d948cdf
SH
3733
3734 if (!has_force) {
3735 force = false;
3736 }
3737
751ebd76 3738 if (job->user_paused && !force) {
f231b88d
CR
3739 error_setg(errp, "The block job for device '%s' is currently paused",
3740 device);
3d948cdf 3741 goto out;
8acc72a4 3742 }
370521a1
SH
3743
3744 trace_qmp_block_job_cancel(job);
3745 block_job_cancel(job);
3d948cdf
SH
3746out:
3747 aio_context_release(aio_context);
370521a1 3748}
fb5458cd 3749
6e37fb81
PB
3750void qmp_block_job_pause(const char *device, Error **errp)
3751{
3d948cdf 3752 AioContext *aio_context;
24d6bffe 3753 BlockJob *job = find_block_job(device, &aio_context, errp);
6e37fb81 3754
751ebd76 3755 if (!job || job->user_paused) {
6e37fb81
PB
3756 return;
3757 }
3758
751ebd76 3759 job->user_paused = true;
6e37fb81
PB
3760 trace_qmp_block_job_pause(job);
3761 block_job_pause(job);
3d948cdf 3762 aio_context_release(aio_context);
6e37fb81
PB
3763}
3764
3765void qmp_block_job_resume(const char *device, Error **errp)
3766{
3d948cdf 3767 AioContext *aio_context;
24d6bffe 3768 BlockJob *job = find_block_job(device, &aio_context, errp);
6e37fb81 3769
751ebd76 3770 if (!job || !job->user_paused) {
6e37fb81
PB
3771 return;
3772 }
3773
751ebd76 3774 job->user_paused = false;
6e37fb81 3775 trace_qmp_block_job_resume(job);
17bd51f9 3776 block_job_iostatus_reset(job);
6e37fb81 3777 block_job_resume(job);
3d948cdf 3778 aio_context_release(aio_context);
6e37fb81
PB
3779}
3780
aeae883b
PB
3781void qmp_block_job_complete(const char *device, Error **errp)
3782{
3d948cdf 3783 AioContext *aio_context;
24d6bffe 3784 BlockJob *job = find_block_job(device, &aio_context, errp);
aeae883b
PB
3785
3786 if (!job) {
aeae883b
PB
3787 return;
3788 }
3789
3790 trace_qmp_block_job_complete(job);
3791 block_job_complete(job, errp);
3d948cdf 3792 aio_context_release(aio_context);
aeae883b
PB
3793}
3794
fa40e656
JC
3795void qmp_change_backing_file(const char *device,
3796 const char *image_node_name,
3797 const char *backing_file,
3798 Error **errp)
3799{
a0e8544c 3800 BlockBackend *blk;
fa40e656 3801 BlockDriverState *bs = NULL;
729962f6 3802 AioContext *aio_context;
fa40e656
JC
3803 BlockDriverState *image_bs = NULL;
3804 Error *local_err = NULL;
3805 bool ro;
3806 int open_flags;
3807 int ret;
3808
a0e8544c
FZ
3809 blk = blk_by_name(device);
3810 if (!blk) {
75158ebb
MA
3811 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3812 "Device '%s' not found", device);
fa40e656
JC
3813 return;
3814 }
3815
5433c24f 3816 aio_context = blk_get_aio_context(blk);
729962f6
SH
3817 aio_context_acquire(aio_context);
3818
5433c24f
HR
3819 if (!blk_is_available(blk)) {
3820 error_setg(errp, "Device '%s' has no medium", device);
3821 goto out;
3822 }
3823 bs = blk_bs(blk);
3824
fa40e656
JC
3825 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
3826 if (local_err) {
3827 error_propagate(errp, local_err);
729962f6 3828 goto out;
fa40e656
JC
3829 }
3830
3831 if (!image_bs) {
3832 error_setg(errp, "image file not found");
729962f6 3833 goto out;
fa40e656
JC
3834 }
3835
3836 if (bdrv_find_base(image_bs) == image_bs) {
3837 error_setg(errp, "not allowing backing file change on an image "
3838 "without a backing file");
729962f6 3839 goto out;
fa40e656
JC
3840 }
3841
3842 /* even though we are not necessarily operating on bs, we need it to
3843 * determine if block ops are currently prohibited on the chain */
3844 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
729962f6 3845 goto out;
fa40e656
JC
3846 }
3847
3848 /* final sanity check */
3849 if (!bdrv_chain_contains(bs, image_bs)) {
3850 error_setg(errp, "'%s' and image file are not in the same chain",
3851 device);
729962f6 3852 goto out;
fa40e656
JC
3853 }
3854
3855 /* if not r/w, reopen to make r/w */
3856 open_flags = image_bs->open_flags;
3857 ro = bdrv_is_read_only(image_bs);
3858
3859 if (ro) {
3860 bdrv_reopen(image_bs, open_flags | BDRV_O_RDWR, &local_err);
3861 if (local_err) {
3862 error_propagate(errp, local_err);
729962f6 3863 goto out;
fa40e656
JC
3864 }
3865 }
3866
3867 ret = bdrv_change_backing_file(image_bs, backing_file,
3868 image_bs->drv ? image_bs->drv->format_name : "");
3869
3870 if (ret < 0) {
3871 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
3872 backing_file);
3873 /* don't exit here, so we can try to restore open flags if
3874 * appropriate */
3875 }
3876
3877 if (ro) {
3878 bdrv_reopen(image_bs, open_flags, &local_err);
621ff94d 3879 error_propagate(errp, local_err);
fa40e656 3880 }
729962f6
SH
3881
3882out:
3883 aio_context_release(aio_context);
fa40e656
JC
3884}
3885
abb21ac3
KW
3886void hmp_drive_add_node(Monitor *mon, const char *optstr)
3887{
3888 QemuOpts *opts;
3889 QDict *qdict;
3890 Error *local_err = NULL;
3891
3892 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
3893 if (!opts) {
3894 return;
3895 }
3896
3897 qdict = qemu_opts_to_qdict(opts, NULL);
3898
3899 if (!qdict_get_try_str(qdict, "node-name")) {
f8746fb8 3900 QDECREF(qdict);
abb21ac3
KW
3901 error_report("'node-name' needs to be specified");
3902 goto out;
3903 }
3904
3905 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
3906 if (!bs) {
3907 error_report_err(local_err);
3908 goto out;
3909 }
3910
3911 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
3912
3913out:
3914 qemu_opts_del(opts);
3915}
3916
d26c9a15
KW
3917void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
3918{
be4b67bc
HR
3919 BlockDriverState *bs;
3920 BlockBackend *blk = NULL;
d26c9a15 3921 QObject *obj;
3b098d56 3922 Visitor *v = qmp_output_visitor_new(&obj);
d26c9a15 3923 QDict *qdict;
d26c9a15
KW
3924 Error *local_err = NULL;
3925
60e19e06 3926 /* TODO Sort it out in raw-posix and drive_new(): Reject aio=native with
d26c9a15 3927 * cache.direct=false instead of silently switching to aio=threads, except
60e19e06 3928 * when called from drive_new().
d26c9a15
KW
3929 *
3930 * For now, simply forbidding the combination for all drivers will do. */
3931 if (options->has_aio && options->aio == BLOCKDEV_AIO_OPTIONS_NATIVE) {
c6e0bd9b
KW
3932 bool direct = options->has_cache &&
3933 options->cache->has_direct &&
3934 options->cache->direct;
3935 if (!direct) {
d26c9a15
KW
3936 error_setg(errp, "aio=native requires cache.direct=true");
3937 goto fail;
3938 }
3939 }
3940
3b098d56 3941 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
84d18f06 3942 if (local_err) {
d26c9a15
KW
3943 error_propagate(errp, local_err);
3944 goto fail;
3945 }
3946
3b098d56 3947 visit_complete(v, &obj);
d26c9a15
KW
3948 qdict = qobject_to_qdict(obj);
3949
3950 qdict_flatten(qdict);
3951
be4b67bc
HR
3952 if (options->has_id) {
3953 blk = blockdev_init(NULL, qdict, &local_err);
3954 if (local_err) {
3955 error_propagate(errp, local_err);
3956 goto fail;
3957 }
3958
3959 bs = blk_bs(blk);
3960 } else {
be4b67bc
HR
3961 if (!qdict_get_try_str(qdict, "node-name")) {
3962 error_setg(errp, "'id' and/or 'node-name' need to be specified for "
3963 "the root node");
3964 goto fail;
3965 }
3966
bd745e23
HR
3967 bs = bds_tree_init(qdict, errp);
3968 if (!bs) {
be4b67bc
HR
3969 goto fail;
3970 }
9c4218e9
HR
3971
3972 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
d26c9a15
KW
3973 }
3974
be4b67bc
HR
3975 if (bs && bdrv_key_required(bs)) {
3976 if (blk) {
efaa7c4e 3977 monitor_remove_blk(blk);
be4b67bc
HR
3978 blk_unref(blk);
3979 } else {
9c4218e9 3980 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
be4b67bc
HR
3981 bdrv_unref(bs);
3982 }
8ae8e904
KW
3983 error_setg(errp, "blockdev-add doesn't support encrypted devices");
3984 goto fail;
3985 }
3986
d26c9a15 3987fail:
3b098d56 3988 visit_free(v);
d26c9a15
KW
3989}
3990
81b936ae
AG
3991void qmp_x_blockdev_del(bool has_id, const char *id,
3992 bool has_node_name, const char *node_name, Error **errp)
3993{
3994 AioContext *aio_context;
3995 BlockBackend *blk;
3996 BlockDriverState *bs;
3997
3998 if (has_id && has_node_name) {
3999 error_setg(errp, "Only one of id and node-name must be specified");
4000 return;
4001 } else if (!has_id && !has_node_name) {
4002 error_setg(errp, "No block device specified");
4003 return;
4004 }
4005
4006 if (has_id) {
efaa7c4e 4007 /* blk_by_name() never returns a BB that is not owned by the monitor */
81b936ae
AG
4008 blk = blk_by_name(id);
4009 if (!blk) {
4010 error_setg(errp, "Cannot find block backend %s", id);
4011 return;
4012 }
5cf87fd6
PB
4013 if (blk_legacy_dinfo(blk)) {
4014 error_setg(errp, "Deleting block backend added with drive-add"
4015 " is not supported");
4016 return;
4017 }
81b936ae
AG
4018 if (blk_get_refcnt(blk) > 1) {
4019 error_setg(errp, "Block backend %s is in use", id);
4020 return;
4021 }
4022 bs = blk_bs(blk);
4023 aio_context = blk_get_aio_context(blk);
4024 } else {
1f0c461b 4025 blk = NULL;
81b936ae
AG
4026 bs = bdrv_find_node(node_name);
4027 if (!bs) {
4028 error_setg(errp, "Cannot find node %s", node_name);
4029 return;
4030 }
1f0c461b 4031 if (bdrv_has_blk(bs)) {
81b936ae 4032 error_setg(errp, "Node %s is in use by %s",
1f0c461b 4033 node_name, bdrv_get_parent_name(bs));
81b936ae
AG
4034 return;
4035 }
4036 aio_context = bdrv_get_aio_context(bs);
4037 }
4038
4039 aio_context_acquire(aio_context);
4040
4041 if (bs) {
4042 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4043 goto out;
4044 }
4045
9c4218e9
HR
4046 if (!blk && !bs->monitor_list.tqe_prev) {
4047 error_setg(errp, "Node %s is not owned by the monitor",
4048 bs->node_name);
4049 goto out;
4050 }
4051
4052 if (bs->refcnt > 1) {
81b936ae
AG
4053 error_setg(errp, "Block device %s is in use",
4054 bdrv_get_device_or_node_name(bs));
4055 goto out;
4056 }
4057 }
4058
4059 if (blk) {
efaa7c4e 4060 monitor_remove_blk(blk);
81b936ae
AG
4061 blk_unref(blk);
4062 } else {
9c4218e9 4063 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
81b936ae
AG
4064 bdrv_unref(bs);
4065 }
4066
4067out:
4068 aio_context_release(aio_context);
4069}
4070
7f821597
WC
4071static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
4072 const char *child_name)
4073{
4074 BdrvChild *child;
4075
4076 QLIST_FOREACH(child, &parent_bs->children, next) {
4077 if (strcmp(child->name, child_name) == 0) {
4078 return child;
4079 }
4080 }
4081
4082 return NULL;
4083}
4084
4085void qmp_x_blockdev_change(const char *parent, bool has_child,
4086 const char *child, bool has_node,
4087 const char *node, Error **errp)
4088{
4089 BlockDriverState *parent_bs, *new_bs = NULL;
4090 BdrvChild *p_child;
4091
4092 parent_bs = bdrv_lookup_bs(parent, parent, errp);
4093 if (!parent_bs) {
4094 return;
4095 }
4096
4097 if (has_child == has_node) {
4098 if (has_child) {
4099 error_setg(errp, "The parameters child and node are in conflict");
4100 } else {
4101 error_setg(errp, "Either child or node must be specified");
4102 }
4103 return;
4104 }
4105
4106 if (has_child) {
4107 p_child = bdrv_find_child(parent_bs, child);
4108 if (!p_child) {
4109 error_setg(errp, "Node '%s' does not have child '%s'",
4110 parent, child);
4111 return;
4112 }
4113 bdrv_del_child(parent_bs, p_child, errp);
4114 }
4115
4116 if (has_node) {
4117 new_bs = bdrv_find_node(node);
4118 if (!new_bs) {
4119 error_setg(errp, "Node '%s' not found", node);
4120 return;
4121 }
4122 bdrv_add_child(parent_bs, new_bs, errp);
4123 }
4124}
4125
fea68bb6 4126BlockJobInfoList *qmp_query_block_jobs(Error **errp)
fb5458cd 4127{
fea68bb6 4128 BlockJobInfoList *head = NULL, **p_next = &head;
f0f55ded 4129 BlockJob *job;
fb5458cd 4130
f0f55ded
AG
4131 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4132 BlockJobInfoList *elem = g_new0(BlockJobInfoList, 1);
4133 AioContext *aio_context = blk_get_aio_context(job->blk);
69691e72
SH
4134
4135 aio_context_acquire(aio_context);
f0f55ded 4136 elem->value = block_job_query(job);
69691e72 4137 aio_context_release(aio_context);
f0f55ded
AG
4138
4139 *p_next = elem;
4140 p_next = &elem->next;
fb5458cd 4141 }
fb5458cd 4142
fea68bb6 4143 return head;
fb5458cd 4144}
4d454574 4145
0006383e 4146QemuOptsList qemu_common_drive_opts = {
4d454574 4147 .name = "drive",
0006383e 4148 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4d454574
PB
4149 .desc = {
4150 {
4d454574
PB
4151 .name = "snapshot",
4152 .type = QEMU_OPT_BOOL,
4153 .help = "enable/disable snapshot mode",
a9384aff
PB
4154 },{
4155 .name = "discard",
4156 .type = QEMU_OPT_STRING,
4157 .help = "discard operation (ignore/off, unmap/on)",
4d454574
PB
4158 },{
4159 .name = "aio",
4160 .type = QEMU_OPT_STRING,
4161 .help = "host AIO implementation (threads, native)",
e4b24b49
KW
4162 },{
4163 .name = BDRV_OPT_CACHE_WB,
4164 .type = QEMU_OPT_BOOL,
4165 .help = "Enable writeback mode",
4d454574
PB
4166 },{
4167 .name = "format",
4168 .type = QEMU_OPT_STRING,
4169 .help = "disk format (raw, qcow2, ...)",
4d454574
PB
4170 },{
4171 .name = "rerror",
4172 .type = QEMU_OPT_STRING,
4173 .help = "read error action",
4174 },{
4175 .name = "werror",
4176 .type = QEMU_OPT_STRING,
4177 .help = "write error action",
4d454574 4178 },{
0f227a94 4179 .name = "read-only",
4d454574
PB
4180 .type = QEMU_OPT_BOOL,
4181 .help = "open drive file as read-only",
4182 },{
57975222 4183 .name = "throttling.iops-total",
4d454574
PB
4184 .type = QEMU_OPT_NUMBER,
4185 .help = "limit total I/O operations per second",
4186 },{
57975222 4187 .name = "throttling.iops-read",
4d454574
PB
4188 .type = QEMU_OPT_NUMBER,
4189 .help = "limit read operations per second",
4190 },{
57975222 4191 .name = "throttling.iops-write",
4d454574
PB
4192 .type = QEMU_OPT_NUMBER,
4193 .help = "limit write operations per second",
4194 },{
57975222 4195 .name = "throttling.bps-total",
4d454574
PB
4196 .type = QEMU_OPT_NUMBER,
4197 .help = "limit total bytes per second",
4198 },{
57975222 4199 .name = "throttling.bps-read",
4d454574
PB
4200 .type = QEMU_OPT_NUMBER,
4201 .help = "limit read bytes per second",
4202 },{
57975222 4203 .name = "throttling.bps-write",
4d454574
PB
4204 .type = QEMU_OPT_NUMBER,
4205 .help = "limit write bytes per second",
3e9fab69
BC
4206 },{
4207 .name = "throttling.iops-total-max",
4208 .type = QEMU_OPT_NUMBER,
4209 .help = "I/O operations burst",
4210 },{
4211 .name = "throttling.iops-read-max",
4212 .type = QEMU_OPT_NUMBER,
4213 .help = "I/O operations read burst",
4214 },{
4215 .name = "throttling.iops-write-max",
4216 .type = QEMU_OPT_NUMBER,
4217 .help = "I/O operations write burst",
4218 },{
4219 .name = "throttling.bps-total-max",
4220 .type = QEMU_OPT_NUMBER,
4221 .help = "total bytes burst",
4222 },{
4223 .name = "throttling.bps-read-max",
4224 .type = QEMU_OPT_NUMBER,
4225 .help = "total bytes read burst",
4226 },{
4227 .name = "throttling.bps-write-max",
4228 .type = QEMU_OPT_NUMBER,
4229 .help = "total bytes write burst",
8a0fc18d
AG
4230 },{
4231 .name = "throttling.iops-total-max-length",
4232 .type = QEMU_OPT_NUMBER,
4233 .help = "length of the iops-total-max burst period, in seconds",
4234 },{
4235 .name = "throttling.iops-read-max-length",
4236 .type = QEMU_OPT_NUMBER,
4237 .help = "length of the iops-read-max burst period, in seconds",
4238 },{
4239 .name = "throttling.iops-write-max-length",
4240 .type = QEMU_OPT_NUMBER,
4241 .help = "length of the iops-write-max burst period, in seconds",
4242 },{
4243 .name = "throttling.bps-total-max-length",
4244 .type = QEMU_OPT_NUMBER,
4245 .help = "length of the bps-total-max burst period, in seconds",
4246 },{
4247 .name = "throttling.bps-read-max-length",
4248 .type = QEMU_OPT_NUMBER,
4249 .help = "length of the bps-read-max burst period, in seconds",
4250 },{
4251 .name = "throttling.bps-write-max-length",
4252 .type = QEMU_OPT_NUMBER,
4253 .help = "length of the bps-write-max burst period, in seconds",
2024c1df
BC
4254 },{
4255 .name = "throttling.iops-size",
4256 .type = QEMU_OPT_NUMBER,
4257 .help = "when limiting by iops max size of an I/O in bytes",
76f4afb4
AG
4258 },{
4259 .name = "throttling.group",
4260 .type = QEMU_OPT_STRING,
4261 .help = "name of the block throttling group",
4d454574
PB
4262 },{
4263 .name = "copy-on-read",
4264 .type = QEMU_OPT_BOOL,
4265 .help = "copy read data from backing file into image file",
465bee1d
PL
4266 },{
4267 .name = "detect-zeroes",
4268 .type = QEMU_OPT_STRING,
4269 .help = "try to optimize zero writes (off, on, unmap)",
362e9299
AG
4270 },{
4271 .name = "stats-account-invalid",
4272 .type = QEMU_OPT_BOOL,
4273 .help = "whether to account for invalid I/O operations "
4274 "in the statistics",
4275 },{
4276 .name = "stats-account-failed",
4277 .type = QEMU_OPT_BOOL,
4278 .help = "whether to account for failed I/O operations "
4279 "in the statistics",
4d454574
PB
4280 },
4281 { /* end of list */ }
4282 },
4283};
0006383e 4284
bd745e23
HR
4285static QemuOptsList qemu_root_bds_opts = {
4286 .name = "root-bds",
23f7fcb2 4287 .head = QTAILQ_HEAD_INITIALIZER(qemu_root_bds_opts.head),
bd745e23
HR
4288 .desc = {
4289 {
4290 .name = "discard",
4291 .type = QEMU_OPT_STRING,
4292 .help = "discard operation (ignore/off, unmap/on)",
bd745e23
HR
4293 },{
4294 .name = "aio",
4295 .type = QEMU_OPT_STRING,
4296 .help = "host AIO implementation (threads, native)",
4297 },{
4298 .name = "read-only",
4299 .type = QEMU_OPT_BOOL,
4300 .help = "open drive file as read-only",
4301 },{
4302 .name = "copy-on-read",
4303 .type = QEMU_OPT_BOOL,
4304 .help = "copy read data from backing file into image file",
4305 },{
4306 .name = "detect-zeroes",
4307 .type = QEMU_OPT_STRING,
4308 .help = "try to optimize zero writes (off, on, unmap)",
4309 },
4310 { /* end of list */ }
4311 },
4312};
4313
0006383e
KW
4314QemuOptsList qemu_drive_opts = {
4315 .name = "drive",
4316 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4317 .desc = {
492fdc6f
KW
4318 /*
4319 * no elements => accept any params
4320 * validation will happen later
4321 */
0006383e
KW
4322 { /* end of list */ }
4323 },
4324};