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