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