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