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