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