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