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