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