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