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