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