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