]> git.ipfire.org Git - thirdparty/qemu.git/blob - blockdev.c
blockdev: Allow external snapshots everywhere
[thirdparty/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 static QTAILQ_HEAD(, BlockDriverState) monitor_bdrv_states =
68 QTAILQ_HEAD_INITIALIZER(monitor_bdrv_states);
69
70 static int do_open_tray(const char *blk_name, const char *qdev_id,
71 bool force, Error **errp);
72 static void blockdev_remove_medium(bool has_device, const char *device,
73 bool has_id, const char *id, Error **errp);
74 static void blockdev_insert_medium(bool has_device, const char *device,
75 bool has_id, const char *id,
76 const char *node_name, Error **errp);
77
78 static const char *const if_name[IF_COUNT] = {
79 [IF_NONE] = "none",
80 [IF_IDE] = "ide",
81 [IF_SCSI] = "scsi",
82 [IF_FLOPPY] = "floppy",
83 [IF_PFLASH] = "pflash",
84 [IF_MTD] = "mtd",
85 [IF_SD] = "sd",
86 [IF_VIRTIO] = "virtio",
87 [IF_XEN] = "xen",
88 };
89
90 static int if_max_devs[IF_COUNT] = {
91 /*
92 * Do not change these numbers! They govern how drive option
93 * index maps to unit and bus. That mapping is ABI.
94 *
95 * All controllers used to implement if=T drives need to support
96 * if_max_devs[T] units, for any T with if_max_devs[T] != 0.
97 * Otherwise, some index values map to "impossible" bus, unit
98 * values.
99 *
100 * For instance, if you change [IF_SCSI] to 255, -drive
101 * if=scsi,index=12 no longer means bus=1,unit=5, but
102 * bus=0,unit=12. With an lsi53c895a controller (7 units max),
103 * the drive can't be set up. Regression.
104 */
105 [IF_IDE] = 2,
106 [IF_SCSI] = 7,
107 };
108
109 /**
110 * Boards may call this to offer board-by-board overrides
111 * of the default, global values.
112 */
113 void override_max_devs(BlockInterfaceType type, int max_devs)
114 {
115 BlockBackend *blk;
116 DriveInfo *dinfo;
117
118 if (max_devs <= 0) {
119 return;
120 }
121
122 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
123 dinfo = blk_legacy_dinfo(blk);
124 if (dinfo->type == type) {
125 fprintf(stderr, "Cannot override units-per-bus property of"
126 " the %s interface, because a drive of that type has"
127 " already been added.\n", if_name[type]);
128 g_assert_not_reached();
129 }
130 }
131
132 if_max_devs[type] = max_devs;
133 }
134
135 /*
136 * We automatically delete the drive when a device using it gets
137 * unplugged. Questionable feature, but we can't just drop it.
138 * Device models call blockdev_mark_auto_del() to schedule the
139 * automatic deletion, and generic qdev code calls blockdev_auto_del()
140 * when deletion is actually safe.
141 */
142 void blockdev_mark_auto_del(BlockBackend *blk)
143 {
144 DriveInfo *dinfo = blk_legacy_dinfo(blk);
145 BlockJob *job;
146
147 if (!dinfo) {
148 return;
149 }
150
151 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
152 if (block_job_has_bdrv(job, blk_bs(blk))) {
153 AioContext *aio_context = job->job.aio_context;
154 aio_context_acquire(aio_context);
155
156 job_cancel(&job->job, false);
157
158 aio_context_release(aio_context);
159 }
160 }
161
162 dinfo->auto_del = 1;
163 }
164
165 void blockdev_auto_del(BlockBackend *blk)
166 {
167 DriveInfo *dinfo = blk_legacy_dinfo(blk);
168
169 if (dinfo && dinfo->auto_del) {
170 monitor_remove_blk(blk);
171 blk_unref(blk);
172 }
173 }
174
175 /**
176 * Returns the current mapping of how many units per bus
177 * a particular interface can support.
178 *
179 * A positive integer indicates n units per bus.
180 * 0 implies the mapping has not been established.
181 * -1 indicates an invalid BlockInterfaceType was given.
182 */
183 int drive_get_max_devs(BlockInterfaceType type)
184 {
185 if (type >= IF_IDE && type < IF_COUNT) {
186 return if_max_devs[type];
187 }
188
189 return -1;
190 }
191
192 static int drive_index_to_bus_id(BlockInterfaceType type, int index)
193 {
194 int max_devs = if_max_devs[type];
195 return max_devs ? index / max_devs : 0;
196 }
197
198 static int drive_index_to_unit_id(BlockInterfaceType type, int index)
199 {
200 int max_devs = if_max_devs[type];
201 return max_devs ? index % max_devs : index;
202 }
203
204 QemuOpts *drive_def(const char *optstr)
205 {
206 return qemu_opts_parse_noisily(qemu_find_opts("drive"), optstr, false);
207 }
208
209 QemuOpts *drive_add(BlockInterfaceType type, int index, const char *file,
210 const char *optstr)
211 {
212 QemuOpts *opts;
213
214 opts = drive_def(optstr);
215 if (!opts) {
216 return NULL;
217 }
218 if (type != IF_DEFAULT) {
219 qemu_opt_set(opts, "if", if_name[type], &error_abort);
220 }
221 if (index >= 0) {
222 qemu_opt_set_number(opts, "index", index, &error_abort);
223 }
224 if (file)
225 qemu_opt_set(opts, "file", file, &error_abort);
226 return opts;
227 }
228
229 DriveInfo *drive_get(BlockInterfaceType type, int bus, int unit)
230 {
231 BlockBackend *blk;
232 DriveInfo *dinfo;
233
234 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
235 dinfo = blk_legacy_dinfo(blk);
236 if (dinfo && dinfo->type == type
237 && dinfo->bus == bus && dinfo->unit == unit) {
238 return dinfo;
239 }
240 }
241
242 return NULL;
243 }
244
245 void drive_check_orphaned(void)
246 {
247 BlockBackend *blk;
248 DriveInfo *dinfo;
249 Location loc;
250 bool orphans = false;
251
252 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
253 dinfo = blk_legacy_dinfo(blk);
254 if (!blk_get_attached_dev(blk) && !dinfo->is_default &&
255 dinfo->type != IF_NONE) {
256 loc_push_none(&loc);
257 qemu_opts_loc_restore(dinfo->opts);
258 error_report("machine type does not support"
259 " if=%s,bus=%d,unit=%d",
260 if_name[dinfo->type], dinfo->bus, dinfo->unit);
261 loc_pop(&loc);
262 orphans = true;
263 }
264 }
265
266 if (orphans) {
267 exit(1);
268 }
269 }
270
271 DriveInfo *drive_get_by_index(BlockInterfaceType type, int index)
272 {
273 return drive_get(type,
274 drive_index_to_bus_id(type, index),
275 drive_index_to_unit_id(type, index));
276 }
277
278 int drive_get_max_bus(BlockInterfaceType type)
279 {
280 int max_bus;
281 BlockBackend *blk;
282 DriveInfo *dinfo;
283
284 max_bus = -1;
285 for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
286 dinfo = blk_legacy_dinfo(blk);
287 if (dinfo && dinfo->type == type && dinfo->bus > max_bus) {
288 max_bus = dinfo->bus;
289 }
290 }
291 return max_bus;
292 }
293
294 /* Get a block device. This should only be used for single-drive devices
295 (e.g. SD/Floppy/MTD). Multi-disk devices (scsi/ide) should use the
296 appropriate bus. */
297 DriveInfo *drive_get_next(BlockInterfaceType type)
298 {
299 static int next_block_unit[IF_COUNT];
300
301 return drive_get(type, 0, next_block_unit[type]++);
302 }
303
304 static void bdrv_format_print(void *opaque, const char *name)
305 {
306 qemu_printf(" %s", name);
307 }
308
309 typedef struct {
310 QEMUBH *bh;
311 BlockDriverState *bs;
312 } BDRVPutRefBH;
313
314 static int parse_block_error_action(const char *buf, bool is_read, Error **errp)
315 {
316 if (!strcmp(buf, "ignore")) {
317 return BLOCKDEV_ON_ERROR_IGNORE;
318 } else if (!is_read && !strcmp(buf, "enospc")) {
319 return BLOCKDEV_ON_ERROR_ENOSPC;
320 } else if (!strcmp(buf, "stop")) {
321 return BLOCKDEV_ON_ERROR_STOP;
322 } else if (!strcmp(buf, "report")) {
323 return BLOCKDEV_ON_ERROR_REPORT;
324 } else {
325 error_setg(errp, "'%s' invalid %s error action",
326 buf, is_read ? "read" : "write");
327 return -1;
328 }
329 }
330
331 static bool parse_stats_intervals(BlockAcctStats *stats, QList *intervals,
332 Error **errp)
333 {
334 const QListEntry *entry;
335 for (entry = qlist_first(intervals); entry; entry = qlist_next(entry)) {
336 switch (qobject_type(entry->value)) {
337
338 case QTYPE_QSTRING: {
339 unsigned long long length;
340 const char *str = qstring_get_str(qobject_to(QString,
341 entry->value));
342 if (parse_uint_full(str, &length, 10) == 0 &&
343 length > 0 && length <= UINT_MAX) {
344 block_acct_add_interval(stats, (unsigned) length);
345 } else {
346 error_setg(errp, "Invalid interval length: %s", str);
347 return false;
348 }
349 break;
350 }
351
352 case QTYPE_QNUM: {
353 int64_t length = qnum_get_int(qobject_to(QNum, entry->value));
354
355 if (length > 0 && length <= UINT_MAX) {
356 block_acct_add_interval(stats, (unsigned) length);
357 } else {
358 error_setg(errp, "Invalid interval length: %" PRId64, length);
359 return false;
360 }
361 break;
362 }
363
364 default:
365 error_setg(errp, "The specification of stats-intervals is invalid");
366 return false;
367 }
368 }
369 return true;
370 }
371
372 typedef enum { MEDIA_DISK, MEDIA_CDROM } DriveMediaType;
373
374 /* All parameters but @opts are optional and may be set to NULL. */
375 static void extract_common_blockdev_options(QemuOpts *opts, int *bdrv_flags,
376 const char **throttling_group, ThrottleConfig *throttle_cfg,
377 BlockdevDetectZeroesOptions *detect_zeroes, Error **errp)
378 {
379 Error *local_error = NULL;
380 const char *aio;
381
382 if (bdrv_flags) {
383 if (qemu_opt_get_bool(opts, "copy-on-read", false)) {
384 *bdrv_flags |= BDRV_O_COPY_ON_READ;
385 }
386
387 if ((aio = qemu_opt_get(opts, "aio")) != NULL) {
388 if (bdrv_parse_aio(aio, bdrv_flags) < 0) {
389 error_setg(errp, "invalid aio option");
390 return;
391 }
392 }
393 }
394
395 /* disk I/O throttling */
396 if (throttling_group) {
397 *throttling_group = qemu_opt_get(opts, "throttling.group");
398 }
399
400 if (throttle_cfg) {
401 throttle_config_init(throttle_cfg);
402 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].avg =
403 qemu_opt_get_number(opts, "throttling.bps-total", 0);
404 throttle_cfg->buckets[THROTTLE_BPS_READ].avg =
405 qemu_opt_get_number(opts, "throttling.bps-read", 0);
406 throttle_cfg->buckets[THROTTLE_BPS_WRITE].avg =
407 qemu_opt_get_number(opts, "throttling.bps-write", 0);
408 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].avg =
409 qemu_opt_get_number(opts, "throttling.iops-total", 0);
410 throttle_cfg->buckets[THROTTLE_OPS_READ].avg =
411 qemu_opt_get_number(opts, "throttling.iops-read", 0);
412 throttle_cfg->buckets[THROTTLE_OPS_WRITE].avg =
413 qemu_opt_get_number(opts, "throttling.iops-write", 0);
414
415 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].max =
416 qemu_opt_get_number(opts, "throttling.bps-total-max", 0);
417 throttle_cfg->buckets[THROTTLE_BPS_READ].max =
418 qemu_opt_get_number(opts, "throttling.bps-read-max", 0);
419 throttle_cfg->buckets[THROTTLE_BPS_WRITE].max =
420 qemu_opt_get_number(opts, "throttling.bps-write-max", 0);
421 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].max =
422 qemu_opt_get_number(opts, "throttling.iops-total-max", 0);
423 throttle_cfg->buckets[THROTTLE_OPS_READ].max =
424 qemu_opt_get_number(opts, "throttling.iops-read-max", 0);
425 throttle_cfg->buckets[THROTTLE_OPS_WRITE].max =
426 qemu_opt_get_number(opts, "throttling.iops-write-max", 0);
427
428 throttle_cfg->buckets[THROTTLE_BPS_TOTAL].burst_length =
429 qemu_opt_get_number(opts, "throttling.bps-total-max-length", 1);
430 throttle_cfg->buckets[THROTTLE_BPS_READ].burst_length =
431 qemu_opt_get_number(opts, "throttling.bps-read-max-length", 1);
432 throttle_cfg->buckets[THROTTLE_BPS_WRITE].burst_length =
433 qemu_opt_get_number(opts, "throttling.bps-write-max-length", 1);
434 throttle_cfg->buckets[THROTTLE_OPS_TOTAL].burst_length =
435 qemu_opt_get_number(opts, "throttling.iops-total-max-length", 1);
436 throttle_cfg->buckets[THROTTLE_OPS_READ].burst_length =
437 qemu_opt_get_number(opts, "throttling.iops-read-max-length", 1);
438 throttle_cfg->buckets[THROTTLE_OPS_WRITE].burst_length =
439 qemu_opt_get_number(opts, "throttling.iops-write-max-length", 1);
440
441 throttle_cfg->op_size =
442 qemu_opt_get_number(opts, "throttling.iops-size", 0);
443
444 if (!throttle_is_valid(throttle_cfg, errp)) {
445 return;
446 }
447 }
448
449 if (detect_zeroes) {
450 *detect_zeroes =
451 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
452 qemu_opt_get(opts, "detect-zeroes"),
453 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
454 &local_error);
455 if (local_error) {
456 error_propagate(errp, local_error);
457 return;
458 }
459 }
460 }
461
462 /* Takes the ownership of bs_opts */
463 static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
464 Error **errp)
465 {
466 const char *buf;
467 int bdrv_flags = 0;
468 int on_read_error, on_write_error;
469 bool account_invalid, account_failed;
470 bool writethrough, read_only;
471 BlockBackend *blk;
472 BlockDriverState *bs;
473 ThrottleConfig cfg;
474 int snapshot = 0;
475 Error *error = NULL;
476 QemuOpts *opts;
477 QDict *interval_dict = NULL;
478 QList *interval_list = NULL;
479 const char *id;
480 BlockdevDetectZeroesOptions detect_zeroes =
481 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
482 const char *throttling_group = NULL;
483
484 /* Check common options by copying from bs_opts to opts, all other options
485 * stay in bs_opts for processing by bdrv_open(). */
486 id = qdict_get_try_str(bs_opts, "id");
487 opts = qemu_opts_create(&qemu_common_drive_opts, id, 1, &error);
488 if (error) {
489 error_propagate(errp, error);
490 goto err_no_opts;
491 }
492
493 qemu_opts_absorb_qdict(opts, bs_opts, &error);
494 if (error) {
495 error_propagate(errp, error);
496 goto early_err;
497 }
498
499 if (id) {
500 qdict_del(bs_opts, "id");
501 }
502
503 /* extract parameters */
504 snapshot = qemu_opt_get_bool(opts, "snapshot", 0);
505
506 account_invalid = qemu_opt_get_bool(opts, "stats-account-invalid", true);
507 account_failed = qemu_opt_get_bool(opts, "stats-account-failed", true);
508
509 writethrough = !qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, true);
510
511 id = qemu_opts_id(opts);
512
513 qdict_extract_subqdict(bs_opts, &interval_dict, "stats-intervals.");
514 qdict_array_split(interval_dict, &interval_list);
515
516 if (qdict_size(interval_dict) != 0) {
517 error_setg(errp, "Invalid option stats-intervals.%s",
518 qdict_first(interval_dict)->key);
519 goto early_err;
520 }
521
522 extract_common_blockdev_options(opts, &bdrv_flags, &throttling_group, &cfg,
523 &detect_zeroes, &error);
524 if (error) {
525 error_propagate(errp, error);
526 goto early_err;
527 }
528
529 if ((buf = qemu_opt_get(opts, "format")) != NULL) {
530 if (is_help_option(buf)) {
531 qemu_printf("Supported formats:");
532 bdrv_iterate_format(bdrv_format_print, NULL, false);
533 qemu_printf("\nSupported formats (read-only):");
534 bdrv_iterate_format(bdrv_format_print, NULL, true);
535 qemu_printf("\n");
536 goto early_err;
537 }
538
539 if (qdict_haskey(bs_opts, "driver")) {
540 error_setg(errp, "Cannot specify both 'driver' and 'format'");
541 goto early_err;
542 }
543 qdict_put_str(bs_opts, "driver", buf);
544 }
545
546 on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
547 if ((buf = qemu_opt_get(opts, "werror")) != NULL) {
548 on_write_error = parse_block_error_action(buf, 0, &error);
549 if (error) {
550 error_propagate(errp, error);
551 goto early_err;
552 }
553 }
554
555 on_read_error = BLOCKDEV_ON_ERROR_REPORT;
556 if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {
557 on_read_error = parse_block_error_action(buf, 1, &error);
558 if (error) {
559 error_propagate(errp, error);
560 goto early_err;
561 }
562 }
563
564 if (snapshot) {
565 bdrv_flags |= BDRV_O_SNAPSHOT;
566 }
567
568 read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
569
570 /* init */
571 if ((!file || !*file) && !qdict_size(bs_opts)) {
572 BlockBackendRootState *blk_rs;
573
574 blk = blk_new(qemu_get_aio_context(), 0, BLK_PERM_ALL);
575 blk_rs = blk_get_root_state(blk);
576 blk_rs->open_flags = bdrv_flags;
577 blk_rs->read_only = read_only;
578 blk_rs->detect_zeroes = detect_zeroes;
579
580 qobject_unref(bs_opts);
581 } else {
582 if (file && !*file) {
583 file = NULL;
584 }
585
586 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
587 * with other callers) rather than what we want as the real defaults.
588 * Apply the defaults here instead. */
589 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
590 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
591 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY,
592 read_only ? "on" : "off");
593 qdict_set_default_str(bs_opts, BDRV_OPT_AUTO_READ_ONLY, "on");
594 assert((bdrv_flags & BDRV_O_CACHE_MASK) == 0);
595
596 if (runstate_check(RUN_STATE_INMIGRATE)) {
597 bdrv_flags |= BDRV_O_INACTIVE;
598 }
599
600 blk = blk_new_open(file, NULL, bs_opts, bdrv_flags, errp);
601 if (!blk) {
602 goto err_no_bs_opts;
603 }
604 bs = blk_bs(blk);
605
606 bs->detect_zeroes = detect_zeroes;
607
608 block_acct_setup(blk_get_stats(blk), account_invalid, account_failed);
609
610 if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
611 blk_unref(blk);
612 blk = NULL;
613 goto err_no_bs_opts;
614 }
615 }
616
617 /* disk I/O throttling */
618 if (throttle_enabled(&cfg)) {
619 if (!throttling_group) {
620 throttling_group = id;
621 }
622 blk_io_limits_enable(blk, throttling_group);
623 blk_set_io_limits(blk, &cfg);
624 }
625
626 blk_set_enable_write_cache(blk, !writethrough);
627 blk_set_on_error(blk, on_read_error, on_write_error);
628
629 if (!monitor_add_blk(blk, id, errp)) {
630 blk_unref(blk);
631 blk = NULL;
632 goto err_no_bs_opts;
633 }
634
635 err_no_bs_opts:
636 qemu_opts_del(opts);
637 qobject_unref(interval_dict);
638 qobject_unref(interval_list);
639 return blk;
640
641 early_err:
642 qemu_opts_del(opts);
643 qobject_unref(interval_dict);
644 qobject_unref(interval_list);
645 err_no_opts:
646 qobject_unref(bs_opts);
647 return NULL;
648 }
649
650 /* Takes the ownership of bs_opts */
651 static BlockDriverState *bds_tree_init(QDict *bs_opts, Error **errp)
652 {
653 int bdrv_flags = 0;
654
655 /* bdrv_open() defaults to the values in bdrv_flags (for compatibility
656 * with other callers) rather than what we want as the real defaults.
657 * Apply the defaults here instead. */
658 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_DIRECT, "off");
659 qdict_set_default_str(bs_opts, BDRV_OPT_CACHE_NO_FLUSH, "off");
660 qdict_set_default_str(bs_opts, BDRV_OPT_READ_ONLY, "off");
661
662 if (runstate_check(RUN_STATE_INMIGRATE)) {
663 bdrv_flags |= BDRV_O_INACTIVE;
664 }
665
666 return bdrv_open(NULL, NULL, bs_opts, bdrv_flags, errp);
667 }
668
669 void blockdev_close_all_bdrv_states(void)
670 {
671 BlockDriverState *bs, *next_bs;
672
673 QTAILQ_FOREACH_SAFE(bs, &monitor_bdrv_states, monitor_list, next_bs) {
674 AioContext *ctx = bdrv_get_aio_context(bs);
675
676 aio_context_acquire(ctx);
677 bdrv_unref(bs);
678 aio_context_release(ctx);
679 }
680 }
681
682 /* Iterates over the list of monitor-owned BlockDriverStates */
683 BlockDriverState *bdrv_next_monitor_owned(BlockDriverState *bs)
684 {
685 return bs ? QTAILQ_NEXT(bs, monitor_list)
686 : QTAILQ_FIRST(&monitor_bdrv_states);
687 }
688
689 static void qemu_opt_rename(QemuOpts *opts, const char *from, const char *to,
690 Error **errp)
691 {
692 const char *value;
693
694 value = qemu_opt_get(opts, from);
695 if (value) {
696 if (qemu_opt_find(opts, to)) {
697 error_setg(errp, "'%s' and its alias '%s' can't be used at the "
698 "same time", to, from);
699 return;
700 }
701 }
702
703 /* rename all items in opts */
704 while ((value = qemu_opt_get(opts, from))) {
705 qemu_opt_set(opts, to, value, &error_abort);
706 qemu_opt_unset(opts, from);
707 }
708 }
709
710 QemuOptsList qemu_legacy_drive_opts = {
711 .name = "drive",
712 .head = QTAILQ_HEAD_INITIALIZER(qemu_legacy_drive_opts.head),
713 .desc = {
714 {
715 .name = "bus",
716 .type = QEMU_OPT_NUMBER,
717 .help = "bus number",
718 },{
719 .name = "unit",
720 .type = QEMU_OPT_NUMBER,
721 .help = "unit number (i.e. lun for scsi)",
722 },{
723 .name = "index",
724 .type = QEMU_OPT_NUMBER,
725 .help = "index number",
726 },{
727 .name = "media",
728 .type = QEMU_OPT_STRING,
729 .help = "media type (disk, cdrom)",
730 },{
731 .name = "if",
732 .type = QEMU_OPT_STRING,
733 .help = "interface (ide, scsi, sd, mtd, floppy, pflash, virtio)",
734 },{
735 .name = "file",
736 .type = QEMU_OPT_STRING,
737 .help = "file name",
738 },
739
740 /* Options that are passed on, but have special semantics with -drive */
741 {
742 .name = BDRV_OPT_READ_ONLY,
743 .type = QEMU_OPT_BOOL,
744 .help = "open drive file as read-only",
745 },{
746 .name = "rerror",
747 .type = QEMU_OPT_STRING,
748 .help = "read error action",
749 },{
750 .name = "werror",
751 .type = QEMU_OPT_STRING,
752 .help = "write error action",
753 },{
754 .name = "copy-on-read",
755 .type = QEMU_OPT_BOOL,
756 .help = "copy read data from backing file into image file",
757 },
758
759 { /* end of list */ }
760 },
761 };
762
763 DriveInfo *drive_new(QemuOpts *all_opts, BlockInterfaceType block_default_type,
764 Error **errp)
765 {
766 const char *value;
767 BlockBackend *blk;
768 DriveInfo *dinfo = NULL;
769 QDict *bs_opts;
770 QemuOpts *legacy_opts;
771 DriveMediaType media = MEDIA_DISK;
772 BlockInterfaceType type;
773 int max_devs, bus_id, unit_id, index;
774 const char *werror, *rerror;
775 bool read_only = false;
776 bool copy_on_read;
777 const char *filename;
778 Error *local_err = NULL;
779 int i;
780
781 /* Change legacy command line options into QMP ones */
782 static const struct {
783 const char *from;
784 const char *to;
785 } opt_renames[] = {
786 { "iops", "throttling.iops-total" },
787 { "iops_rd", "throttling.iops-read" },
788 { "iops_wr", "throttling.iops-write" },
789
790 { "bps", "throttling.bps-total" },
791 { "bps_rd", "throttling.bps-read" },
792 { "bps_wr", "throttling.bps-write" },
793
794 { "iops_max", "throttling.iops-total-max" },
795 { "iops_rd_max", "throttling.iops-read-max" },
796 { "iops_wr_max", "throttling.iops-write-max" },
797
798 { "bps_max", "throttling.bps-total-max" },
799 { "bps_rd_max", "throttling.bps-read-max" },
800 { "bps_wr_max", "throttling.bps-write-max" },
801
802 { "iops_size", "throttling.iops-size" },
803
804 { "group", "throttling.group" },
805
806 { "readonly", BDRV_OPT_READ_ONLY },
807 };
808
809 for (i = 0; i < ARRAY_SIZE(opt_renames); i++) {
810 qemu_opt_rename(all_opts, opt_renames[i].from, opt_renames[i].to,
811 &local_err);
812 if (local_err) {
813 error_propagate(errp, local_err);
814 return NULL;
815 }
816 }
817
818 value = qemu_opt_get(all_opts, "cache");
819 if (value) {
820 int flags = 0;
821 bool writethrough;
822
823 if (bdrv_parse_cache_mode(value, &flags, &writethrough) != 0) {
824 error_setg(errp, "invalid cache option");
825 return NULL;
826 }
827
828 /* Specific options take precedence */
829 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_WB)) {
830 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_WB,
831 !writethrough, &error_abort);
832 }
833 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_DIRECT)) {
834 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_DIRECT,
835 !!(flags & BDRV_O_NOCACHE), &error_abort);
836 }
837 if (!qemu_opt_get(all_opts, BDRV_OPT_CACHE_NO_FLUSH)) {
838 qemu_opt_set_bool(all_opts, BDRV_OPT_CACHE_NO_FLUSH,
839 !!(flags & BDRV_O_NO_FLUSH), &error_abort);
840 }
841 qemu_opt_unset(all_opts, "cache");
842 }
843
844 /* Get a QDict for processing the options */
845 bs_opts = qdict_new();
846 qemu_opts_to_qdict(all_opts, bs_opts);
847
848 legacy_opts = qemu_opts_create(&qemu_legacy_drive_opts, NULL, 0,
849 &error_abort);
850 qemu_opts_absorb_qdict(legacy_opts, bs_opts, &local_err);
851 if (local_err) {
852 error_propagate(errp, local_err);
853 goto fail;
854 }
855
856 /* Media type */
857 value = qemu_opt_get(legacy_opts, "media");
858 if (value) {
859 if (!strcmp(value, "disk")) {
860 media = MEDIA_DISK;
861 } else if (!strcmp(value, "cdrom")) {
862 media = MEDIA_CDROM;
863 read_only = true;
864 } else {
865 error_setg(errp, "'%s' invalid media", value);
866 goto fail;
867 }
868 }
869
870 /* copy-on-read is disabled with a warning for read-only devices */
871 read_only |= qemu_opt_get_bool(legacy_opts, BDRV_OPT_READ_ONLY, false);
872 copy_on_read = qemu_opt_get_bool(legacy_opts, "copy-on-read", false);
873
874 if (read_only && copy_on_read) {
875 warn_report("disabling copy-on-read on read-only drive");
876 copy_on_read = false;
877 }
878
879 qdict_put_str(bs_opts, BDRV_OPT_READ_ONLY, read_only ? "on" : "off");
880 qdict_put_str(bs_opts, "copy-on-read", copy_on_read ? "on" : "off");
881
882 /* Controller type */
883 value = qemu_opt_get(legacy_opts, "if");
884 if (value) {
885 for (type = 0;
886 type < IF_COUNT && strcmp(value, if_name[type]);
887 type++) {
888 }
889 if (type == IF_COUNT) {
890 error_setg(errp, "unsupported bus type '%s'", value);
891 goto fail;
892 }
893 } else {
894 type = block_default_type;
895 }
896
897 /* Device address specified by bus/unit or index.
898 * If none was specified, try to find the first free one. */
899 bus_id = qemu_opt_get_number(legacy_opts, "bus", 0);
900 unit_id = qemu_opt_get_number(legacy_opts, "unit", -1);
901 index = qemu_opt_get_number(legacy_opts, "index", -1);
902
903 max_devs = if_max_devs[type];
904
905 if (index != -1) {
906 if (bus_id != 0 || unit_id != -1) {
907 error_setg(errp, "index cannot be used with bus and unit");
908 goto fail;
909 }
910 bus_id = drive_index_to_bus_id(type, index);
911 unit_id = drive_index_to_unit_id(type, index);
912 }
913
914 if (unit_id == -1) {
915 unit_id = 0;
916 while (drive_get(type, bus_id, unit_id) != NULL) {
917 unit_id++;
918 if (max_devs && unit_id >= max_devs) {
919 unit_id -= max_devs;
920 bus_id++;
921 }
922 }
923 }
924
925 if (max_devs && unit_id >= max_devs) {
926 error_setg(errp, "unit %d too big (max is %d)", unit_id, max_devs - 1);
927 goto fail;
928 }
929
930 if (drive_get(type, bus_id, unit_id) != NULL) {
931 error_setg(errp, "drive with bus=%d, unit=%d (index=%d) exists",
932 bus_id, unit_id, index);
933 goto fail;
934 }
935
936 /* no id supplied -> create one */
937 if (qemu_opts_id(all_opts) == NULL) {
938 char *new_id;
939 const char *mediastr = "";
940 if (type == IF_IDE || type == IF_SCSI) {
941 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
942 }
943 if (max_devs) {
944 new_id = g_strdup_printf("%s%i%s%i", if_name[type], bus_id,
945 mediastr, unit_id);
946 } else {
947 new_id = g_strdup_printf("%s%s%i", if_name[type],
948 mediastr, unit_id);
949 }
950 qdict_put_str(bs_opts, "id", new_id);
951 g_free(new_id);
952 }
953
954 /* Add virtio block device */
955 if (type == IF_VIRTIO) {
956 QemuOpts *devopts;
957 devopts = qemu_opts_create(qemu_find_opts("device"), NULL, 0,
958 &error_abort);
959 if (arch_type == QEMU_ARCH_S390X) {
960 qemu_opt_set(devopts, "driver", "virtio-blk-ccw", &error_abort);
961 } else {
962 qemu_opt_set(devopts, "driver", "virtio-blk-pci", &error_abort);
963 }
964 qemu_opt_set(devopts, "drive", qdict_get_str(bs_opts, "id"),
965 &error_abort);
966 }
967
968 filename = qemu_opt_get(legacy_opts, "file");
969
970 /* Check werror/rerror compatibility with if=... */
971 werror = qemu_opt_get(legacy_opts, "werror");
972 if (werror != NULL) {
973 if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO &&
974 type != IF_NONE) {
975 error_setg(errp, "werror is not supported by this bus type");
976 goto fail;
977 }
978 qdict_put_str(bs_opts, "werror", werror);
979 }
980
981 rerror = qemu_opt_get(legacy_opts, "rerror");
982 if (rerror != NULL) {
983 if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI &&
984 type != IF_NONE) {
985 error_setg(errp, "rerror is not supported by this bus type");
986 goto fail;
987 }
988 qdict_put_str(bs_opts, "rerror", rerror);
989 }
990
991 /* Actual block device init: Functionality shared with blockdev-add */
992 blk = blockdev_init(filename, bs_opts, &local_err);
993 bs_opts = NULL;
994 if (!blk) {
995 error_propagate(errp, local_err);
996 goto fail;
997 } else {
998 assert(!local_err);
999 }
1000
1001 /* Create legacy DriveInfo */
1002 dinfo = g_malloc0(sizeof(*dinfo));
1003 dinfo->opts = all_opts;
1004
1005 dinfo->type = type;
1006 dinfo->bus = bus_id;
1007 dinfo->unit = unit_id;
1008
1009 blk_set_legacy_dinfo(blk, dinfo);
1010
1011 switch(type) {
1012 case IF_IDE:
1013 case IF_SCSI:
1014 case IF_XEN:
1015 case IF_NONE:
1016 dinfo->media_cd = media == MEDIA_CDROM;
1017 break;
1018 default:
1019 break;
1020 }
1021
1022 fail:
1023 qemu_opts_del(legacy_opts);
1024 qobject_unref(bs_opts);
1025 return dinfo;
1026 }
1027
1028 static BlockDriverState *qmp_get_root_bs(const char *name, Error **errp)
1029 {
1030 BlockDriverState *bs;
1031
1032 bs = bdrv_lookup_bs(name, name, errp);
1033 if (bs == NULL) {
1034 return NULL;
1035 }
1036
1037 if (!bdrv_is_root_node(bs)) {
1038 error_setg(errp, "Need a root block node");
1039 return NULL;
1040 }
1041
1042 if (!bdrv_is_inserted(bs)) {
1043 error_setg(errp, "Device has no medium");
1044 return NULL;
1045 }
1046
1047 return bs;
1048 }
1049
1050 static BlockBackend *qmp_get_blk(const char *blk_name, const char *qdev_id,
1051 Error **errp)
1052 {
1053 BlockBackend *blk;
1054
1055 if (!blk_name == !qdev_id) {
1056 error_setg(errp, "Need exactly one of 'device' and 'id'");
1057 return NULL;
1058 }
1059
1060 if (qdev_id) {
1061 blk = blk_by_qdev_id(qdev_id, errp);
1062 } else {
1063 blk = blk_by_name(blk_name);
1064 if (blk == NULL) {
1065 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1066 "Device '%s' not found", blk_name);
1067 }
1068 }
1069
1070 return blk;
1071 }
1072
1073 void hmp_commit(Monitor *mon, const QDict *qdict)
1074 {
1075 const char *device = qdict_get_str(qdict, "device");
1076 BlockBackend *blk;
1077 int ret;
1078
1079 if (!strcmp(device, "all")) {
1080 ret = blk_commit_all();
1081 } else {
1082 BlockDriverState *bs;
1083 AioContext *aio_context;
1084
1085 blk = blk_by_name(device);
1086 if (!blk) {
1087 error_report("Device '%s' not found", device);
1088 return;
1089 }
1090 if (!blk_is_available(blk)) {
1091 error_report("Device '%s' has no medium", device);
1092 return;
1093 }
1094
1095 bs = blk_bs(blk);
1096 aio_context = bdrv_get_aio_context(bs);
1097 aio_context_acquire(aio_context);
1098
1099 ret = bdrv_commit(bs);
1100
1101 aio_context_release(aio_context);
1102 }
1103 if (ret < 0) {
1104 error_report("'commit' error for '%s': %s", device, strerror(-ret));
1105 }
1106 }
1107
1108 static void blockdev_do_action(TransactionAction *action, Error **errp)
1109 {
1110 TransactionActionList list;
1111
1112 list.value = action;
1113 list.next = NULL;
1114 qmp_transaction(&list, false, NULL, errp);
1115 }
1116
1117 void qmp_blockdev_snapshot_sync(bool has_device, const char *device,
1118 bool has_node_name, const char *node_name,
1119 const char *snapshot_file,
1120 bool has_snapshot_node_name,
1121 const char *snapshot_node_name,
1122 bool has_format, const char *format,
1123 bool has_mode, NewImageMode mode, Error **errp)
1124 {
1125 BlockdevSnapshotSync snapshot = {
1126 .has_device = has_device,
1127 .device = (char *) device,
1128 .has_node_name = has_node_name,
1129 .node_name = (char *) node_name,
1130 .snapshot_file = (char *) snapshot_file,
1131 .has_snapshot_node_name = has_snapshot_node_name,
1132 .snapshot_node_name = (char *) snapshot_node_name,
1133 .has_format = has_format,
1134 .format = (char *) format,
1135 .has_mode = has_mode,
1136 .mode = mode,
1137 };
1138 TransactionAction action = {
1139 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC,
1140 .u.blockdev_snapshot_sync.data = &snapshot,
1141 };
1142 blockdev_do_action(&action, errp);
1143 }
1144
1145 void qmp_blockdev_snapshot(const char *node, const char *overlay,
1146 Error **errp)
1147 {
1148 BlockdevSnapshot snapshot_data = {
1149 .node = (char *) node,
1150 .overlay = (char *) overlay
1151 };
1152 TransactionAction action = {
1153 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT,
1154 .u.blockdev_snapshot.data = &snapshot_data,
1155 };
1156 blockdev_do_action(&action, errp);
1157 }
1158
1159 void qmp_blockdev_snapshot_internal_sync(const char *device,
1160 const char *name,
1161 Error **errp)
1162 {
1163 BlockdevSnapshotInternal snapshot = {
1164 .device = (char *) device,
1165 .name = (char *) name
1166 };
1167 TransactionAction action = {
1168 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC,
1169 .u.blockdev_snapshot_internal_sync.data = &snapshot,
1170 };
1171 blockdev_do_action(&action, errp);
1172 }
1173
1174 SnapshotInfo *qmp_blockdev_snapshot_delete_internal_sync(const char *device,
1175 bool has_id,
1176 const char *id,
1177 bool has_name,
1178 const char *name,
1179 Error **errp)
1180 {
1181 BlockDriverState *bs;
1182 AioContext *aio_context;
1183 QEMUSnapshotInfo sn;
1184 Error *local_err = NULL;
1185 SnapshotInfo *info = NULL;
1186 int ret;
1187
1188 bs = qmp_get_root_bs(device, errp);
1189 if (!bs) {
1190 return NULL;
1191 }
1192 aio_context = bdrv_get_aio_context(bs);
1193 aio_context_acquire(aio_context);
1194
1195 if (!has_id) {
1196 id = NULL;
1197 }
1198
1199 if (!has_name) {
1200 name = NULL;
1201 }
1202
1203 if (!id && !name) {
1204 error_setg(errp, "Name or id must be provided");
1205 goto out_aio_context;
1206 }
1207
1208 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE, errp)) {
1209 goto out_aio_context;
1210 }
1211
1212 ret = bdrv_snapshot_find_by_id_and_name(bs, id, name, &sn, &local_err);
1213 if (local_err) {
1214 error_propagate(errp, local_err);
1215 goto out_aio_context;
1216 }
1217 if (!ret) {
1218 error_setg(errp,
1219 "Snapshot with id '%s' and name '%s' does not exist on "
1220 "device '%s'",
1221 STR_OR_NULL(id), STR_OR_NULL(name), device);
1222 goto out_aio_context;
1223 }
1224
1225 bdrv_snapshot_delete(bs, id, name, &local_err);
1226 if (local_err) {
1227 error_propagate(errp, local_err);
1228 goto out_aio_context;
1229 }
1230
1231 aio_context_release(aio_context);
1232
1233 info = g_new0(SnapshotInfo, 1);
1234 info->id = g_strdup(sn.id_str);
1235 info->name = g_strdup(sn.name);
1236 info->date_nsec = sn.date_nsec;
1237 info->date_sec = sn.date_sec;
1238 info->vm_state_size = sn.vm_state_size;
1239 info->vm_clock_nsec = sn.vm_clock_nsec % 1000000000;
1240 info->vm_clock_sec = sn.vm_clock_nsec / 1000000000;
1241
1242 return info;
1243
1244 out_aio_context:
1245 aio_context_release(aio_context);
1246 return NULL;
1247 }
1248
1249 /**
1250 * block_dirty_bitmap_lookup:
1251 * Return a dirty bitmap (if present), after validating
1252 * the node reference and bitmap names.
1253 *
1254 * @node: The name of the BDS node to search for bitmaps
1255 * @name: The name of the bitmap to search for
1256 * @pbs: Output pointer for BDS lookup, if desired. Can be NULL.
1257 * @errp: Output pointer for error information. Can be NULL.
1258 *
1259 * @return: A bitmap object on success, or NULL on failure.
1260 */
1261 static BdrvDirtyBitmap *block_dirty_bitmap_lookup(const char *node,
1262 const char *name,
1263 BlockDriverState **pbs,
1264 Error **errp)
1265 {
1266 BlockDriverState *bs;
1267 BdrvDirtyBitmap *bitmap;
1268
1269 if (!node) {
1270 error_setg(errp, "Node cannot be NULL");
1271 return NULL;
1272 }
1273 if (!name) {
1274 error_setg(errp, "Bitmap name cannot be NULL");
1275 return NULL;
1276 }
1277 bs = bdrv_lookup_bs(node, node, NULL);
1278 if (!bs) {
1279 error_setg(errp, "Node '%s' not found", node);
1280 return NULL;
1281 }
1282
1283 bitmap = bdrv_find_dirty_bitmap(bs, name);
1284 if (!bitmap) {
1285 error_setg(errp, "Dirty bitmap '%s' not found", name);
1286 return NULL;
1287 }
1288
1289 if (pbs) {
1290 *pbs = bs;
1291 }
1292
1293 return bitmap;
1294 }
1295
1296 /* New and old BlockDriverState structs for atomic group operations */
1297
1298 typedef struct BlkActionState BlkActionState;
1299
1300 /**
1301 * BlkActionOps:
1302 * Table of operations that define an Action.
1303 *
1304 * @instance_size: Size of state struct, in bytes.
1305 * @prepare: Prepare the work, must NOT be NULL.
1306 * @commit: Commit the changes, can be NULL.
1307 * @abort: Abort the changes on fail, can be NULL.
1308 * @clean: Clean up resources after all transaction actions have called
1309 * commit() or abort(). Can be NULL.
1310 *
1311 * Only prepare() may fail. In a single transaction, only one of commit() or
1312 * abort() will be called. clean() will always be called if it is present.
1313 */
1314 typedef struct BlkActionOps {
1315 size_t instance_size;
1316 void (*prepare)(BlkActionState *common, Error **errp);
1317 void (*commit)(BlkActionState *common);
1318 void (*abort)(BlkActionState *common);
1319 void (*clean)(BlkActionState *common);
1320 } BlkActionOps;
1321
1322 /**
1323 * BlkActionState:
1324 * Describes one Action's state within a Transaction.
1325 *
1326 * @action: QAPI-defined enum identifying which Action to perform.
1327 * @ops: Table of ActionOps this Action can perform.
1328 * @block_job_txn: Transaction which this action belongs to.
1329 * @entry: List membership for all Actions in this Transaction.
1330 *
1331 * This structure must be arranged as first member in a subclassed type,
1332 * assuming that the compiler will also arrange it to the same offsets as the
1333 * base class.
1334 */
1335 struct BlkActionState {
1336 TransactionAction *action;
1337 const BlkActionOps *ops;
1338 JobTxn *block_job_txn;
1339 TransactionProperties *txn_props;
1340 QTAILQ_ENTRY(BlkActionState) entry;
1341 };
1342
1343 /* internal snapshot private data */
1344 typedef struct InternalSnapshotState {
1345 BlkActionState common;
1346 BlockDriverState *bs;
1347 QEMUSnapshotInfo sn;
1348 bool created;
1349 } InternalSnapshotState;
1350
1351
1352 static int action_check_completion_mode(BlkActionState *s, Error **errp)
1353 {
1354 if (s->txn_props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
1355 error_setg(errp,
1356 "Action '%s' does not support Transaction property "
1357 "completion-mode = %s",
1358 TransactionActionKind_str(s->action->type),
1359 ActionCompletionMode_str(s->txn_props->completion_mode));
1360 return -1;
1361 }
1362 return 0;
1363 }
1364
1365 static void internal_snapshot_prepare(BlkActionState *common,
1366 Error **errp)
1367 {
1368 Error *local_err = NULL;
1369 const char *device;
1370 const char *name;
1371 BlockDriverState *bs;
1372 QEMUSnapshotInfo old_sn, *sn;
1373 bool ret;
1374 qemu_timeval tv;
1375 BlockdevSnapshotInternal *internal;
1376 InternalSnapshotState *state;
1377 AioContext *aio_context;
1378 int ret1;
1379
1380 g_assert(common->action->type ==
1381 TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);
1382 internal = common->action->u.blockdev_snapshot_internal_sync.data;
1383 state = DO_UPCAST(InternalSnapshotState, common, common);
1384
1385 /* 1. parse input */
1386 device = internal->device;
1387 name = internal->name;
1388
1389 /* 2. check for validation */
1390 if (action_check_completion_mode(common, errp) < 0) {
1391 return;
1392 }
1393
1394 bs = qmp_get_root_bs(device, errp);
1395 if (!bs) {
1396 return;
1397 }
1398
1399 aio_context = bdrv_get_aio_context(bs);
1400 aio_context_acquire(aio_context);
1401
1402 state->bs = bs;
1403
1404 /* Paired with .clean() */
1405 bdrv_drained_begin(bs);
1406
1407 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {
1408 goto out;
1409 }
1410
1411 if (bdrv_is_read_only(bs)) {
1412 error_setg(errp, "Device '%s' is read only", device);
1413 goto out;
1414 }
1415
1416 if (!bdrv_can_snapshot(bs)) {
1417 error_setg(errp, "Block format '%s' used by device '%s' "
1418 "does not support internal snapshots",
1419 bs->drv->format_name, device);
1420 goto out;
1421 }
1422
1423 if (!strlen(name)) {
1424 error_setg(errp, "Name is empty");
1425 goto out;
1426 }
1427
1428 /* check whether a snapshot with name exist */
1429 ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,
1430 &local_err);
1431 if (local_err) {
1432 error_propagate(errp, local_err);
1433 goto out;
1434 } else if (ret) {
1435 error_setg(errp,
1436 "Snapshot with name '%s' already exists on device '%s'",
1437 name, device);
1438 goto out;
1439 }
1440
1441 /* 3. take the snapshot */
1442 sn = &state->sn;
1443 pstrcpy(sn->name, sizeof(sn->name), name);
1444 qemu_gettimeofday(&tv);
1445 sn->date_sec = tv.tv_sec;
1446 sn->date_nsec = tv.tv_usec * 1000;
1447 sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
1448
1449 ret1 = bdrv_snapshot_create(bs, sn);
1450 if (ret1 < 0) {
1451 error_setg_errno(errp, -ret1,
1452 "Failed to create snapshot '%s' on device '%s'",
1453 name, device);
1454 goto out;
1455 }
1456
1457 /* 4. succeed, mark a snapshot is created */
1458 state->created = true;
1459
1460 out:
1461 aio_context_release(aio_context);
1462 }
1463
1464 static void internal_snapshot_abort(BlkActionState *common)
1465 {
1466 InternalSnapshotState *state =
1467 DO_UPCAST(InternalSnapshotState, common, common);
1468 BlockDriverState *bs = state->bs;
1469 QEMUSnapshotInfo *sn = &state->sn;
1470 AioContext *aio_context;
1471 Error *local_error = NULL;
1472
1473 if (!state->created) {
1474 return;
1475 }
1476
1477 aio_context = bdrv_get_aio_context(state->bs);
1478 aio_context_acquire(aio_context);
1479
1480 if (bdrv_snapshot_delete(bs, sn->id_str, sn->name, &local_error) < 0) {
1481 error_reportf_err(local_error,
1482 "Failed to delete snapshot with id '%s' and "
1483 "name '%s' on device '%s' in abort: ",
1484 sn->id_str, sn->name,
1485 bdrv_get_device_name(bs));
1486 }
1487
1488 aio_context_release(aio_context);
1489 }
1490
1491 static void internal_snapshot_clean(BlkActionState *common)
1492 {
1493 InternalSnapshotState *state = DO_UPCAST(InternalSnapshotState,
1494 common, common);
1495 AioContext *aio_context;
1496
1497 if (!state->bs) {
1498 return;
1499 }
1500
1501 aio_context = bdrv_get_aio_context(state->bs);
1502 aio_context_acquire(aio_context);
1503
1504 bdrv_drained_end(state->bs);
1505
1506 aio_context_release(aio_context);
1507 }
1508
1509 /* external snapshot private data */
1510 typedef struct ExternalSnapshotState {
1511 BlkActionState common;
1512 BlockDriverState *old_bs;
1513 BlockDriverState *new_bs;
1514 bool overlay_appended;
1515 } ExternalSnapshotState;
1516
1517 static void external_snapshot_prepare(BlkActionState *common,
1518 Error **errp)
1519 {
1520 int flags = 0;
1521 QDict *options = NULL;
1522 Error *local_err = NULL;
1523 /* Device and node name of the image to generate the snapshot from */
1524 const char *device;
1525 const char *node_name;
1526 /* Reference to the new image (for 'blockdev-snapshot') */
1527 const char *snapshot_ref;
1528 /* File name of the new image (for 'blockdev-snapshot-sync') */
1529 const char *new_image_file;
1530 ExternalSnapshotState *state =
1531 DO_UPCAST(ExternalSnapshotState, common, common);
1532 TransactionAction *action = common->action;
1533 AioContext *aio_context;
1534 AioContext *old_context;
1535 int ret;
1536
1537 /* 'blockdev-snapshot' and 'blockdev-snapshot-sync' have similar
1538 * purpose but a different set of parameters */
1539 switch (action->type) {
1540 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT:
1541 {
1542 BlockdevSnapshot *s = action->u.blockdev_snapshot.data;
1543 device = s->node;
1544 node_name = s->node;
1545 new_image_file = NULL;
1546 snapshot_ref = s->overlay;
1547 }
1548 break;
1549 case TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC:
1550 {
1551 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1552 device = s->has_device ? s->device : NULL;
1553 node_name = s->has_node_name ? s->node_name : NULL;
1554 new_image_file = s->snapshot_file;
1555 snapshot_ref = NULL;
1556 }
1557 break;
1558 default:
1559 g_assert_not_reached();
1560 }
1561
1562 /* start processing */
1563 if (action_check_completion_mode(common, errp) < 0) {
1564 return;
1565 }
1566
1567 state->old_bs = bdrv_lookup_bs(device, node_name, errp);
1568 if (!state->old_bs) {
1569 return;
1570 }
1571
1572 aio_context = bdrv_get_aio_context(state->old_bs);
1573 aio_context_acquire(aio_context);
1574
1575 /* Paired with .clean() */
1576 bdrv_drained_begin(state->old_bs);
1577
1578 if (!bdrv_is_inserted(state->old_bs)) {
1579 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
1580 goto out;
1581 }
1582
1583 if (bdrv_op_is_blocked(state->old_bs,
1584 BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT, errp)) {
1585 goto out;
1586 }
1587
1588 if (!bdrv_is_read_only(state->old_bs)) {
1589 if (bdrv_flush(state->old_bs)) {
1590 error_setg(errp, QERR_IO_ERROR);
1591 goto out;
1592 }
1593 }
1594
1595 if (action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC) {
1596 BlockdevSnapshotSync *s = action->u.blockdev_snapshot_sync.data;
1597 const char *format = s->has_format ? s->format : "qcow2";
1598 enum NewImageMode mode;
1599 const char *snapshot_node_name =
1600 s->has_snapshot_node_name ? s->snapshot_node_name : NULL;
1601
1602 if (node_name && !snapshot_node_name) {
1603 error_setg(errp, "New overlay node name missing");
1604 goto out;
1605 }
1606
1607 if (snapshot_node_name &&
1608 bdrv_lookup_bs(snapshot_node_name, snapshot_node_name, NULL)) {
1609 error_setg(errp, "New overlay node name already in use");
1610 goto out;
1611 }
1612
1613 flags = state->old_bs->open_flags;
1614 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_COPY_ON_READ);
1615 flags |= BDRV_O_NO_BACKING;
1616
1617 /* create new image w/backing file */
1618 mode = s->has_mode ? s->mode : NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1619 if (mode != NEW_IMAGE_MODE_EXISTING) {
1620 int64_t size = bdrv_getlength(state->old_bs);
1621 if (size < 0) {
1622 error_setg_errno(errp, -size, "bdrv_getlength failed");
1623 goto out;
1624 }
1625 bdrv_refresh_filename(state->old_bs);
1626 bdrv_img_create(new_image_file, format,
1627 state->old_bs->filename,
1628 state->old_bs->drv->format_name,
1629 NULL, size, flags, false, &local_err);
1630 if (local_err) {
1631 error_propagate(errp, local_err);
1632 goto out;
1633 }
1634 }
1635
1636 options = qdict_new();
1637 if (snapshot_node_name) {
1638 qdict_put_str(options, "node-name", snapshot_node_name);
1639 }
1640 qdict_put_str(options, "driver", format);
1641 }
1642
1643 state->new_bs = bdrv_open(new_image_file, snapshot_ref, options, flags,
1644 errp);
1645 /* We will manually add the backing_hd field to the bs later */
1646 if (!state->new_bs) {
1647 goto out;
1648 }
1649
1650 if (bdrv_has_blk(state->new_bs)) {
1651 error_setg(errp, "The overlay is already in use");
1652 goto out;
1653 }
1654
1655 if (bdrv_op_is_blocked(state->new_bs, BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
1656 errp)) {
1657 goto out;
1658 }
1659
1660 if (state->new_bs->backing != NULL) {
1661 error_setg(errp, "The overlay already has a backing image");
1662 goto out;
1663 }
1664
1665 if (!state->new_bs->drv->supports_backing) {
1666 error_setg(errp, "The overlay does not support backing images");
1667 goto out;
1668 }
1669
1670 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
1671 old_context = bdrv_get_aio_context(state->new_bs);
1672 aio_context_release(aio_context);
1673 aio_context_acquire(old_context);
1674
1675 ret = bdrv_try_set_aio_context(state->new_bs, aio_context, errp);
1676
1677 aio_context_release(old_context);
1678 aio_context_acquire(aio_context);
1679
1680 if (ret < 0) {
1681 goto out;
1682 }
1683
1684 /* This removes our old bs and adds the new bs. This is an operation that
1685 * can fail, so we need to do it in .prepare; undoing it for abort is
1686 * always possible. */
1687 bdrv_ref(state->new_bs);
1688 bdrv_append(state->new_bs, state->old_bs, &local_err);
1689 if (local_err) {
1690 error_propagate(errp, local_err);
1691 goto out;
1692 }
1693 state->overlay_appended = true;
1694
1695 out:
1696 aio_context_release(aio_context);
1697 }
1698
1699 static void external_snapshot_commit(BlkActionState *common)
1700 {
1701 ExternalSnapshotState *state =
1702 DO_UPCAST(ExternalSnapshotState, common, common);
1703 AioContext *aio_context;
1704
1705 aio_context = bdrv_get_aio_context(state->old_bs);
1706 aio_context_acquire(aio_context);
1707
1708 /* We don't need (or want) to use the transactional
1709 * bdrv_reopen_multiple() across all the entries at once, because we
1710 * don't want to abort all of them if one of them fails the reopen */
1711 if (!atomic_read(&state->old_bs->copy_on_read)) {
1712 bdrv_reopen_set_read_only(state->old_bs, true, NULL);
1713 }
1714
1715 aio_context_release(aio_context);
1716 }
1717
1718 static void external_snapshot_abort(BlkActionState *common)
1719 {
1720 ExternalSnapshotState *state =
1721 DO_UPCAST(ExternalSnapshotState, common, common);
1722 if (state->new_bs) {
1723 if (state->overlay_appended) {
1724 AioContext *aio_context;
1725 AioContext *tmp_context;
1726 int ret;
1727
1728 aio_context = bdrv_get_aio_context(state->old_bs);
1729 aio_context_acquire(aio_context);
1730
1731 bdrv_ref(state->old_bs); /* we can't let bdrv_set_backind_hd()
1732 close state->old_bs; we need it */
1733 bdrv_set_backing_hd(state->new_bs, NULL, &error_abort);
1734
1735 /*
1736 * The call to bdrv_set_backing_hd() above returns state->old_bs to
1737 * the main AioContext. As we're still going to be using it, return
1738 * it to the AioContext it was before.
1739 */
1740 tmp_context = bdrv_get_aio_context(state->old_bs);
1741 if (aio_context != tmp_context) {
1742 aio_context_release(aio_context);
1743 aio_context_acquire(tmp_context);
1744
1745 ret = bdrv_try_set_aio_context(state->old_bs,
1746 aio_context, NULL);
1747 assert(ret == 0);
1748
1749 aio_context_release(tmp_context);
1750 aio_context_acquire(aio_context);
1751 }
1752
1753 bdrv_replace_node(state->new_bs, state->old_bs, &error_abort);
1754 bdrv_unref(state->old_bs); /* bdrv_replace_node() ref'ed old_bs */
1755
1756 aio_context_release(aio_context);
1757 }
1758 }
1759 }
1760
1761 static void external_snapshot_clean(BlkActionState *common)
1762 {
1763 ExternalSnapshotState *state =
1764 DO_UPCAST(ExternalSnapshotState, common, common);
1765 AioContext *aio_context;
1766
1767 if (!state->old_bs) {
1768 return;
1769 }
1770
1771 aio_context = bdrv_get_aio_context(state->old_bs);
1772 aio_context_acquire(aio_context);
1773
1774 bdrv_drained_end(state->old_bs);
1775 bdrv_unref(state->new_bs);
1776
1777 aio_context_release(aio_context);
1778 }
1779
1780 typedef struct DriveBackupState {
1781 BlkActionState common;
1782 BlockDriverState *bs;
1783 BlockJob *job;
1784 } DriveBackupState;
1785
1786 static BlockJob *do_backup_common(BackupCommon *backup,
1787 BlockDriverState *bs,
1788 BlockDriverState *target_bs,
1789 AioContext *aio_context,
1790 JobTxn *txn, Error **errp);
1791
1792 static void drive_backup_prepare(BlkActionState *common, Error **errp)
1793 {
1794 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1795 DriveBackup *backup;
1796 BlockDriverState *bs;
1797 BlockDriverState *target_bs;
1798 BlockDriverState *source = NULL;
1799 AioContext *aio_context;
1800 AioContext *old_context;
1801 QDict *options;
1802 Error *local_err = NULL;
1803 int flags;
1804 int64_t size;
1805 bool set_backing_hd = false;
1806 int ret;
1807
1808 assert(common->action->type == TRANSACTION_ACTION_KIND_DRIVE_BACKUP);
1809 backup = common->action->u.drive_backup.data;
1810
1811 if (!backup->has_mode) {
1812 backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
1813 }
1814
1815 bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1816 if (!bs) {
1817 return;
1818 }
1819
1820 if (!bs->drv) {
1821 error_setg(errp, "Device has no medium");
1822 return;
1823 }
1824
1825 aio_context = bdrv_get_aio_context(bs);
1826 aio_context_acquire(aio_context);
1827
1828 /* Paired with .clean() */
1829 bdrv_drained_begin(bs);
1830
1831 if (!backup->has_format) {
1832 backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?
1833 NULL : (char *) bs->drv->format_name;
1834 }
1835
1836 /* Early check to avoid creating target */
1837 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
1838 goto out;
1839 }
1840
1841 flags = bs->open_flags | BDRV_O_RDWR;
1842
1843 /*
1844 * See if we have a backing HD we can use to create our new image
1845 * on top of.
1846 */
1847 if (backup->sync == MIRROR_SYNC_MODE_TOP) {
1848 source = backing_bs(bs);
1849 if (!source) {
1850 backup->sync = MIRROR_SYNC_MODE_FULL;
1851 }
1852 }
1853 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
1854 source = bs;
1855 flags |= BDRV_O_NO_BACKING;
1856 set_backing_hd = true;
1857 }
1858
1859 size = bdrv_getlength(bs);
1860 if (size < 0) {
1861 error_setg_errno(errp, -size, "bdrv_getlength failed");
1862 goto out;
1863 }
1864
1865 if (backup->mode != NEW_IMAGE_MODE_EXISTING) {
1866 assert(backup->format);
1867 if (source) {
1868 bdrv_refresh_filename(source);
1869 bdrv_img_create(backup->target, backup->format, source->filename,
1870 source->drv->format_name, NULL,
1871 size, flags, false, &local_err);
1872 } else {
1873 bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,
1874 size, flags, false, &local_err);
1875 }
1876 }
1877
1878 if (local_err) {
1879 error_propagate(errp, local_err);
1880 goto out;
1881 }
1882
1883 options = qdict_new();
1884 qdict_put_str(options, "discard", "unmap");
1885 qdict_put_str(options, "detect-zeroes", "unmap");
1886 if (backup->format) {
1887 qdict_put_str(options, "driver", backup->format);
1888 }
1889
1890 target_bs = bdrv_open(backup->target, NULL, options, flags, errp);
1891 if (!target_bs) {
1892 goto out;
1893 }
1894
1895 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
1896 old_context = bdrv_get_aio_context(target_bs);
1897 aio_context_release(aio_context);
1898 aio_context_acquire(old_context);
1899
1900 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
1901 if (ret < 0) {
1902 bdrv_unref(target_bs);
1903 aio_context_release(old_context);
1904 return;
1905 }
1906
1907 aio_context_release(old_context);
1908 aio_context_acquire(aio_context);
1909
1910 if (set_backing_hd) {
1911 bdrv_set_backing_hd(target_bs, source, &local_err);
1912 if (local_err) {
1913 goto unref;
1914 }
1915 }
1916
1917 state->bs = bs;
1918
1919 state->job = do_backup_common(qapi_DriveBackup_base(backup),
1920 bs, target_bs, aio_context,
1921 common->block_job_txn, errp);
1922
1923 unref:
1924 bdrv_unref(target_bs);
1925 out:
1926 aio_context_release(aio_context);
1927 }
1928
1929 static void drive_backup_commit(BlkActionState *common)
1930 {
1931 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1932 AioContext *aio_context;
1933
1934 aio_context = bdrv_get_aio_context(state->bs);
1935 aio_context_acquire(aio_context);
1936
1937 assert(state->job);
1938 job_start(&state->job->job);
1939
1940 aio_context_release(aio_context);
1941 }
1942
1943 static void drive_backup_abort(BlkActionState *common)
1944 {
1945 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1946
1947 if (state->job) {
1948 AioContext *aio_context;
1949
1950 aio_context = bdrv_get_aio_context(state->bs);
1951 aio_context_acquire(aio_context);
1952
1953 job_cancel_sync(&state->job->job);
1954
1955 aio_context_release(aio_context);
1956 }
1957 }
1958
1959 static void drive_backup_clean(BlkActionState *common)
1960 {
1961 DriveBackupState *state = DO_UPCAST(DriveBackupState, common, common);
1962 AioContext *aio_context;
1963
1964 if (!state->bs) {
1965 return;
1966 }
1967
1968 aio_context = bdrv_get_aio_context(state->bs);
1969 aio_context_acquire(aio_context);
1970
1971 bdrv_drained_end(state->bs);
1972
1973 aio_context_release(aio_context);
1974 }
1975
1976 typedef struct BlockdevBackupState {
1977 BlkActionState common;
1978 BlockDriverState *bs;
1979 BlockJob *job;
1980 } BlockdevBackupState;
1981
1982 static void blockdev_backup_prepare(BlkActionState *common, Error **errp)
1983 {
1984 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
1985 BlockdevBackup *backup;
1986 BlockDriverState *bs;
1987 BlockDriverState *target_bs;
1988 AioContext *aio_context;
1989 AioContext *old_context;
1990 int ret;
1991
1992 assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);
1993 backup = common->action->u.blockdev_backup.data;
1994
1995 bs = bdrv_lookup_bs(backup->device, backup->device, errp);
1996 if (!bs) {
1997 return;
1998 }
1999
2000 target_bs = bdrv_lookup_bs(backup->target, backup->target, errp);
2001 if (!target_bs) {
2002 return;
2003 }
2004
2005 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
2006 aio_context = bdrv_get_aio_context(bs);
2007 old_context = bdrv_get_aio_context(target_bs);
2008 aio_context_acquire(old_context);
2009
2010 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
2011 if (ret < 0) {
2012 aio_context_release(old_context);
2013 return;
2014 }
2015
2016 aio_context_release(old_context);
2017 aio_context_acquire(aio_context);
2018 state->bs = bs;
2019
2020 /* Paired with .clean() */
2021 bdrv_drained_begin(state->bs);
2022
2023 state->job = do_backup_common(qapi_BlockdevBackup_base(backup),
2024 bs, target_bs, aio_context,
2025 common->block_job_txn, errp);
2026
2027 aio_context_release(aio_context);
2028 }
2029
2030 static void blockdev_backup_commit(BlkActionState *common)
2031 {
2032 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2033 AioContext *aio_context;
2034
2035 aio_context = bdrv_get_aio_context(state->bs);
2036 aio_context_acquire(aio_context);
2037
2038 assert(state->job);
2039 job_start(&state->job->job);
2040
2041 aio_context_release(aio_context);
2042 }
2043
2044 static void blockdev_backup_abort(BlkActionState *common)
2045 {
2046 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2047
2048 if (state->job) {
2049 AioContext *aio_context;
2050
2051 aio_context = bdrv_get_aio_context(state->bs);
2052 aio_context_acquire(aio_context);
2053
2054 job_cancel_sync(&state->job->job);
2055
2056 aio_context_release(aio_context);
2057 }
2058 }
2059
2060 static void blockdev_backup_clean(BlkActionState *common)
2061 {
2062 BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);
2063 AioContext *aio_context;
2064
2065 if (!state->bs) {
2066 return;
2067 }
2068
2069 aio_context = bdrv_get_aio_context(state->bs);
2070 aio_context_acquire(aio_context);
2071
2072 bdrv_drained_end(state->bs);
2073
2074 aio_context_release(aio_context);
2075 }
2076
2077 typedef struct BlockDirtyBitmapState {
2078 BlkActionState common;
2079 BdrvDirtyBitmap *bitmap;
2080 BlockDriverState *bs;
2081 HBitmap *backup;
2082 bool prepared;
2083 bool was_enabled;
2084 } BlockDirtyBitmapState;
2085
2086 static void block_dirty_bitmap_add_prepare(BlkActionState *common,
2087 Error **errp)
2088 {
2089 Error *local_err = NULL;
2090 BlockDirtyBitmapAdd *action;
2091 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2092 common, common);
2093
2094 if (action_check_completion_mode(common, errp) < 0) {
2095 return;
2096 }
2097
2098 action = common->action->u.block_dirty_bitmap_add.data;
2099 /* AIO context taken and released within qmp_block_dirty_bitmap_add */
2100 qmp_block_dirty_bitmap_add(action->node, action->name,
2101 action->has_granularity, action->granularity,
2102 action->has_persistent, action->persistent,
2103 action->has_disabled, action->disabled,
2104 &local_err);
2105
2106 if (!local_err) {
2107 state->prepared = true;
2108 } else {
2109 error_propagate(errp, local_err);
2110 }
2111 }
2112
2113 static void block_dirty_bitmap_add_abort(BlkActionState *common)
2114 {
2115 BlockDirtyBitmapAdd *action;
2116 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2117 common, common);
2118
2119 action = common->action->u.block_dirty_bitmap_add.data;
2120 /* Should not be able to fail: IF the bitmap was added via .prepare(),
2121 * then the node reference and bitmap name must have been valid.
2122 */
2123 if (state->prepared) {
2124 qmp_block_dirty_bitmap_remove(action->node, action->name, &error_abort);
2125 }
2126 }
2127
2128 static void block_dirty_bitmap_clear_prepare(BlkActionState *common,
2129 Error **errp)
2130 {
2131 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2132 common, common);
2133 BlockDirtyBitmap *action;
2134
2135 if (action_check_completion_mode(common, errp) < 0) {
2136 return;
2137 }
2138
2139 action = common->action->u.block_dirty_bitmap_clear.data;
2140 state->bitmap = block_dirty_bitmap_lookup(action->node,
2141 action->name,
2142 &state->bs,
2143 errp);
2144 if (!state->bitmap) {
2145 return;
2146 }
2147
2148 if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_DEFAULT, errp)) {
2149 return;
2150 }
2151
2152 bdrv_clear_dirty_bitmap(state->bitmap, &state->backup);
2153 }
2154
2155 static void block_dirty_bitmap_restore(BlkActionState *common)
2156 {
2157 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2158 common, common);
2159
2160 if (state->backup) {
2161 bdrv_restore_dirty_bitmap(state->bitmap, state->backup);
2162 }
2163 }
2164
2165 static void block_dirty_bitmap_free_backup(BlkActionState *common)
2166 {
2167 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2168 common, common);
2169
2170 hbitmap_free(state->backup);
2171 }
2172
2173 static void block_dirty_bitmap_enable_prepare(BlkActionState *common,
2174 Error **errp)
2175 {
2176 BlockDirtyBitmap *action;
2177 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2178 common, common);
2179
2180 if (action_check_completion_mode(common, errp) < 0) {
2181 return;
2182 }
2183
2184 action = common->action->u.block_dirty_bitmap_enable.data;
2185 state->bitmap = block_dirty_bitmap_lookup(action->node,
2186 action->name,
2187 NULL,
2188 errp);
2189 if (!state->bitmap) {
2190 return;
2191 }
2192
2193 if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2194 return;
2195 }
2196
2197 state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2198 bdrv_enable_dirty_bitmap(state->bitmap);
2199 }
2200
2201 static void block_dirty_bitmap_enable_abort(BlkActionState *common)
2202 {
2203 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2204 common, common);
2205
2206 if (!state->was_enabled) {
2207 bdrv_disable_dirty_bitmap(state->bitmap);
2208 }
2209 }
2210
2211 static void block_dirty_bitmap_disable_prepare(BlkActionState *common,
2212 Error **errp)
2213 {
2214 BlockDirtyBitmap *action;
2215 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2216 common, common);
2217
2218 if (action_check_completion_mode(common, errp) < 0) {
2219 return;
2220 }
2221
2222 action = common->action->u.block_dirty_bitmap_disable.data;
2223 state->bitmap = block_dirty_bitmap_lookup(action->node,
2224 action->name,
2225 NULL,
2226 errp);
2227 if (!state->bitmap) {
2228 return;
2229 }
2230
2231 if (bdrv_dirty_bitmap_check(state->bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
2232 return;
2233 }
2234
2235 state->was_enabled = bdrv_dirty_bitmap_enabled(state->bitmap);
2236 bdrv_disable_dirty_bitmap(state->bitmap);
2237 }
2238
2239 static void block_dirty_bitmap_disable_abort(BlkActionState *common)
2240 {
2241 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2242 common, common);
2243
2244 if (state->was_enabled) {
2245 bdrv_enable_dirty_bitmap(state->bitmap);
2246 }
2247 }
2248
2249 static BdrvDirtyBitmap *do_block_dirty_bitmap_merge(
2250 const char *node, const char *target,
2251 BlockDirtyBitmapMergeSourceList *bitmaps,
2252 HBitmap **backup, Error **errp);
2253
2254 static void block_dirty_bitmap_merge_prepare(BlkActionState *common,
2255 Error **errp)
2256 {
2257 BlockDirtyBitmapMerge *action;
2258 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2259 common, common);
2260
2261 if (action_check_completion_mode(common, errp) < 0) {
2262 return;
2263 }
2264
2265 action = common->action->u.block_dirty_bitmap_merge.data;
2266
2267 state->bitmap = do_block_dirty_bitmap_merge(action->node, action->target,
2268 action->bitmaps, &state->backup,
2269 errp);
2270 }
2271
2272 static BdrvDirtyBitmap *do_block_dirty_bitmap_remove(
2273 const char *node, const char *name, bool release,
2274 BlockDriverState **bitmap_bs, Error **errp);
2275
2276 static void block_dirty_bitmap_remove_prepare(BlkActionState *common,
2277 Error **errp)
2278 {
2279 BlockDirtyBitmap *action;
2280 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2281 common, common);
2282
2283 if (action_check_completion_mode(common, errp) < 0) {
2284 return;
2285 }
2286
2287 action = common->action->u.block_dirty_bitmap_remove.data;
2288
2289 state->bitmap = do_block_dirty_bitmap_remove(action->node, action->name,
2290 false, &state->bs, errp);
2291 if (state->bitmap) {
2292 bdrv_dirty_bitmap_skip_store(state->bitmap, true);
2293 bdrv_dirty_bitmap_set_busy(state->bitmap, true);
2294 }
2295 }
2296
2297 static void block_dirty_bitmap_remove_abort(BlkActionState *common)
2298 {
2299 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2300 common, common);
2301
2302 if (state->bitmap) {
2303 bdrv_dirty_bitmap_skip_store(state->bitmap, false);
2304 bdrv_dirty_bitmap_set_busy(state->bitmap, false);
2305 }
2306 }
2307
2308 static void block_dirty_bitmap_remove_commit(BlkActionState *common)
2309 {
2310 BlockDirtyBitmapState *state = DO_UPCAST(BlockDirtyBitmapState,
2311 common, common);
2312
2313 bdrv_dirty_bitmap_set_busy(state->bitmap, false);
2314 bdrv_release_dirty_bitmap(state->bitmap);
2315 }
2316
2317 static void abort_prepare(BlkActionState *common, Error **errp)
2318 {
2319 error_setg(errp, "Transaction aborted using Abort action");
2320 }
2321
2322 static void abort_commit(BlkActionState *common)
2323 {
2324 g_assert_not_reached(); /* this action never succeeds */
2325 }
2326
2327 static const BlkActionOps actions[] = {
2328 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT] = {
2329 .instance_size = sizeof(ExternalSnapshotState),
2330 .prepare = external_snapshot_prepare,
2331 .commit = external_snapshot_commit,
2332 .abort = external_snapshot_abort,
2333 .clean = external_snapshot_clean,
2334 },
2335 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_SYNC] = {
2336 .instance_size = sizeof(ExternalSnapshotState),
2337 .prepare = external_snapshot_prepare,
2338 .commit = external_snapshot_commit,
2339 .abort = external_snapshot_abort,
2340 .clean = external_snapshot_clean,
2341 },
2342 [TRANSACTION_ACTION_KIND_DRIVE_BACKUP] = {
2343 .instance_size = sizeof(DriveBackupState),
2344 .prepare = drive_backup_prepare,
2345 .commit = drive_backup_commit,
2346 .abort = drive_backup_abort,
2347 .clean = drive_backup_clean,
2348 },
2349 [TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP] = {
2350 .instance_size = sizeof(BlockdevBackupState),
2351 .prepare = blockdev_backup_prepare,
2352 .commit = blockdev_backup_commit,
2353 .abort = blockdev_backup_abort,
2354 .clean = blockdev_backup_clean,
2355 },
2356 [TRANSACTION_ACTION_KIND_ABORT] = {
2357 .instance_size = sizeof(BlkActionState),
2358 .prepare = abort_prepare,
2359 .commit = abort_commit,
2360 },
2361 [TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC] = {
2362 .instance_size = sizeof(InternalSnapshotState),
2363 .prepare = internal_snapshot_prepare,
2364 .abort = internal_snapshot_abort,
2365 .clean = internal_snapshot_clean,
2366 },
2367 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ADD] = {
2368 .instance_size = sizeof(BlockDirtyBitmapState),
2369 .prepare = block_dirty_bitmap_add_prepare,
2370 .abort = block_dirty_bitmap_add_abort,
2371 },
2372 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_CLEAR] = {
2373 .instance_size = sizeof(BlockDirtyBitmapState),
2374 .prepare = block_dirty_bitmap_clear_prepare,
2375 .commit = block_dirty_bitmap_free_backup,
2376 .abort = block_dirty_bitmap_restore,
2377 },
2378 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_ENABLE] = {
2379 .instance_size = sizeof(BlockDirtyBitmapState),
2380 .prepare = block_dirty_bitmap_enable_prepare,
2381 .abort = block_dirty_bitmap_enable_abort,
2382 },
2383 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_DISABLE] = {
2384 .instance_size = sizeof(BlockDirtyBitmapState),
2385 .prepare = block_dirty_bitmap_disable_prepare,
2386 .abort = block_dirty_bitmap_disable_abort,
2387 },
2388 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_MERGE] = {
2389 .instance_size = sizeof(BlockDirtyBitmapState),
2390 .prepare = block_dirty_bitmap_merge_prepare,
2391 .commit = block_dirty_bitmap_free_backup,
2392 .abort = block_dirty_bitmap_restore,
2393 },
2394 [TRANSACTION_ACTION_KIND_BLOCK_DIRTY_BITMAP_REMOVE] = {
2395 .instance_size = sizeof(BlockDirtyBitmapState),
2396 .prepare = block_dirty_bitmap_remove_prepare,
2397 .commit = block_dirty_bitmap_remove_commit,
2398 .abort = block_dirty_bitmap_remove_abort,
2399 },
2400 /* Where are transactions for MIRROR, COMMIT and STREAM?
2401 * Although these blockjobs use transaction callbacks like the backup job,
2402 * these jobs do not necessarily adhere to transaction semantics.
2403 * These jobs may not fully undo all of their actions on abort, nor do they
2404 * necessarily work in transactions with more than one job in them.
2405 */
2406 };
2407
2408 /**
2409 * Allocate a TransactionProperties structure if necessary, and fill
2410 * that structure with desired defaults if they are unset.
2411 */
2412 static TransactionProperties *get_transaction_properties(
2413 TransactionProperties *props)
2414 {
2415 if (!props) {
2416 props = g_new0(TransactionProperties, 1);
2417 }
2418
2419 if (!props->has_completion_mode) {
2420 props->has_completion_mode = true;
2421 props->completion_mode = ACTION_COMPLETION_MODE_INDIVIDUAL;
2422 }
2423
2424 return props;
2425 }
2426
2427 /*
2428 * 'Atomic' group operations. The operations are performed as a set, and if
2429 * any fail then we roll back all operations in the group.
2430 */
2431 void qmp_transaction(TransactionActionList *dev_list,
2432 bool has_props,
2433 struct TransactionProperties *props,
2434 Error **errp)
2435 {
2436 TransactionActionList *dev_entry = dev_list;
2437 JobTxn *block_job_txn = NULL;
2438 BlkActionState *state, *next;
2439 Error *local_err = NULL;
2440
2441 QTAILQ_HEAD(, BlkActionState) snap_bdrv_states;
2442 QTAILQ_INIT(&snap_bdrv_states);
2443
2444 /* Does this transaction get canceled as a group on failure?
2445 * If not, we don't really need to make a JobTxn.
2446 */
2447 props = get_transaction_properties(props);
2448 if (props->completion_mode != ACTION_COMPLETION_MODE_INDIVIDUAL) {
2449 block_job_txn = job_txn_new();
2450 }
2451
2452 /* drain all i/o before any operations */
2453 bdrv_drain_all();
2454
2455 /* We don't do anything in this loop that commits us to the operations */
2456 while (NULL != dev_entry) {
2457 TransactionAction *dev_info = NULL;
2458 const BlkActionOps *ops;
2459
2460 dev_info = dev_entry->value;
2461 dev_entry = dev_entry->next;
2462
2463 assert(dev_info->type < ARRAY_SIZE(actions));
2464
2465 ops = &actions[dev_info->type];
2466 assert(ops->instance_size > 0);
2467
2468 state = g_malloc0(ops->instance_size);
2469 state->ops = ops;
2470 state->action = dev_info;
2471 state->block_job_txn = block_job_txn;
2472 state->txn_props = props;
2473 QTAILQ_INSERT_TAIL(&snap_bdrv_states, state, entry);
2474
2475 state->ops->prepare(state, &local_err);
2476 if (local_err) {
2477 error_propagate(errp, local_err);
2478 goto delete_and_fail;
2479 }
2480 }
2481
2482 QTAILQ_FOREACH(state, &snap_bdrv_states, entry) {
2483 if (state->ops->commit) {
2484 state->ops->commit(state);
2485 }
2486 }
2487
2488 /* success */
2489 goto exit;
2490
2491 delete_and_fail:
2492 /* failure, and it is all-or-none; roll back all operations */
2493 QTAILQ_FOREACH_REVERSE(state, &snap_bdrv_states, entry) {
2494 if (state->ops->abort) {
2495 state->ops->abort(state);
2496 }
2497 }
2498 exit:
2499 QTAILQ_FOREACH_SAFE(state, &snap_bdrv_states, entry, next) {
2500 if (state->ops->clean) {
2501 state->ops->clean(state);
2502 }
2503 g_free(state);
2504 }
2505 if (!has_props) {
2506 qapi_free_TransactionProperties(props);
2507 }
2508 job_txn_unref(block_job_txn);
2509 }
2510
2511 void qmp_eject(bool has_device, const char *device,
2512 bool has_id, const char *id,
2513 bool has_force, bool force, Error **errp)
2514 {
2515 Error *local_err = NULL;
2516 int rc;
2517
2518 if (!has_force) {
2519 force = false;
2520 }
2521
2522 rc = do_open_tray(has_device ? device : NULL,
2523 has_id ? id : NULL,
2524 force, &local_err);
2525 if (rc && rc != -ENOSYS) {
2526 error_propagate(errp, local_err);
2527 return;
2528 }
2529 error_free(local_err);
2530
2531 blockdev_remove_medium(has_device, device, has_id, id, errp);
2532 }
2533
2534 void qmp_block_passwd(bool has_device, const char *device,
2535 bool has_node_name, const char *node_name,
2536 const char *password, Error **errp)
2537 {
2538 error_setg(errp,
2539 "Setting block passwords directly is no longer supported");
2540 }
2541
2542 /*
2543 * Attempt to open the tray of @device.
2544 * If @force, ignore its tray lock.
2545 * Else, if the tray is locked, don't open it, but ask the guest to open it.
2546 * On error, store an error through @errp and return -errno.
2547 * If @device does not exist, return -ENODEV.
2548 * If it has no removable media, return -ENOTSUP.
2549 * If it has no tray, return -ENOSYS.
2550 * If the guest was asked to open the tray, return -EINPROGRESS.
2551 * Else, return 0.
2552 */
2553 static int do_open_tray(const char *blk_name, const char *qdev_id,
2554 bool force, Error **errp)
2555 {
2556 BlockBackend *blk;
2557 const char *device = qdev_id ?: blk_name;
2558 bool locked;
2559
2560 blk = qmp_get_blk(blk_name, qdev_id, errp);
2561 if (!blk) {
2562 return -ENODEV;
2563 }
2564
2565 if (!blk_dev_has_removable_media(blk)) {
2566 error_setg(errp, "Device '%s' is not removable", device);
2567 return -ENOTSUP;
2568 }
2569
2570 if (!blk_dev_has_tray(blk)) {
2571 error_setg(errp, "Device '%s' does not have a tray", device);
2572 return -ENOSYS;
2573 }
2574
2575 if (blk_dev_is_tray_open(blk)) {
2576 return 0;
2577 }
2578
2579 locked = blk_dev_is_medium_locked(blk);
2580 if (locked) {
2581 blk_dev_eject_request(blk, force);
2582 }
2583
2584 if (!locked || force) {
2585 blk_dev_change_media_cb(blk, false, &error_abort);
2586 }
2587
2588 if (locked && !force) {
2589 error_setg(errp, "Device '%s' is locked and force was not specified, "
2590 "wait for tray to open and try again", device);
2591 return -EINPROGRESS;
2592 }
2593
2594 return 0;
2595 }
2596
2597 void qmp_blockdev_open_tray(bool has_device, const char *device,
2598 bool has_id, const char *id,
2599 bool has_force, bool force,
2600 Error **errp)
2601 {
2602 Error *local_err = NULL;
2603 int rc;
2604
2605 if (!has_force) {
2606 force = false;
2607 }
2608 rc = do_open_tray(has_device ? device : NULL,
2609 has_id ? id : NULL,
2610 force, &local_err);
2611 if (rc && rc != -ENOSYS && rc != -EINPROGRESS) {
2612 error_propagate(errp, local_err);
2613 return;
2614 }
2615 error_free(local_err);
2616 }
2617
2618 void qmp_blockdev_close_tray(bool has_device, const char *device,
2619 bool has_id, const char *id,
2620 Error **errp)
2621 {
2622 BlockBackend *blk;
2623 Error *local_err = NULL;
2624
2625 device = has_device ? device : NULL;
2626 id = has_id ? id : NULL;
2627
2628 blk = qmp_get_blk(device, id, errp);
2629 if (!blk) {
2630 return;
2631 }
2632
2633 if (!blk_dev_has_removable_media(blk)) {
2634 error_setg(errp, "Device '%s' is not removable", device ?: id);
2635 return;
2636 }
2637
2638 if (!blk_dev_has_tray(blk)) {
2639 /* Ignore this command on tray-less devices */
2640 return;
2641 }
2642
2643 if (!blk_dev_is_tray_open(blk)) {
2644 return;
2645 }
2646
2647 blk_dev_change_media_cb(blk, true, &local_err);
2648 if (local_err) {
2649 error_propagate(errp, local_err);
2650 return;
2651 }
2652 }
2653
2654 static void blockdev_remove_medium(bool has_device, const char *device,
2655 bool has_id, const char *id, Error **errp)
2656 {
2657 BlockBackend *blk;
2658 BlockDriverState *bs;
2659 AioContext *aio_context;
2660 bool has_attached_device;
2661
2662 device = has_device ? device : NULL;
2663 id = has_id ? id : NULL;
2664
2665 blk = qmp_get_blk(device, id, errp);
2666 if (!blk) {
2667 return;
2668 }
2669
2670 /* For BBs without a device, we can exchange the BDS tree at will */
2671 has_attached_device = blk_get_attached_dev(blk);
2672
2673 if (has_attached_device && !blk_dev_has_removable_media(blk)) {
2674 error_setg(errp, "Device '%s' is not removable", device ?: id);
2675 return;
2676 }
2677
2678 if (has_attached_device && blk_dev_has_tray(blk) &&
2679 !blk_dev_is_tray_open(blk))
2680 {
2681 error_setg(errp, "Tray of device '%s' is not open", device ?: id);
2682 return;
2683 }
2684
2685 bs = blk_bs(blk);
2686 if (!bs) {
2687 return;
2688 }
2689
2690 aio_context = bdrv_get_aio_context(bs);
2691 aio_context_acquire(aio_context);
2692
2693 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_EJECT, errp)) {
2694 goto out;
2695 }
2696
2697 blk_remove_bs(blk);
2698
2699 if (!blk_dev_has_tray(blk)) {
2700 /* For tray-less devices, blockdev-open-tray is a no-op (or may not be
2701 * called at all); therefore, the medium needs to be ejected here.
2702 * Do it after blk_remove_bs() so blk_is_inserted(blk) returns the @load
2703 * value passed here (i.e. false). */
2704 blk_dev_change_media_cb(blk, false, &error_abort);
2705 }
2706
2707 out:
2708 aio_context_release(aio_context);
2709 }
2710
2711 void qmp_blockdev_remove_medium(const char *id, Error **errp)
2712 {
2713 blockdev_remove_medium(false, NULL, true, id, errp);
2714 }
2715
2716 static void qmp_blockdev_insert_anon_medium(BlockBackend *blk,
2717 BlockDriverState *bs, Error **errp)
2718 {
2719 Error *local_err = NULL;
2720 bool has_device;
2721 int ret;
2722
2723 /* For BBs without a device, we can exchange the BDS tree at will */
2724 has_device = blk_get_attached_dev(blk);
2725
2726 if (has_device && !blk_dev_has_removable_media(blk)) {
2727 error_setg(errp, "Device is not removable");
2728 return;
2729 }
2730
2731 if (has_device && blk_dev_has_tray(blk) && !blk_dev_is_tray_open(blk)) {
2732 error_setg(errp, "Tray of the device is not open");
2733 return;
2734 }
2735
2736 if (blk_bs(blk)) {
2737 error_setg(errp, "There already is a medium in the device");
2738 return;
2739 }
2740
2741 ret = blk_insert_bs(blk, bs, errp);
2742 if (ret < 0) {
2743 return;
2744 }
2745
2746 if (!blk_dev_has_tray(blk)) {
2747 /* For tray-less devices, blockdev-close-tray is a no-op (or may not be
2748 * called at all); therefore, the medium needs to be pushed into the
2749 * slot here.
2750 * Do it after blk_insert_bs() so blk_is_inserted(blk) returns the @load
2751 * value passed here (i.e. true). */
2752 blk_dev_change_media_cb(blk, true, &local_err);
2753 if (local_err) {
2754 error_propagate(errp, local_err);
2755 blk_remove_bs(blk);
2756 return;
2757 }
2758 }
2759 }
2760
2761 static void blockdev_insert_medium(bool has_device, const char *device,
2762 bool has_id, const char *id,
2763 const char *node_name, Error **errp)
2764 {
2765 BlockBackend *blk;
2766 BlockDriverState *bs;
2767
2768 blk = qmp_get_blk(has_device ? device : NULL,
2769 has_id ? id : NULL,
2770 errp);
2771 if (!blk) {
2772 return;
2773 }
2774
2775 bs = bdrv_find_node(node_name);
2776 if (!bs) {
2777 error_setg(errp, "Node '%s' not found", node_name);
2778 return;
2779 }
2780
2781 if (bdrv_has_blk(bs)) {
2782 error_setg(errp, "Node '%s' is already in use", node_name);
2783 return;
2784 }
2785
2786 qmp_blockdev_insert_anon_medium(blk, bs, errp);
2787 }
2788
2789 void qmp_blockdev_insert_medium(const char *id, const char *node_name,
2790 Error **errp)
2791 {
2792 blockdev_insert_medium(false, NULL, true, id, node_name, errp);
2793 }
2794
2795 void qmp_blockdev_change_medium(bool has_device, const char *device,
2796 bool has_id, const char *id,
2797 const char *filename,
2798 bool has_format, const char *format,
2799 bool has_read_only,
2800 BlockdevChangeReadOnlyMode read_only,
2801 Error **errp)
2802 {
2803 BlockBackend *blk;
2804 BlockDriverState *medium_bs = NULL;
2805 int bdrv_flags;
2806 bool detect_zeroes;
2807 int rc;
2808 QDict *options = NULL;
2809 Error *err = NULL;
2810
2811 blk = qmp_get_blk(has_device ? device : NULL,
2812 has_id ? id : NULL,
2813 errp);
2814 if (!blk) {
2815 goto fail;
2816 }
2817
2818 if (blk_bs(blk)) {
2819 blk_update_root_state(blk);
2820 }
2821
2822 bdrv_flags = blk_get_open_flags_from_root_state(blk);
2823 bdrv_flags &= ~(BDRV_O_TEMPORARY | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING |
2824 BDRV_O_PROTOCOL | BDRV_O_AUTO_RDONLY);
2825
2826 if (!has_read_only) {
2827 read_only = BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN;
2828 }
2829
2830 switch (read_only) {
2831 case BLOCKDEV_CHANGE_READ_ONLY_MODE_RETAIN:
2832 break;
2833
2834 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_ONLY:
2835 bdrv_flags &= ~BDRV_O_RDWR;
2836 break;
2837
2838 case BLOCKDEV_CHANGE_READ_ONLY_MODE_READ_WRITE:
2839 bdrv_flags |= BDRV_O_RDWR;
2840 break;
2841
2842 default:
2843 abort();
2844 }
2845
2846 options = qdict_new();
2847 detect_zeroes = blk_get_detect_zeroes_from_root_state(blk);
2848 qdict_put_str(options, "detect-zeroes", detect_zeroes ? "on" : "off");
2849
2850 if (has_format) {
2851 qdict_put_str(options, "driver", format);
2852 }
2853
2854 medium_bs = bdrv_open(filename, NULL, options, bdrv_flags, errp);
2855 if (!medium_bs) {
2856 goto fail;
2857 }
2858
2859 rc = do_open_tray(has_device ? device : NULL,
2860 has_id ? id : NULL,
2861 false, &err);
2862 if (rc && rc != -ENOSYS) {
2863 error_propagate(errp, err);
2864 goto fail;
2865 }
2866 error_free(err);
2867 err = NULL;
2868
2869 blockdev_remove_medium(has_device, device, has_id, id, &err);
2870 if (err) {
2871 error_propagate(errp, err);
2872 goto fail;
2873 }
2874
2875 qmp_blockdev_insert_anon_medium(blk, medium_bs, &err);
2876 if (err) {
2877 error_propagate(errp, err);
2878 goto fail;
2879 }
2880
2881 qmp_blockdev_close_tray(has_device, device, has_id, id, errp);
2882
2883 fail:
2884 /* If the medium has been inserted, the device has its own reference, so
2885 * ours must be relinquished; and if it has not been inserted successfully,
2886 * the reference must be relinquished anyway */
2887 bdrv_unref(medium_bs);
2888 }
2889
2890 /* throttling disk I/O limits */
2891 void qmp_block_set_io_throttle(BlockIOThrottle *arg, Error **errp)
2892 {
2893 ThrottleConfig cfg;
2894 BlockDriverState *bs;
2895 BlockBackend *blk;
2896 AioContext *aio_context;
2897
2898 blk = qmp_get_blk(arg->has_device ? arg->device : NULL,
2899 arg->has_id ? arg->id : NULL,
2900 errp);
2901 if (!blk) {
2902 return;
2903 }
2904
2905 aio_context = blk_get_aio_context(blk);
2906 aio_context_acquire(aio_context);
2907
2908 bs = blk_bs(blk);
2909 if (!bs) {
2910 error_setg(errp, "Device has no medium");
2911 goto out;
2912 }
2913
2914 throttle_config_init(&cfg);
2915 cfg.buckets[THROTTLE_BPS_TOTAL].avg = arg->bps;
2916 cfg.buckets[THROTTLE_BPS_READ].avg = arg->bps_rd;
2917 cfg.buckets[THROTTLE_BPS_WRITE].avg = arg->bps_wr;
2918
2919 cfg.buckets[THROTTLE_OPS_TOTAL].avg = arg->iops;
2920 cfg.buckets[THROTTLE_OPS_READ].avg = arg->iops_rd;
2921 cfg.buckets[THROTTLE_OPS_WRITE].avg = arg->iops_wr;
2922
2923 if (arg->has_bps_max) {
2924 cfg.buckets[THROTTLE_BPS_TOTAL].max = arg->bps_max;
2925 }
2926 if (arg->has_bps_rd_max) {
2927 cfg.buckets[THROTTLE_BPS_READ].max = arg->bps_rd_max;
2928 }
2929 if (arg->has_bps_wr_max) {
2930 cfg.buckets[THROTTLE_BPS_WRITE].max = arg->bps_wr_max;
2931 }
2932 if (arg->has_iops_max) {
2933 cfg.buckets[THROTTLE_OPS_TOTAL].max = arg->iops_max;
2934 }
2935 if (arg->has_iops_rd_max) {
2936 cfg.buckets[THROTTLE_OPS_READ].max = arg->iops_rd_max;
2937 }
2938 if (arg->has_iops_wr_max) {
2939 cfg.buckets[THROTTLE_OPS_WRITE].max = arg->iops_wr_max;
2940 }
2941
2942 if (arg->has_bps_max_length) {
2943 cfg.buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_max_length;
2944 }
2945 if (arg->has_bps_rd_max_length) {
2946 cfg.buckets[THROTTLE_BPS_READ].burst_length = arg->bps_rd_max_length;
2947 }
2948 if (arg->has_bps_wr_max_length) {
2949 cfg.buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_wr_max_length;
2950 }
2951 if (arg->has_iops_max_length) {
2952 cfg.buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_max_length;
2953 }
2954 if (arg->has_iops_rd_max_length) {
2955 cfg.buckets[THROTTLE_OPS_READ].burst_length = arg->iops_rd_max_length;
2956 }
2957 if (arg->has_iops_wr_max_length) {
2958 cfg.buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_wr_max_length;
2959 }
2960
2961 if (arg->has_iops_size) {
2962 cfg.op_size = arg->iops_size;
2963 }
2964
2965 if (!throttle_is_valid(&cfg, errp)) {
2966 goto out;
2967 }
2968
2969 if (throttle_enabled(&cfg)) {
2970 /* Enable I/O limits if they're not enabled yet, otherwise
2971 * just update the throttling group. */
2972 if (!blk_get_public(blk)->throttle_group_member.throttle_state) {
2973 blk_io_limits_enable(blk,
2974 arg->has_group ? arg->group :
2975 arg->has_device ? arg->device :
2976 arg->id);
2977 } else if (arg->has_group) {
2978 blk_io_limits_update_group(blk, arg->group);
2979 }
2980 /* Set the new throttling configuration */
2981 blk_set_io_limits(blk, &cfg);
2982 } else if (blk_get_public(blk)->throttle_group_member.throttle_state) {
2983 /* If all throttling settings are set to 0, disable I/O limits */
2984 blk_io_limits_disable(blk);
2985 }
2986
2987 out:
2988 aio_context_release(aio_context);
2989 }
2990
2991 void qmp_block_dirty_bitmap_add(const char *node, const char *name,
2992 bool has_granularity, uint32_t granularity,
2993 bool has_persistent, bool persistent,
2994 bool has_disabled, bool disabled,
2995 Error **errp)
2996 {
2997 BlockDriverState *bs;
2998 BdrvDirtyBitmap *bitmap;
2999 AioContext *aio_context;
3000
3001 if (!name || name[0] == '\0') {
3002 error_setg(errp, "Bitmap name cannot be empty");
3003 return;
3004 }
3005
3006 bs = bdrv_lookup_bs(node, node, errp);
3007 if (!bs) {
3008 return;
3009 }
3010
3011 aio_context = bdrv_get_aio_context(bs);
3012 aio_context_acquire(aio_context);
3013
3014 if (has_granularity) {
3015 if (granularity < 512 || !is_power_of_2(granularity)) {
3016 error_setg(errp, "Granularity must be power of 2 "
3017 "and at least 512");
3018 goto out;
3019 }
3020 } else {
3021 /* Default to cluster size, if available: */
3022 granularity = bdrv_get_default_bitmap_granularity(bs);
3023 }
3024
3025 if (!has_persistent) {
3026 persistent = false;
3027 }
3028
3029 if (!has_disabled) {
3030 disabled = false;
3031 }
3032
3033 if (persistent &&
3034 !bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp))
3035 {
3036 goto out;
3037 }
3038
3039 bitmap = bdrv_create_dirty_bitmap(bs, granularity, name, errp);
3040 if (bitmap == NULL) {
3041 goto out;
3042 }
3043
3044 if (disabled) {
3045 bdrv_disable_dirty_bitmap(bitmap);
3046 }
3047
3048 bdrv_dirty_bitmap_set_persistence(bitmap, persistent);
3049
3050 out:
3051 aio_context_release(aio_context);
3052 }
3053
3054 static BdrvDirtyBitmap *do_block_dirty_bitmap_remove(
3055 const char *node, const char *name, bool release,
3056 BlockDriverState **bitmap_bs, Error **errp)
3057 {
3058 BlockDriverState *bs;
3059 BdrvDirtyBitmap *bitmap;
3060 AioContext *aio_context;
3061
3062 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3063 if (!bitmap || !bs) {
3064 return NULL;
3065 }
3066
3067 aio_context = bdrv_get_aio_context(bs);
3068 aio_context_acquire(aio_context);
3069
3070 if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_BUSY | BDRV_BITMAP_RO,
3071 errp)) {
3072 aio_context_release(aio_context);
3073 return NULL;
3074 }
3075
3076 if (bdrv_dirty_bitmap_get_persistence(bitmap) &&
3077 bdrv_remove_persistent_dirty_bitmap(bs, name, errp) < 0)
3078 {
3079 aio_context_release(aio_context);
3080 return NULL;
3081 }
3082
3083 if (release) {
3084 bdrv_release_dirty_bitmap(bitmap);
3085 }
3086
3087 if (bitmap_bs) {
3088 *bitmap_bs = bs;
3089 }
3090
3091 aio_context_release(aio_context);
3092 return release ? NULL : bitmap;
3093 }
3094
3095 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
3096 Error **errp)
3097 {
3098 do_block_dirty_bitmap_remove(node, name, true, NULL, errp);
3099 }
3100
3101 /**
3102 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
3103 * immediately after a full backup operation.
3104 */
3105 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
3106 Error **errp)
3107 {
3108 BdrvDirtyBitmap *bitmap;
3109 BlockDriverState *bs;
3110
3111 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3112 if (!bitmap || !bs) {
3113 return;
3114 }
3115
3116 if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_DEFAULT, errp)) {
3117 return;
3118 }
3119
3120 bdrv_clear_dirty_bitmap(bitmap, NULL);
3121 }
3122
3123 void qmp_block_dirty_bitmap_enable(const char *node, const char *name,
3124 Error **errp)
3125 {
3126 BlockDriverState *bs;
3127 BdrvDirtyBitmap *bitmap;
3128
3129 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3130 if (!bitmap) {
3131 return;
3132 }
3133
3134 if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
3135 return;
3136 }
3137
3138 bdrv_enable_dirty_bitmap(bitmap);
3139 }
3140
3141 void qmp_block_dirty_bitmap_disable(const char *node, const char *name,
3142 Error **errp)
3143 {
3144 BlockDriverState *bs;
3145 BdrvDirtyBitmap *bitmap;
3146
3147 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3148 if (!bitmap) {
3149 return;
3150 }
3151
3152 if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
3153 return;
3154 }
3155
3156 bdrv_disable_dirty_bitmap(bitmap);
3157 }
3158
3159 static BdrvDirtyBitmap *do_block_dirty_bitmap_merge(
3160 const char *node, const char *target,
3161 BlockDirtyBitmapMergeSourceList *bitmaps,
3162 HBitmap **backup, Error **errp)
3163 {
3164 BlockDriverState *bs;
3165 BdrvDirtyBitmap *dst, *src, *anon;
3166 BlockDirtyBitmapMergeSourceList *lst;
3167 Error *local_err = NULL;
3168
3169 dst = block_dirty_bitmap_lookup(node, target, &bs, errp);
3170 if (!dst) {
3171 return NULL;
3172 }
3173
3174 anon = bdrv_create_dirty_bitmap(bs, bdrv_dirty_bitmap_granularity(dst),
3175 NULL, errp);
3176 if (!anon) {
3177 return NULL;
3178 }
3179
3180 for (lst = bitmaps; lst; lst = lst->next) {
3181 switch (lst->value->type) {
3182 const char *name, *node;
3183 case QTYPE_QSTRING:
3184 name = lst->value->u.local;
3185 src = bdrv_find_dirty_bitmap(bs, name);
3186 if (!src) {
3187 error_setg(errp, "Dirty bitmap '%s' not found", name);
3188 dst = NULL;
3189 goto out;
3190 }
3191 break;
3192 case QTYPE_QDICT:
3193 node = lst->value->u.external.node;
3194 name = lst->value->u.external.name;
3195 src = block_dirty_bitmap_lookup(node, name, NULL, errp);
3196 if (!src) {
3197 dst = NULL;
3198 goto out;
3199 }
3200 break;
3201 default:
3202 abort();
3203 }
3204
3205 bdrv_merge_dirty_bitmap(anon, src, NULL, &local_err);
3206 if (local_err) {
3207 error_propagate(errp, local_err);
3208 dst = NULL;
3209 goto out;
3210 }
3211 }
3212
3213 /* Merge into dst; dst is unchanged on failure. */
3214 bdrv_merge_dirty_bitmap(dst, anon, backup, errp);
3215
3216 out:
3217 bdrv_release_dirty_bitmap(anon);
3218 return dst;
3219 }
3220
3221 void qmp_block_dirty_bitmap_merge(const char *node, const char *target,
3222 BlockDirtyBitmapMergeSourceList *bitmaps,
3223 Error **errp)
3224 {
3225 do_block_dirty_bitmap_merge(node, target, bitmaps, NULL, errp);
3226 }
3227
3228 BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
3229 const char *name,
3230 Error **errp)
3231 {
3232 BdrvDirtyBitmap *bitmap;
3233 BlockDriverState *bs;
3234 BlockDirtyBitmapSha256 *ret = NULL;
3235 char *sha256;
3236
3237 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3238 if (!bitmap || !bs) {
3239 return NULL;
3240 }
3241
3242 sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
3243 if (sha256 == NULL) {
3244 return NULL;
3245 }
3246
3247 ret = g_new(BlockDirtyBitmapSha256, 1);
3248 ret->sha256 = sha256;
3249
3250 return ret;
3251 }
3252
3253 void hmp_drive_del(Monitor *mon, const QDict *qdict)
3254 {
3255 const char *id = qdict_get_str(qdict, "id");
3256 BlockBackend *blk;
3257 BlockDriverState *bs;
3258 AioContext *aio_context;
3259 Error *local_err = NULL;
3260
3261 bs = bdrv_find_node(id);
3262 if (bs) {
3263 qmp_blockdev_del(id, &local_err);
3264 if (local_err) {
3265 error_report_err(local_err);
3266 }
3267 return;
3268 }
3269
3270 blk = blk_by_name(id);
3271 if (!blk) {
3272 error_report("Device '%s' not found", id);
3273 return;
3274 }
3275
3276 if (!blk_legacy_dinfo(blk)) {
3277 error_report("Deleting device added with blockdev-add"
3278 " is not supported");
3279 return;
3280 }
3281
3282 aio_context = blk_get_aio_context(blk);
3283 aio_context_acquire(aio_context);
3284
3285 bs = blk_bs(blk);
3286 if (bs) {
3287 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
3288 error_report_err(local_err);
3289 aio_context_release(aio_context);
3290 return;
3291 }
3292
3293 blk_remove_bs(blk);
3294 }
3295
3296 /* Make the BlockBackend and the attached BlockDriverState anonymous */
3297 monitor_remove_blk(blk);
3298
3299 /* If this BlockBackend has a device attached to it, its refcount will be
3300 * decremented when the device is removed; otherwise we have to do so here.
3301 */
3302 if (blk_get_attached_dev(blk)) {
3303 /* Further I/O must not pause the guest */
3304 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
3305 BLOCKDEV_ON_ERROR_REPORT);
3306 } else {
3307 blk_unref(blk);
3308 }
3309
3310 aio_context_release(aio_context);
3311 }
3312
3313 void qmp_block_resize(bool has_device, const char *device,
3314 bool has_node_name, const char *node_name,
3315 int64_t size, Error **errp)
3316 {
3317 Error *local_err = NULL;
3318 BlockBackend *blk = NULL;
3319 BlockDriverState *bs;
3320 AioContext *aio_context;
3321 int ret;
3322
3323 bs = bdrv_lookup_bs(has_device ? device : NULL,
3324 has_node_name ? node_name : NULL,
3325 &local_err);
3326 if (local_err) {
3327 error_propagate(errp, local_err);
3328 return;
3329 }
3330
3331 aio_context = bdrv_get_aio_context(bs);
3332 aio_context_acquire(aio_context);
3333
3334 if (!bdrv_is_first_non_filter(bs)) {
3335 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
3336 goto out;
3337 }
3338
3339 if (size < 0) {
3340 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
3341 goto out;
3342 }
3343
3344 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
3345 error_setg(errp, QERR_DEVICE_IN_USE, device);
3346 goto out;
3347 }
3348
3349 blk = blk_new(bdrv_get_aio_context(bs), BLK_PERM_RESIZE, BLK_PERM_ALL);
3350 ret = blk_insert_bs(blk, bs, errp);
3351 if (ret < 0) {
3352 goto out;
3353 }
3354
3355 bdrv_drained_begin(bs);
3356 ret = blk_truncate(blk, size, false, PREALLOC_MODE_OFF, errp);
3357 bdrv_drained_end(bs);
3358
3359 out:
3360 blk_unref(blk);
3361 aio_context_release(aio_context);
3362 }
3363
3364 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
3365 bool has_base, const char *base,
3366 bool has_base_node, const char *base_node,
3367 bool has_backing_file, const char *backing_file,
3368 bool has_speed, int64_t speed,
3369 bool has_on_error, BlockdevOnError on_error,
3370 bool has_auto_finalize, bool auto_finalize,
3371 bool has_auto_dismiss, bool auto_dismiss,
3372 Error **errp)
3373 {
3374 BlockDriverState *bs, *iter;
3375 BlockDriverState *base_bs = NULL;
3376 AioContext *aio_context;
3377 Error *local_err = NULL;
3378 const char *base_name = NULL;
3379 int job_flags = JOB_DEFAULT;
3380
3381 if (!has_on_error) {
3382 on_error = BLOCKDEV_ON_ERROR_REPORT;
3383 }
3384
3385 bs = bdrv_lookup_bs(device, device, errp);
3386 if (!bs) {
3387 return;
3388 }
3389
3390 aio_context = bdrv_get_aio_context(bs);
3391 aio_context_acquire(aio_context);
3392
3393 if (has_base && has_base_node) {
3394 error_setg(errp, "'base' and 'base-node' cannot be specified "
3395 "at the same time");
3396 goto out;
3397 }
3398
3399 if (has_base) {
3400 base_bs = bdrv_find_backing_image(bs, base);
3401 if (base_bs == NULL) {
3402 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3403 goto out;
3404 }
3405 assert(bdrv_get_aio_context(base_bs) == aio_context);
3406 base_name = base;
3407 }
3408
3409 if (has_base_node) {
3410 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3411 if (!base_bs) {
3412 goto out;
3413 }
3414 if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
3415 error_setg(errp, "Node '%s' is not a backing image of '%s'",
3416 base_node, device);
3417 goto out;
3418 }
3419 assert(bdrv_get_aio_context(base_bs) == aio_context);
3420 bdrv_refresh_filename(base_bs);
3421 base_name = base_bs->filename;
3422 }
3423
3424 /* Check for op blockers in the whole chain between bs and base */
3425 for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
3426 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
3427 goto out;
3428 }
3429 }
3430
3431 /* if we are streaming the entire chain, the result will have no backing
3432 * file, and specifying one is therefore an error */
3433 if (base_bs == NULL && has_backing_file) {
3434 error_setg(errp, "backing file specified, but streaming the "
3435 "entire chain");
3436 goto out;
3437 }
3438
3439 /* backing_file string overrides base bs filename */
3440 base_name = has_backing_file ? backing_file : base_name;
3441
3442 if (has_auto_finalize && !auto_finalize) {
3443 job_flags |= JOB_MANUAL_FINALIZE;
3444 }
3445 if (has_auto_dismiss && !auto_dismiss) {
3446 job_flags |= JOB_MANUAL_DISMISS;
3447 }
3448
3449 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3450 job_flags, has_speed ? speed : 0, on_error, &local_err);
3451 if (local_err) {
3452 error_propagate(errp, local_err);
3453 goto out;
3454 }
3455
3456 trace_qmp_block_stream(bs);
3457
3458 out:
3459 aio_context_release(aio_context);
3460 }
3461
3462 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3463 bool has_base_node, const char *base_node,
3464 bool has_base, const char *base,
3465 bool has_top_node, const char *top_node,
3466 bool has_top, const char *top,
3467 bool has_backing_file, const char *backing_file,
3468 bool has_speed, int64_t speed,
3469 bool has_on_error, BlockdevOnError on_error,
3470 bool has_filter_node_name, const char *filter_node_name,
3471 bool has_auto_finalize, bool auto_finalize,
3472 bool has_auto_dismiss, bool auto_dismiss,
3473 Error **errp)
3474 {
3475 BlockDriverState *bs;
3476 BlockDriverState *iter;
3477 BlockDriverState *base_bs, *top_bs;
3478 AioContext *aio_context;
3479 Error *local_err = NULL;
3480 int job_flags = JOB_DEFAULT;
3481
3482 if (!has_speed) {
3483 speed = 0;
3484 }
3485 if (!has_on_error) {
3486 on_error = BLOCKDEV_ON_ERROR_REPORT;
3487 }
3488 if (!has_filter_node_name) {
3489 filter_node_name = NULL;
3490 }
3491 if (has_auto_finalize && !auto_finalize) {
3492 job_flags |= JOB_MANUAL_FINALIZE;
3493 }
3494 if (has_auto_dismiss && !auto_dismiss) {
3495 job_flags |= JOB_MANUAL_DISMISS;
3496 }
3497
3498 /* Important Note:
3499 * libvirt relies on the DeviceNotFound error class in order to probe for
3500 * live commit feature versions; for this to work, we must make sure to
3501 * perform the device lookup before any generic errors that may occur in a
3502 * scenario in which all optional arguments are omitted. */
3503 bs = qmp_get_root_bs(device, &local_err);
3504 if (!bs) {
3505 bs = bdrv_lookup_bs(device, device, NULL);
3506 if (!bs) {
3507 error_free(local_err);
3508 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3509 "Device '%s' not found", device);
3510 } else {
3511 error_propagate(errp, local_err);
3512 }
3513 return;
3514 }
3515
3516 aio_context = bdrv_get_aio_context(bs);
3517 aio_context_acquire(aio_context);
3518
3519 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3520 goto out;
3521 }
3522
3523 /* default top_bs is the active layer */
3524 top_bs = bs;
3525
3526 if (has_top_node && has_top) {
3527 error_setg(errp, "'top-node' and 'top' are mutually exclusive");
3528 goto out;
3529 } else if (has_top_node) {
3530 top_bs = bdrv_lookup_bs(NULL, top_node, errp);
3531 if (top_bs == NULL) {
3532 goto out;
3533 }
3534 if (!bdrv_chain_contains(bs, top_bs)) {
3535 error_setg(errp, "'%s' is not in this backing file chain",
3536 top_node);
3537 goto out;
3538 }
3539 } else if (has_top && top) {
3540 /* This strcmp() is just a shortcut, there is no need to
3541 * refresh @bs's filename. If it mismatches,
3542 * bdrv_find_backing_image() will do the refresh and may still
3543 * return @bs. */
3544 if (strcmp(bs->filename, top) != 0) {
3545 top_bs = bdrv_find_backing_image(bs, top);
3546 }
3547 }
3548
3549 if (top_bs == NULL) {
3550 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3551 goto out;
3552 }
3553
3554 assert(bdrv_get_aio_context(top_bs) == aio_context);
3555
3556 if (has_base_node && has_base) {
3557 error_setg(errp, "'base-node' and 'base' are mutually exclusive");
3558 goto out;
3559 } else if (has_base_node) {
3560 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3561 if (base_bs == NULL) {
3562 goto out;
3563 }
3564 if (!bdrv_chain_contains(top_bs, base_bs)) {
3565 error_setg(errp, "'%s' is not in this backing file chain",
3566 base_node);
3567 goto out;
3568 }
3569 } else if (has_base && base) {
3570 base_bs = bdrv_find_backing_image(top_bs, base);
3571 } else {
3572 base_bs = bdrv_find_base(top_bs);
3573 }
3574
3575 if (base_bs == NULL) {
3576 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3577 goto out;
3578 }
3579
3580 assert(bdrv_get_aio_context(base_bs) == aio_context);
3581
3582 for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
3583 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3584 goto out;
3585 }
3586 }
3587
3588 /* Do not allow attempts to commit an image into itself */
3589 if (top_bs == base_bs) {
3590 error_setg(errp, "cannot commit an image into itself");
3591 goto out;
3592 }
3593
3594 if (top_bs == bs) {
3595 if (has_backing_file) {
3596 error_setg(errp, "'backing-file' specified,"
3597 " but 'top' is the active layer");
3598 goto out;
3599 }
3600 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
3601 job_flags, speed, on_error,
3602 filter_node_name, NULL, NULL, false, &local_err);
3603 } else {
3604 BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
3605 if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3606 goto out;
3607 }
3608 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, job_flags,
3609 speed, on_error, has_backing_file ? backing_file : NULL,
3610 filter_node_name, &local_err);
3611 }
3612 if (local_err != NULL) {
3613 error_propagate(errp, local_err);
3614 goto out;
3615 }
3616
3617 out:
3618 aio_context_release(aio_context);
3619 }
3620
3621 /* Common QMP interface for drive-backup and blockdev-backup */
3622 static BlockJob *do_backup_common(BackupCommon *backup,
3623 BlockDriverState *bs,
3624 BlockDriverState *target_bs,
3625 AioContext *aio_context,
3626 JobTxn *txn, Error **errp)
3627 {
3628 BlockJob *job = NULL;
3629 BdrvDirtyBitmap *bmap = NULL;
3630 int job_flags = JOB_DEFAULT;
3631
3632 if (!backup->has_speed) {
3633 backup->speed = 0;
3634 }
3635 if (!backup->has_on_source_error) {
3636 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3637 }
3638 if (!backup->has_on_target_error) {
3639 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3640 }
3641 if (!backup->has_job_id) {
3642 backup->job_id = NULL;
3643 }
3644 if (!backup->has_auto_finalize) {
3645 backup->auto_finalize = true;
3646 }
3647 if (!backup->has_auto_dismiss) {
3648 backup->auto_dismiss = true;
3649 }
3650 if (!backup->has_compress) {
3651 backup->compress = false;
3652 }
3653
3654 if ((backup->sync == MIRROR_SYNC_MODE_BITMAP) ||
3655 (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL)) {
3656 /* done before desugaring 'incremental' to print the right message */
3657 if (!backup->has_bitmap) {
3658 error_setg(errp, "must provide a valid bitmap name for "
3659 "'%s' sync mode", MirrorSyncMode_str(backup->sync));
3660 return NULL;
3661 }
3662 }
3663
3664 if (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL) {
3665 if (backup->has_bitmap_mode &&
3666 backup->bitmap_mode != BITMAP_SYNC_MODE_ON_SUCCESS) {
3667 error_setg(errp, "Bitmap sync mode must be '%s' "
3668 "when using sync mode '%s'",
3669 BitmapSyncMode_str(BITMAP_SYNC_MODE_ON_SUCCESS),
3670 MirrorSyncMode_str(backup->sync));
3671 return NULL;
3672 }
3673 backup->has_bitmap_mode = true;
3674 backup->sync = MIRROR_SYNC_MODE_BITMAP;
3675 backup->bitmap_mode = BITMAP_SYNC_MODE_ON_SUCCESS;
3676 }
3677
3678 if (backup->has_bitmap) {
3679 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3680 if (!bmap) {
3681 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3682 return NULL;
3683 }
3684 if (!backup->has_bitmap_mode) {
3685 error_setg(errp, "Bitmap sync mode must be given "
3686 "when providing a bitmap");
3687 return NULL;
3688 }
3689 if (bdrv_dirty_bitmap_check(bmap, BDRV_BITMAP_ALLOW_RO, errp)) {
3690 return NULL;
3691 }
3692
3693 /* This does not produce a useful bitmap artifact: */
3694 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3695 error_setg(errp, "sync mode '%s' does not produce meaningful bitmap"
3696 " outputs", MirrorSyncMode_str(backup->sync));
3697 return NULL;
3698 }
3699
3700 /* If the bitmap isn't used for input or output, this is useless: */
3701 if (backup->bitmap_mode == BITMAP_SYNC_MODE_NEVER &&
3702 backup->sync != MIRROR_SYNC_MODE_BITMAP) {
3703 error_setg(errp, "Bitmap sync mode '%s' has no meaningful effect"
3704 " when combined with sync mode '%s'",
3705 BitmapSyncMode_str(backup->bitmap_mode),
3706 MirrorSyncMode_str(backup->sync));
3707 return NULL;
3708 }
3709 }
3710
3711 if (!backup->has_bitmap && backup->has_bitmap_mode) {
3712 error_setg(errp, "Cannot specify bitmap sync mode without a bitmap");
3713 return NULL;
3714 }
3715
3716 if (!backup->auto_finalize) {
3717 job_flags |= JOB_MANUAL_FINALIZE;
3718 }
3719 if (!backup->auto_dismiss) {
3720 job_flags |= JOB_MANUAL_DISMISS;
3721 }
3722
3723 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3724 backup->sync, bmap, backup->bitmap_mode,
3725 backup->compress,
3726 backup->filter_node_name,
3727 backup->on_source_error,
3728 backup->on_target_error,
3729 job_flags, NULL, NULL, txn, errp);
3730 return job;
3731 }
3732
3733 void qmp_drive_backup(DriveBackup *backup, Error **errp)
3734 {
3735 TransactionAction action = {
3736 .type = TRANSACTION_ACTION_KIND_DRIVE_BACKUP,
3737 .u.drive_backup.data = backup,
3738 };
3739 blockdev_do_action(&action, errp);
3740 }
3741
3742 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3743 {
3744 return bdrv_named_nodes_list(errp);
3745 }
3746
3747 XDbgBlockGraph *qmp_x_debug_query_block_graph(Error **errp)
3748 {
3749 return bdrv_get_xdbg_block_graph(errp);
3750 }
3751
3752 void qmp_blockdev_backup(BlockdevBackup *backup, Error **errp)
3753 {
3754 TransactionAction action = {
3755 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP,
3756 .u.blockdev_backup.data = backup,
3757 };
3758 blockdev_do_action(&action, errp);
3759 }
3760
3761 /* Parameter check and block job starting for drive mirroring.
3762 * Caller should hold @device and @target's aio context (must be the same).
3763 **/
3764 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3765 BlockDriverState *target,
3766 bool has_replaces, const char *replaces,
3767 enum MirrorSyncMode sync,
3768 BlockMirrorBackingMode backing_mode,
3769 bool zero_target,
3770 bool has_speed, int64_t speed,
3771 bool has_granularity, uint32_t granularity,
3772 bool has_buf_size, int64_t buf_size,
3773 bool has_on_source_error,
3774 BlockdevOnError on_source_error,
3775 bool has_on_target_error,
3776 BlockdevOnError on_target_error,
3777 bool has_unmap, bool unmap,
3778 bool has_filter_node_name,
3779 const char *filter_node_name,
3780 bool has_copy_mode, MirrorCopyMode copy_mode,
3781 bool has_auto_finalize, bool auto_finalize,
3782 bool has_auto_dismiss, bool auto_dismiss,
3783 Error **errp)
3784 {
3785 int job_flags = JOB_DEFAULT;
3786
3787 if (!has_speed) {
3788 speed = 0;
3789 }
3790 if (!has_on_source_error) {
3791 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3792 }
3793 if (!has_on_target_error) {
3794 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3795 }
3796 if (!has_granularity) {
3797 granularity = 0;
3798 }
3799 if (!has_buf_size) {
3800 buf_size = 0;
3801 }
3802 if (!has_unmap) {
3803 unmap = true;
3804 }
3805 if (!has_filter_node_name) {
3806 filter_node_name = NULL;
3807 }
3808 if (!has_copy_mode) {
3809 copy_mode = MIRROR_COPY_MODE_BACKGROUND;
3810 }
3811 if (has_auto_finalize && !auto_finalize) {
3812 job_flags |= JOB_MANUAL_FINALIZE;
3813 }
3814 if (has_auto_dismiss && !auto_dismiss) {
3815 job_flags |= JOB_MANUAL_DISMISS;
3816 }
3817
3818 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3819 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3820 "a value in range [512B, 64MB]");
3821 return;
3822 }
3823 if (granularity & (granularity - 1)) {
3824 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3825 "power of 2");
3826 return;
3827 }
3828
3829 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3830 return;
3831 }
3832 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3833 return;
3834 }
3835
3836 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3837 sync = MIRROR_SYNC_MODE_FULL;
3838 }
3839
3840 if (has_replaces) {
3841 BlockDriverState *to_replace_bs;
3842 AioContext *replace_aio_context;
3843 int64_t bs_size, replace_size;
3844
3845 bs_size = bdrv_getlength(bs);
3846 if (bs_size < 0) {
3847 error_setg_errno(errp, -bs_size, "Failed to query device's size");
3848 return;
3849 }
3850
3851 to_replace_bs = check_to_replace_node(bs, replaces, errp);
3852 if (!to_replace_bs) {
3853 return;
3854 }
3855
3856 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3857 aio_context_acquire(replace_aio_context);
3858 replace_size = bdrv_getlength(to_replace_bs);
3859 aio_context_release(replace_aio_context);
3860
3861 if (replace_size < 0) {
3862 error_setg_errno(errp, -replace_size,
3863 "Failed to query the replacement node's size");
3864 return;
3865 }
3866 if (bs_size != replace_size) {
3867 error_setg(errp, "cannot replace image with a mirror image of "
3868 "different size");
3869 return;
3870 }
3871 }
3872
3873 /* pass the node name to replace to mirror start since it's loose coupling
3874 * and will allow to check whether the node still exist at mirror completion
3875 */
3876 mirror_start(job_id, bs, target,
3877 has_replaces ? replaces : NULL, job_flags,
3878 speed, granularity, buf_size, sync, backing_mode, zero_target,
3879 on_source_error, on_target_error, unmap, filter_node_name,
3880 copy_mode, errp);
3881 }
3882
3883 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3884 {
3885 BlockDriverState *bs;
3886 BlockDriverState *source, *target_bs;
3887 AioContext *aio_context;
3888 AioContext *old_context;
3889 BlockMirrorBackingMode backing_mode;
3890 Error *local_err = NULL;
3891 QDict *options = NULL;
3892 int flags;
3893 int64_t size;
3894 const char *format = arg->format;
3895 bool zero_target;
3896 int ret;
3897
3898 bs = qmp_get_root_bs(arg->device, errp);
3899 if (!bs) {
3900 return;
3901 }
3902
3903 /* Early check to avoid creating target */
3904 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3905 return;
3906 }
3907
3908 aio_context = bdrv_get_aio_context(bs);
3909 aio_context_acquire(aio_context);
3910
3911 if (!arg->has_mode) {
3912 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3913 }
3914
3915 if (!arg->has_format) {
3916 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3917 ? NULL : bs->drv->format_name);
3918 }
3919
3920 flags = bs->open_flags | BDRV_O_RDWR;
3921 source = backing_bs(bs);
3922 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3923 arg->sync = MIRROR_SYNC_MODE_FULL;
3924 }
3925 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3926 source = bs;
3927 }
3928
3929 size = bdrv_getlength(bs);
3930 if (size < 0) {
3931 error_setg_errno(errp, -size, "bdrv_getlength failed");
3932 goto out;
3933 }
3934
3935 if (arg->has_replaces) {
3936 if (!arg->has_node_name) {
3937 error_setg(errp, "a node-name must be provided when replacing a"
3938 " named node of the graph");
3939 goto out;
3940 }
3941 }
3942
3943 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3944 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3945 } else {
3946 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3947 }
3948
3949 /* Don't open backing image in create() */
3950 flags |= BDRV_O_NO_BACKING;
3951
3952 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3953 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3954 {
3955 /* create new image w/o backing file */
3956 assert(format);
3957 bdrv_img_create(arg->target, format,
3958 NULL, NULL, NULL, size, flags, false, &local_err);
3959 } else {
3960 switch (arg->mode) {
3961 case NEW_IMAGE_MODE_EXISTING:
3962 break;
3963 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3964 /* create new image with backing file */
3965 bdrv_refresh_filename(source);
3966 bdrv_img_create(arg->target, format,
3967 source->filename,
3968 source->drv->format_name,
3969 NULL, size, flags, false, &local_err);
3970 break;
3971 default:
3972 abort();
3973 }
3974 }
3975
3976 if (local_err) {
3977 error_propagate(errp, local_err);
3978 goto out;
3979 }
3980
3981 options = qdict_new();
3982 if (arg->has_node_name) {
3983 qdict_put_str(options, "node-name", arg->node_name);
3984 }
3985 if (format) {
3986 qdict_put_str(options, "driver", format);
3987 }
3988
3989 /* Mirroring takes care of copy-on-write using the source's backing
3990 * file.
3991 */
3992 target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
3993 if (!target_bs) {
3994 goto out;
3995 }
3996
3997 zero_target = (arg->sync == MIRROR_SYNC_MODE_FULL &&
3998 (arg->mode == NEW_IMAGE_MODE_EXISTING ||
3999 !bdrv_has_zero_init(target_bs)));
4000
4001
4002 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
4003 old_context = bdrv_get_aio_context(target_bs);
4004 aio_context_release(aio_context);
4005 aio_context_acquire(old_context);
4006
4007 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
4008 if (ret < 0) {
4009 bdrv_unref(target_bs);
4010 aio_context_release(old_context);
4011 return;
4012 }
4013
4014 aio_context_release(old_context);
4015 aio_context_acquire(aio_context);
4016
4017 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
4018 arg->has_replaces, arg->replaces, arg->sync,
4019 backing_mode, zero_target,
4020 arg->has_speed, arg->speed,
4021 arg->has_granularity, arg->granularity,
4022 arg->has_buf_size, arg->buf_size,
4023 arg->has_on_source_error, arg->on_source_error,
4024 arg->has_on_target_error, arg->on_target_error,
4025 arg->has_unmap, arg->unmap,
4026 false, NULL,
4027 arg->has_copy_mode, arg->copy_mode,
4028 arg->has_auto_finalize, arg->auto_finalize,
4029 arg->has_auto_dismiss, arg->auto_dismiss,
4030 &local_err);
4031 bdrv_unref(target_bs);
4032 error_propagate(errp, local_err);
4033 out:
4034 aio_context_release(aio_context);
4035 }
4036
4037 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
4038 const char *device, const char *target,
4039 bool has_replaces, const char *replaces,
4040 MirrorSyncMode sync,
4041 bool has_speed, int64_t speed,
4042 bool has_granularity, uint32_t granularity,
4043 bool has_buf_size, int64_t buf_size,
4044 bool has_on_source_error,
4045 BlockdevOnError on_source_error,
4046 bool has_on_target_error,
4047 BlockdevOnError on_target_error,
4048 bool has_filter_node_name,
4049 const char *filter_node_name,
4050 bool has_copy_mode, MirrorCopyMode copy_mode,
4051 bool has_auto_finalize, bool auto_finalize,
4052 bool has_auto_dismiss, bool auto_dismiss,
4053 Error **errp)
4054 {
4055 BlockDriverState *bs;
4056 BlockDriverState *target_bs;
4057 AioContext *aio_context;
4058 AioContext *old_context;
4059 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
4060 Error *local_err = NULL;
4061 bool zero_target;
4062 int ret;
4063
4064 bs = qmp_get_root_bs(device, errp);
4065 if (!bs) {
4066 return;
4067 }
4068
4069 target_bs = bdrv_lookup_bs(target, target, errp);
4070 if (!target_bs) {
4071 return;
4072 }
4073
4074 zero_target = (sync == MIRROR_SYNC_MODE_FULL);
4075
4076 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
4077 old_context = bdrv_get_aio_context(target_bs);
4078 aio_context = bdrv_get_aio_context(bs);
4079 aio_context_acquire(old_context);
4080
4081 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
4082
4083 aio_context_release(old_context);
4084 aio_context_acquire(aio_context);
4085
4086 if (ret < 0) {
4087 goto out;
4088 }
4089
4090 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
4091 has_replaces, replaces, sync, backing_mode,
4092 zero_target, has_speed, speed,
4093 has_granularity, granularity,
4094 has_buf_size, buf_size,
4095 has_on_source_error, on_source_error,
4096 has_on_target_error, on_target_error,
4097 true, true,
4098 has_filter_node_name, filter_node_name,
4099 has_copy_mode, copy_mode,
4100 has_auto_finalize, auto_finalize,
4101 has_auto_dismiss, auto_dismiss,
4102 &local_err);
4103 error_propagate(errp, local_err);
4104 out:
4105 aio_context_release(aio_context);
4106 }
4107
4108 /* Get a block job using its ID and acquire its AioContext */
4109 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
4110 Error **errp)
4111 {
4112 BlockJob *job;
4113
4114 assert(id != NULL);
4115
4116 *aio_context = NULL;
4117
4118 job = block_job_get(id);
4119
4120 if (!job) {
4121 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
4122 "Block job '%s' not found", id);
4123 return NULL;
4124 }
4125
4126 *aio_context = blk_get_aio_context(job->blk);
4127 aio_context_acquire(*aio_context);
4128
4129 return job;
4130 }
4131
4132 void qmp_block_job_set_speed(const char *device, int64_t speed, Error **errp)
4133 {
4134 AioContext *aio_context;
4135 BlockJob *job = find_block_job(device, &aio_context, errp);
4136
4137 if (!job) {
4138 return;
4139 }
4140
4141 block_job_set_speed(job, speed, errp);
4142 aio_context_release(aio_context);
4143 }
4144
4145 void qmp_block_job_cancel(const char *device,
4146 bool has_force, bool force, Error **errp)
4147 {
4148 AioContext *aio_context;
4149 BlockJob *job = find_block_job(device, &aio_context, errp);
4150
4151 if (!job) {
4152 return;
4153 }
4154
4155 if (!has_force) {
4156 force = false;
4157 }
4158
4159 if (job_user_paused(&job->job) && !force) {
4160 error_setg(errp, "The block job for device '%s' is currently paused",
4161 device);
4162 goto out;
4163 }
4164
4165 trace_qmp_block_job_cancel(job);
4166 job_user_cancel(&job->job, force, errp);
4167 out:
4168 aio_context_release(aio_context);
4169 }
4170
4171 void qmp_block_job_pause(const char *device, Error **errp)
4172 {
4173 AioContext *aio_context;
4174 BlockJob *job = find_block_job(device, &aio_context, errp);
4175
4176 if (!job) {
4177 return;
4178 }
4179
4180 trace_qmp_block_job_pause(job);
4181 job_user_pause(&job->job, errp);
4182 aio_context_release(aio_context);
4183 }
4184
4185 void qmp_block_job_resume(const char *device, Error **errp)
4186 {
4187 AioContext *aio_context;
4188 BlockJob *job = find_block_job(device, &aio_context, errp);
4189
4190 if (!job) {
4191 return;
4192 }
4193
4194 trace_qmp_block_job_resume(job);
4195 job_user_resume(&job->job, errp);
4196 aio_context_release(aio_context);
4197 }
4198
4199 void qmp_block_job_complete(const char *device, Error **errp)
4200 {
4201 AioContext *aio_context;
4202 BlockJob *job = find_block_job(device, &aio_context, errp);
4203
4204 if (!job) {
4205 return;
4206 }
4207
4208 trace_qmp_block_job_complete(job);
4209 job_complete(&job->job, errp);
4210 aio_context_release(aio_context);
4211 }
4212
4213 void qmp_block_job_finalize(const char *id, Error **errp)
4214 {
4215 AioContext *aio_context;
4216 BlockJob *job = find_block_job(id, &aio_context, errp);
4217
4218 if (!job) {
4219 return;
4220 }
4221
4222 trace_qmp_block_job_finalize(job);
4223 job_finalize(&job->job, errp);
4224 aio_context_release(aio_context);
4225 }
4226
4227 void qmp_block_job_dismiss(const char *id, Error **errp)
4228 {
4229 AioContext *aio_context;
4230 BlockJob *bjob = find_block_job(id, &aio_context, errp);
4231 Job *job;
4232
4233 if (!bjob) {
4234 return;
4235 }
4236
4237 trace_qmp_block_job_dismiss(bjob);
4238 job = &bjob->job;
4239 job_dismiss(&job, errp);
4240 aio_context_release(aio_context);
4241 }
4242
4243 void qmp_change_backing_file(const char *device,
4244 const char *image_node_name,
4245 const char *backing_file,
4246 Error **errp)
4247 {
4248 BlockDriverState *bs = NULL;
4249 AioContext *aio_context;
4250 BlockDriverState *image_bs = NULL;
4251 Error *local_err = NULL;
4252 bool ro;
4253 int ret;
4254
4255 bs = qmp_get_root_bs(device, errp);
4256 if (!bs) {
4257 return;
4258 }
4259
4260 aio_context = bdrv_get_aio_context(bs);
4261 aio_context_acquire(aio_context);
4262
4263 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
4264 if (local_err) {
4265 error_propagate(errp, local_err);
4266 goto out;
4267 }
4268
4269 if (!image_bs) {
4270 error_setg(errp, "image file not found");
4271 goto out;
4272 }
4273
4274 if (bdrv_find_base(image_bs) == image_bs) {
4275 error_setg(errp, "not allowing backing file change on an image "
4276 "without a backing file");
4277 goto out;
4278 }
4279
4280 /* even though we are not necessarily operating on bs, we need it to
4281 * determine if block ops are currently prohibited on the chain */
4282 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
4283 goto out;
4284 }
4285
4286 /* final sanity check */
4287 if (!bdrv_chain_contains(bs, image_bs)) {
4288 error_setg(errp, "'%s' and image file are not in the same chain",
4289 device);
4290 goto out;
4291 }
4292
4293 /* if not r/w, reopen to make r/w */
4294 ro = bdrv_is_read_only(image_bs);
4295
4296 if (ro) {
4297 if (bdrv_reopen_set_read_only(image_bs, false, errp) != 0) {
4298 goto out;
4299 }
4300 }
4301
4302 ret = bdrv_change_backing_file(image_bs, backing_file,
4303 image_bs->drv ? image_bs->drv->format_name : "");
4304
4305 if (ret < 0) {
4306 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
4307 backing_file);
4308 /* don't exit here, so we can try to restore open flags if
4309 * appropriate */
4310 }
4311
4312 if (ro) {
4313 bdrv_reopen_set_read_only(image_bs, true, &local_err);
4314 error_propagate(errp, local_err);
4315 }
4316
4317 out:
4318 aio_context_release(aio_context);
4319 }
4320
4321 void hmp_drive_add_node(Monitor *mon, const char *optstr)
4322 {
4323 QemuOpts *opts;
4324 QDict *qdict;
4325 Error *local_err = NULL;
4326
4327 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
4328 if (!opts) {
4329 return;
4330 }
4331
4332 qdict = qemu_opts_to_qdict(opts, NULL);
4333
4334 if (!qdict_get_try_str(qdict, "node-name")) {
4335 qobject_unref(qdict);
4336 error_report("'node-name' needs to be specified");
4337 goto out;
4338 }
4339
4340 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
4341 if (!bs) {
4342 error_report_err(local_err);
4343 goto out;
4344 }
4345
4346 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4347
4348 out:
4349 qemu_opts_del(opts);
4350 }
4351
4352 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
4353 {
4354 BlockDriverState *bs;
4355 QObject *obj;
4356 Visitor *v = qobject_output_visitor_new(&obj);
4357 QDict *qdict;
4358 Error *local_err = NULL;
4359
4360 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
4361 if (local_err) {
4362 error_propagate(errp, local_err);
4363 goto fail;
4364 }
4365
4366 visit_complete(v, &obj);
4367 qdict = qobject_to(QDict, obj);
4368
4369 qdict_flatten(qdict);
4370
4371 if (!qdict_get_try_str(qdict, "node-name")) {
4372 error_setg(errp, "'node-name' must be specified for the root node");
4373 goto fail;
4374 }
4375
4376 bs = bds_tree_init(qdict, errp);
4377 if (!bs) {
4378 goto fail;
4379 }
4380
4381 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4382
4383 fail:
4384 visit_free(v);
4385 }
4386
4387 void qmp_x_blockdev_reopen(BlockdevOptions *options, Error **errp)
4388 {
4389 BlockDriverState *bs;
4390 AioContext *ctx;
4391 QObject *obj;
4392 Visitor *v = qobject_output_visitor_new(&obj);
4393 Error *local_err = NULL;
4394 BlockReopenQueue *queue;
4395 QDict *qdict;
4396
4397 /* Check for the selected node name */
4398 if (!options->has_node_name) {
4399 error_setg(errp, "Node name not specified");
4400 goto fail;
4401 }
4402
4403 bs = bdrv_find_node(options->node_name);
4404 if (!bs) {
4405 error_setg(errp, "Cannot find node named '%s'", options->node_name);
4406 goto fail;
4407 }
4408
4409 /* Put all options in a QDict and flatten it */
4410 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
4411 if (local_err) {
4412 error_propagate(errp, local_err);
4413 goto fail;
4414 }
4415
4416 visit_complete(v, &obj);
4417 qdict = qobject_to(QDict, obj);
4418
4419 qdict_flatten(qdict);
4420
4421 /* Perform the reopen operation */
4422 ctx = bdrv_get_aio_context(bs);
4423 aio_context_acquire(ctx);
4424 bdrv_subtree_drained_begin(bs);
4425 queue = bdrv_reopen_queue(NULL, bs, qdict, false);
4426 bdrv_reopen_multiple(queue, errp);
4427 bdrv_subtree_drained_end(bs);
4428 aio_context_release(ctx);
4429
4430 fail:
4431 visit_free(v);
4432 }
4433
4434 void qmp_blockdev_del(const char *node_name, Error **errp)
4435 {
4436 AioContext *aio_context;
4437 BlockDriverState *bs;
4438
4439 bs = bdrv_find_node(node_name);
4440 if (!bs) {
4441 error_setg(errp, "Cannot find node %s", node_name);
4442 return;
4443 }
4444 if (bdrv_has_blk(bs)) {
4445 error_setg(errp, "Node %s is in use", node_name);
4446 return;
4447 }
4448 aio_context = bdrv_get_aio_context(bs);
4449 aio_context_acquire(aio_context);
4450
4451 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4452 goto out;
4453 }
4454
4455 if (!QTAILQ_IN_USE(bs, monitor_list)) {
4456 error_setg(errp, "Node %s is not owned by the monitor",
4457 bs->node_name);
4458 goto out;
4459 }
4460
4461 if (bs->refcnt > 1) {
4462 error_setg(errp, "Block device %s is in use",
4463 bdrv_get_device_or_node_name(bs));
4464 goto out;
4465 }
4466
4467 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4468 bdrv_unref(bs);
4469
4470 out:
4471 aio_context_release(aio_context);
4472 }
4473
4474 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
4475 const char *child_name)
4476 {
4477 BdrvChild *child;
4478
4479 QLIST_FOREACH(child, &parent_bs->children, next) {
4480 if (strcmp(child->name, child_name) == 0) {
4481 return child;
4482 }
4483 }
4484
4485 return NULL;
4486 }
4487
4488 void qmp_x_blockdev_change(const char *parent, bool has_child,
4489 const char *child, bool has_node,
4490 const char *node, Error **errp)
4491 {
4492 BlockDriverState *parent_bs, *new_bs = NULL;
4493 BdrvChild *p_child;
4494
4495 parent_bs = bdrv_lookup_bs(parent, parent, errp);
4496 if (!parent_bs) {
4497 return;
4498 }
4499
4500 if (has_child == has_node) {
4501 if (has_child) {
4502 error_setg(errp, "The parameters child and node are in conflict");
4503 } else {
4504 error_setg(errp, "Either child or node must be specified");
4505 }
4506 return;
4507 }
4508
4509 if (has_child) {
4510 p_child = bdrv_find_child(parent_bs, child);
4511 if (!p_child) {
4512 error_setg(errp, "Node '%s' does not have child '%s'",
4513 parent, child);
4514 return;
4515 }
4516 bdrv_del_child(parent_bs, p_child, errp);
4517 }
4518
4519 if (has_node) {
4520 new_bs = bdrv_find_node(node);
4521 if (!new_bs) {
4522 error_setg(errp, "Node '%s' not found", node);
4523 return;
4524 }
4525 bdrv_add_child(parent_bs, new_bs, errp);
4526 }
4527 }
4528
4529 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4530 {
4531 BlockJobInfoList *head = NULL, **p_next = &head;
4532 BlockJob *job;
4533
4534 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4535 BlockJobInfoList *elem;
4536 AioContext *aio_context;
4537
4538 if (block_job_is_internal(job)) {
4539 continue;
4540 }
4541 elem = g_new0(BlockJobInfoList, 1);
4542 aio_context = blk_get_aio_context(job->blk);
4543 aio_context_acquire(aio_context);
4544 elem->value = block_job_query(job, errp);
4545 aio_context_release(aio_context);
4546 if (!elem->value) {
4547 g_free(elem);
4548 qapi_free_BlockJobInfoList(head);
4549 return NULL;
4550 }
4551 *p_next = elem;
4552 p_next = &elem->next;
4553 }
4554
4555 return head;
4556 }
4557
4558 void qmp_x_blockdev_set_iothread(const char *node_name, StrOrNull *iothread,
4559 bool has_force, bool force, Error **errp)
4560 {
4561 AioContext *old_context;
4562 AioContext *new_context;
4563 BlockDriverState *bs;
4564
4565 bs = bdrv_find_node(node_name);
4566 if (!bs) {
4567 error_setg(errp, "Cannot find node %s", node_name);
4568 return;
4569 }
4570
4571 /* Protects against accidents. */
4572 if (!(has_force && force) && bdrv_has_blk(bs)) {
4573 error_setg(errp, "Node %s is associated with a BlockBackend and could "
4574 "be in use (use force=true to override this check)",
4575 node_name);
4576 return;
4577 }
4578
4579 if (iothread->type == QTYPE_QSTRING) {
4580 IOThread *obj = iothread_by_id(iothread->u.s);
4581 if (!obj) {
4582 error_setg(errp, "Cannot find iothread %s", iothread->u.s);
4583 return;
4584 }
4585
4586 new_context = iothread_get_aio_context(obj);
4587 } else {
4588 new_context = qemu_get_aio_context();
4589 }
4590
4591 old_context = bdrv_get_aio_context(bs);
4592 aio_context_acquire(old_context);
4593
4594 bdrv_try_set_aio_context(bs, new_context, errp);
4595
4596 aio_context_release(old_context);
4597 }
4598
4599 void qmp_block_latency_histogram_set(
4600 const char *id,
4601 bool has_boundaries, uint64List *boundaries,
4602 bool has_boundaries_read, uint64List *boundaries_read,
4603 bool has_boundaries_write, uint64List *boundaries_write,
4604 bool has_boundaries_flush, uint64List *boundaries_flush,
4605 Error **errp)
4606 {
4607 BlockBackend *blk = qmp_get_blk(NULL, id, errp);
4608 BlockAcctStats *stats;
4609 int ret;
4610
4611 if (!blk) {
4612 return;
4613 }
4614
4615 stats = blk_get_stats(blk);
4616
4617 if (!has_boundaries && !has_boundaries_read && !has_boundaries_write &&
4618 !has_boundaries_flush)
4619 {
4620 block_latency_histograms_clear(stats);
4621 return;
4622 }
4623
4624 if (has_boundaries || has_boundaries_read) {
4625 ret = block_latency_histogram_set(
4626 stats, BLOCK_ACCT_READ,
4627 has_boundaries_read ? boundaries_read : boundaries);
4628 if (ret) {
4629 error_setg(errp, "Device '%s' set read boundaries fail", id);
4630 return;
4631 }
4632 }
4633
4634 if (has_boundaries || has_boundaries_write) {
4635 ret = block_latency_histogram_set(
4636 stats, BLOCK_ACCT_WRITE,
4637 has_boundaries_write ? boundaries_write : boundaries);
4638 if (ret) {
4639 error_setg(errp, "Device '%s' set write boundaries fail", id);
4640 return;
4641 }
4642 }
4643
4644 if (has_boundaries || has_boundaries_flush) {
4645 ret = block_latency_histogram_set(
4646 stats, BLOCK_ACCT_FLUSH,
4647 has_boundaries_flush ? boundaries_flush : boundaries);
4648 if (ret) {
4649 error_setg(errp, "Device '%s' set flush boundaries fail", id);
4650 return;
4651 }
4652 }
4653 }
4654
4655 QemuOptsList qemu_common_drive_opts = {
4656 .name = "drive",
4657 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4658 .desc = {
4659 {
4660 .name = "snapshot",
4661 .type = QEMU_OPT_BOOL,
4662 .help = "enable/disable snapshot mode",
4663 },{
4664 .name = "aio",
4665 .type = QEMU_OPT_STRING,
4666 .help = "host AIO implementation (threads, native, io_uring)",
4667 },{
4668 .name = BDRV_OPT_CACHE_WB,
4669 .type = QEMU_OPT_BOOL,
4670 .help = "Enable writeback mode",
4671 },{
4672 .name = "format",
4673 .type = QEMU_OPT_STRING,
4674 .help = "disk format (raw, qcow2, ...)",
4675 },{
4676 .name = "rerror",
4677 .type = QEMU_OPT_STRING,
4678 .help = "read error action",
4679 },{
4680 .name = "werror",
4681 .type = QEMU_OPT_STRING,
4682 .help = "write error action",
4683 },{
4684 .name = BDRV_OPT_READ_ONLY,
4685 .type = QEMU_OPT_BOOL,
4686 .help = "open drive file as read-only",
4687 },
4688
4689 THROTTLE_OPTS,
4690
4691 {
4692 .name = "throttling.group",
4693 .type = QEMU_OPT_STRING,
4694 .help = "name of the block throttling group",
4695 },{
4696 .name = "copy-on-read",
4697 .type = QEMU_OPT_BOOL,
4698 .help = "copy read data from backing file into image file",
4699 },{
4700 .name = "detect-zeroes",
4701 .type = QEMU_OPT_STRING,
4702 .help = "try to optimize zero writes (off, on, unmap)",
4703 },{
4704 .name = "stats-account-invalid",
4705 .type = QEMU_OPT_BOOL,
4706 .help = "whether to account for invalid I/O operations "
4707 "in the statistics",
4708 },{
4709 .name = "stats-account-failed",
4710 .type = QEMU_OPT_BOOL,
4711 .help = "whether to account for failed I/O operations "
4712 "in the statistics",
4713 },
4714 { /* end of list */ }
4715 },
4716 };
4717
4718 QemuOptsList qemu_drive_opts = {
4719 .name = "drive",
4720 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4721 .desc = {
4722 /*
4723 * no elements => accept any params
4724 * validation will happen later
4725 */
4726 { /* end of list */ }
4727 },
4728 };