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