]> git.proxmox.com Git - mirror_qemu.git/blob - blockdev.c
blockdev: Acquire AioContext on dirty bitmap functions
[mirror_qemu.git] / blockdev.c
1 /*
2 * QEMU host block devices
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 *
6 * This work is licensed under the terms of the GNU GPL, version 2 or
7 * later. See the COPYING file in the top-level directory.
8 *
9 * This file incorporates work covered by the following copyright and
10 * permission notice:
11 *
12 * Copyright (c) 2003-2008 Fabrice Bellard
13 *
14 * Permission is hereby granted, free of charge, to any person obtaining a copy
15 * of this software and associated documentation files (the "Software"), to deal
16 * in the Software without restriction, including without limitation the rights
17 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 * copies of the Software, and to permit persons to whom the Software is
19 * furnished to do so, subject to the following conditions:
20 *
21 * The above copyright notice and this permission notice shall be included in
22 * all copies or substantial portions of the Software.
23 *
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
27 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
30 * THE SOFTWARE.
31 */
32
33 #include "qemu/osdep.h"
34 #include "sysemu/block-backend.h"
35 #include "sysemu/blockdev.h"
36 #include "hw/block/block.h"
37 #include "block/blockjob.h"
38 #include "block/qdict.h"
39 #include "block/throttle-groups.h"
40 #include "monitor/monitor.h"
41 #include "qemu/error-report.h"
42 #include "qemu/option.h"
43 #include "qemu/qemu-print.h"
44 #include "qemu/config-file.h"
45 #include "qapi/qapi-commands-block.h"
46 #include "qapi/qapi-commands-transaction.h"
47 #include "qapi/qapi-visit-block-core.h"
48 #include "qapi/qmp/qdict.h"
49 #include "qapi/qmp/qnum.h"
50 #include "qapi/qmp/qstring.h"
51 #include "qapi/error.h"
52 #include "qapi/qmp/qerror.h"
53 #include "qapi/qmp/qlist.h"
54 #include "qapi/qobject-output-visitor.h"
55 #include "sysemu/sysemu.h"
56 #include "sysemu/iothread.h"
57 #include "block/block_int.h"
58 #include "block/trace.h"
59 #include "sysemu/arch_init.h"
60 #include "sysemu/qtest.h"
61 #include "sysemu/runstate.h"
62 #include "qemu/cutils.h"
63 #include "qemu/help_option.h"
64 #include "qemu/main-loop.h"
65 #include "qemu/throttle-options.h"
66
67 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 AioContext *aio_context;
2988
2989 if (!name || name[0] == '\0') {
2990 error_setg(errp, "Bitmap name cannot be empty");
2991 return;
2992 }
2993
2994 bs = bdrv_lookup_bs(node, node, errp);
2995 if (!bs) {
2996 return;
2997 }
2998
2999 aio_context = bdrv_get_aio_context(bs);
3000 aio_context_acquire(aio_context);
3001
3002 if (has_granularity) {
3003 if (granularity < 512 || !is_power_of_2(granularity)) {
3004 error_setg(errp, "Granularity must be power of 2 "
3005 "and at least 512");
3006 goto out;
3007 }
3008 } else {
3009 /* Default to cluster size, if available: */
3010 granularity = bdrv_get_default_bitmap_granularity(bs);
3011 }
3012
3013 if (!has_persistent) {
3014 persistent = false;
3015 }
3016
3017 if (!has_disabled) {
3018 disabled = false;
3019 }
3020
3021 if (persistent &&
3022 !bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp))
3023 {
3024 goto out;
3025 }
3026
3027 bitmap = bdrv_create_dirty_bitmap(bs, granularity, name, errp);
3028 if (bitmap == NULL) {
3029 goto out;
3030 }
3031
3032 if (disabled) {
3033 bdrv_disable_dirty_bitmap(bitmap);
3034 }
3035
3036 bdrv_dirty_bitmap_set_persistence(bitmap, persistent);
3037
3038 out:
3039 aio_context_release(aio_context);
3040 }
3041
3042 static BdrvDirtyBitmap *do_block_dirty_bitmap_remove(
3043 const char *node, const char *name, bool release,
3044 BlockDriverState **bitmap_bs, Error **errp)
3045 {
3046 BlockDriverState *bs;
3047 BdrvDirtyBitmap *bitmap;
3048 AioContext *aio_context;
3049
3050 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3051 if (!bitmap || !bs) {
3052 return NULL;
3053 }
3054
3055 aio_context = bdrv_get_aio_context(bs);
3056 aio_context_acquire(aio_context);
3057
3058 if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_BUSY | BDRV_BITMAP_RO,
3059 errp)) {
3060 aio_context_release(aio_context);
3061 return NULL;
3062 }
3063
3064 if (bdrv_dirty_bitmap_get_persistence(bitmap) &&
3065 bdrv_remove_persistent_dirty_bitmap(bs, name, errp) < 0)
3066 {
3067 aio_context_release(aio_context);
3068 return NULL;
3069 }
3070
3071 if (release) {
3072 bdrv_release_dirty_bitmap(bitmap);
3073 }
3074
3075 if (bitmap_bs) {
3076 *bitmap_bs = bs;
3077 }
3078
3079 aio_context_release(aio_context);
3080 return release ? NULL : bitmap;
3081 }
3082
3083 void qmp_block_dirty_bitmap_remove(const char *node, const char *name,
3084 Error **errp)
3085 {
3086 do_block_dirty_bitmap_remove(node, name, true, NULL, errp);
3087 }
3088
3089 /**
3090 * Completely clear a bitmap, for the purposes of synchronizing a bitmap
3091 * immediately after a full backup operation.
3092 */
3093 void qmp_block_dirty_bitmap_clear(const char *node, const char *name,
3094 Error **errp)
3095 {
3096 BdrvDirtyBitmap *bitmap;
3097 BlockDriverState *bs;
3098
3099 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3100 if (!bitmap || !bs) {
3101 return;
3102 }
3103
3104 if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_DEFAULT, errp)) {
3105 return;
3106 }
3107
3108 bdrv_clear_dirty_bitmap(bitmap, NULL);
3109 }
3110
3111 void qmp_block_dirty_bitmap_enable(const char *node, const char *name,
3112 Error **errp)
3113 {
3114 BlockDriverState *bs;
3115 BdrvDirtyBitmap *bitmap;
3116
3117 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3118 if (!bitmap) {
3119 return;
3120 }
3121
3122 if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
3123 return;
3124 }
3125
3126 bdrv_enable_dirty_bitmap(bitmap);
3127 }
3128
3129 void qmp_block_dirty_bitmap_disable(const char *node, const char *name,
3130 Error **errp)
3131 {
3132 BlockDriverState *bs;
3133 BdrvDirtyBitmap *bitmap;
3134
3135 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3136 if (!bitmap) {
3137 return;
3138 }
3139
3140 if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
3141 return;
3142 }
3143
3144 bdrv_disable_dirty_bitmap(bitmap);
3145 }
3146
3147 static BdrvDirtyBitmap *do_block_dirty_bitmap_merge(
3148 const char *node, const char *target,
3149 BlockDirtyBitmapMergeSourceList *bitmaps,
3150 HBitmap **backup, Error **errp)
3151 {
3152 BlockDriverState *bs;
3153 BdrvDirtyBitmap *dst, *src, *anon;
3154 BlockDirtyBitmapMergeSourceList *lst;
3155 Error *local_err = NULL;
3156
3157 dst = block_dirty_bitmap_lookup(node, target, &bs, errp);
3158 if (!dst) {
3159 return NULL;
3160 }
3161
3162 anon = bdrv_create_dirty_bitmap(bs, bdrv_dirty_bitmap_granularity(dst),
3163 NULL, errp);
3164 if (!anon) {
3165 return NULL;
3166 }
3167
3168 for (lst = bitmaps; lst; lst = lst->next) {
3169 switch (lst->value->type) {
3170 const char *name, *node;
3171 case QTYPE_QSTRING:
3172 name = lst->value->u.local;
3173 src = bdrv_find_dirty_bitmap(bs, name);
3174 if (!src) {
3175 error_setg(errp, "Dirty bitmap '%s' not found", name);
3176 dst = NULL;
3177 goto out;
3178 }
3179 break;
3180 case QTYPE_QDICT:
3181 node = lst->value->u.external.node;
3182 name = lst->value->u.external.name;
3183 src = block_dirty_bitmap_lookup(node, name, NULL, errp);
3184 if (!src) {
3185 dst = NULL;
3186 goto out;
3187 }
3188 break;
3189 default:
3190 abort();
3191 }
3192
3193 bdrv_merge_dirty_bitmap(anon, src, NULL, &local_err);
3194 if (local_err) {
3195 error_propagate(errp, local_err);
3196 dst = NULL;
3197 goto out;
3198 }
3199 }
3200
3201 /* Merge into dst; dst is unchanged on failure. */
3202 bdrv_merge_dirty_bitmap(dst, anon, backup, errp);
3203
3204 out:
3205 bdrv_release_dirty_bitmap(anon);
3206 return dst;
3207 }
3208
3209 void qmp_block_dirty_bitmap_merge(const char *node, const char *target,
3210 BlockDirtyBitmapMergeSourceList *bitmaps,
3211 Error **errp)
3212 {
3213 do_block_dirty_bitmap_merge(node, target, bitmaps, NULL, errp);
3214 }
3215
3216 BlockDirtyBitmapSha256 *qmp_x_debug_block_dirty_bitmap_sha256(const char *node,
3217 const char *name,
3218 Error **errp)
3219 {
3220 BdrvDirtyBitmap *bitmap;
3221 BlockDriverState *bs;
3222 BlockDirtyBitmapSha256 *ret = NULL;
3223 char *sha256;
3224
3225 bitmap = block_dirty_bitmap_lookup(node, name, &bs, errp);
3226 if (!bitmap || !bs) {
3227 return NULL;
3228 }
3229
3230 sha256 = bdrv_dirty_bitmap_sha256(bitmap, errp);
3231 if (sha256 == NULL) {
3232 return NULL;
3233 }
3234
3235 ret = g_new(BlockDirtyBitmapSha256, 1);
3236 ret->sha256 = sha256;
3237
3238 return ret;
3239 }
3240
3241 void hmp_drive_del(Monitor *mon, const QDict *qdict)
3242 {
3243 const char *id = qdict_get_str(qdict, "id");
3244 BlockBackend *blk;
3245 BlockDriverState *bs;
3246 AioContext *aio_context;
3247 Error *local_err = NULL;
3248
3249 bs = bdrv_find_node(id);
3250 if (bs) {
3251 qmp_blockdev_del(id, &local_err);
3252 if (local_err) {
3253 error_report_err(local_err);
3254 }
3255 return;
3256 }
3257
3258 blk = blk_by_name(id);
3259 if (!blk) {
3260 error_report("Device '%s' not found", id);
3261 return;
3262 }
3263
3264 if (!blk_legacy_dinfo(blk)) {
3265 error_report("Deleting device added with blockdev-add"
3266 " is not supported");
3267 return;
3268 }
3269
3270 aio_context = blk_get_aio_context(blk);
3271 aio_context_acquire(aio_context);
3272
3273 bs = blk_bs(blk);
3274 if (bs) {
3275 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, &local_err)) {
3276 error_report_err(local_err);
3277 aio_context_release(aio_context);
3278 return;
3279 }
3280
3281 blk_remove_bs(blk);
3282 }
3283
3284 /* Make the BlockBackend and the attached BlockDriverState anonymous */
3285 monitor_remove_blk(blk);
3286
3287 /* If this BlockBackend has a device attached to it, its refcount will be
3288 * decremented when the device is removed; otherwise we have to do so here.
3289 */
3290 if (blk_get_attached_dev(blk)) {
3291 /* Further I/O must not pause the guest */
3292 blk_set_on_error(blk, BLOCKDEV_ON_ERROR_REPORT,
3293 BLOCKDEV_ON_ERROR_REPORT);
3294 } else {
3295 blk_unref(blk);
3296 }
3297
3298 aio_context_release(aio_context);
3299 }
3300
3301 void qmp_block_resize(bool has_device, const char *device,
3302 bool has_node_name, const char *node_name,
3303 int64_t size, Error **errp)
3304 {
3305 Error *local_err = NULL;
3306 BlockBackend *blk = NULL;
3307 BlockDriverState *bs;
3308 AioContext *aio_context;
3309 int ret;
3310
3311 bs = bdrv_lookup_bs(has_device ? device : NULL,
3312 has_node_name ? node_name : NULL,
3313 &local_err);
3314 if (local_err) {
3315 error_propagate(errp, local_err);
3316 return;
3317 }
3318
3319 aio_context = bdrv_get_aio_context(bs);
3320 aio_context_acquire(aio_context);
3321
3322 if (!bdrv_is_first_non_filter(bs)) {
3323 error_setg(errp, QERR_FEATURE_DISABLED, "resize");
3324 goto out;
3325 }
3326
3327 if (size < 0) {
3328 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");
3329 goto out;
3330 }
3331
3332 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {
3333 error_setg(errp, QERR_DEVICE_IN_USE, device);
3334 goto out;
3335 }
3336
3337 blk = blk_new(bdrv_get_aio_context(bs), BLK_PERM_RESIZE, BLK_PERM_ALL);
3338 ret = blk_insert_bs(blk, bs, errp);
3339 if (ret < 0) {
3340 goto out;
3341 }
3342
3343 bdrv_drained_begin(bs);
3344 ret = blk_truncate(blk, size, false, PREALLOC_MODE_OFF, errp);
3345 bdrv_drained_end(bs);
3346
3347 out:
3348 blk_unref(blk);
3349 aio_context_release(aio_context);
3350 }
3351
3352 void qmp_block_stream(bool has_job_id, const char *job_id, const char *device,
3353 bool has_base, const char *base,
3354 bool has_base_node, const char *base_node,
3355 bool has_backing_file, const char *backing_file,
3356 bool has_speed, int64_t speed,
3357 bool has_on_error, BlockdevOnError on_error,
3358 bool has_auto_finalize, bool auto_finalize,
3359 bool has_auto_dismiss, bool auto_dismiss,
3360 Error **errp)
3361 {
3362 BlockDriverState *bs, *iter;
3363 BlockDriverState *base_bs = NULL;
3364 AioContext *aio_context;
3365 Error *local_err = NULL;
3366 const char *base_name = NULL;
3367 int job_flags = JOB_DEFAULT;
3368
3369 if (!has_on_error) {
3370 on_error = BLOCKDEV_ON_ERROR_REPORT;
3371 }
3372
3373 bs = bdrv_lookup_bs(device, device, errp);
3374 if (!bs) {
3375 return;
3376 }
3377
3378 aio_context = bdrv_get_aio_context(bs);
3379 aio_context_acquire(aio_context);
3380
3381 if (has_base && has_base_node) {
3382 error_setg(errp, "'base' and 'base-node' cannot be specified "
3383 "at the same time");
3384 goto out;
3385 }
3386
3387 if (has_base) {
3388 base_bs = bdrv_find_backing_image(bs, base);
3389 if (base_bs == NULL) {
3390 error_setg(errp, QERR_BASE_NOT_FOUND, base);
3391 goto out;
3392 }
3393 assert(bdrv_get_aio_context(base_bs) == aio_context);
3394 base_name = base;
3395 }
3396
3397 if (has_base_node) {
3398 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3399 if (!base_bs) {
3400 goto out;
3401 }
3402 if (bs == base_bs || !bdrv_chain_contains(bs, base_bs)) {
3403 error_setg(errp, "Node '%s' is not a backing image of '%s'",
3404 base_node, device);
3405 goto out;
3406 }
3407 assert(bdrv_get_aio_context(base_bs) == aio_context);
3408 bdrv_refresh_filename(base_bs);
3409 base_name = base_bs->filename;
3410 }
3411
3412 /* Check for op blockers in the whole chain between bs and base */
3413 for (iter = bs; iter && iter != base_bs; iter = backing_bs(iter)) {
3414 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_STREAM, errp)) {
3415 goto out;
3416 }
3417 }
3418
3419 /* if we are streaming the entire chain, the result will have no backing
3420 * file, and specifying one is therefore an error */
3421 if (base_bs == NULL && has_backing_file) {
3422 error_setg(errp, "backing file specified, but streaming the "
3423 "entire chain");
3424 goto out;
3425 }
3426
3427 /* backing_file string overrides base bs filename */
3428 base_name = has_backing_file ? backing_file : base_name;
3429
3430 if (has_auto_finalize && !auto_finalize) {
3431 job_flags |= JOB_MANUAL_FINALIZE;
3432 }
3433 if (has_auto_dismiss && !auto_dismiss) {
3434 job_flags |= JOB_MANUAL_DISMISS;
3435 }
3436
3437 stream_start(has_job_id ? job_id : NULL, bs, base_bs, base_name,
3438 job_flags, has_speed ? speed : 0, on_error, &local_err);
3439 if (local_err) {
3440 error_propagate(errp, local_err);
3441 goto out;
3442 }
3443
3444 trace_qmp_block_stream(bs);
3445
3446 out:
3447 aio_context_release(aio_context);
3448 }
3449
3450 void qmp_block_commit(bool has_job_id, const char *job_id, const char *device,
3451 bool has_base_node, const char *base_node,
3452 bool has_base, const char *base,
3453 bool has_top_node, const char *top_node,
3454 bool has_top, const char *top,
3455 bool has_backing_file, const char *backing_file,
3456 bool has_speed, int64_t speed,
3457 bool has_filter_node_name, const char *filter_node_name,
3458 bool has_auto_finalize, bool auto_finalize,
3459 bool has_auto_dismiss, bool auto_dismiss,
3460 Error **errp)
3461 {
3462 BlockDriverState *bs;
3463 BlockDriverState *iter;
3464 BlockDriverState *base_bs, *top_bs;
3465 AioContext *aio_context;
3466 Error *local_err = NULL;
3467 /* This will be part of the QMP command, if/when the
3468 * BlockdevOnError change for blkmirror makes it in
3469 */
3470 BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;
3471 int job_flags = JOB_DEFAULT;
3472
3473 if (!has_speed) {
3474 speed = 0;
3475 }
3476 if (!has_filter_node_name) {
3477 filter_node_name = NULL;
3478 }
3479 if (has_auto_finalize && !auto_finalize) {
3480 job_flags |= JOB_MANUAL_FINALIZE;
3481 }
3482 if (has_auto_dismiss && !auto_dismiss) {
3483 job_flags |= JOB_MANUAL_DISMISS;
3484 }
3485
3486 /* Important Note:
3487 * libvirt relies on the DeviceNotFound error class in order to probe for
3488 * live commit feature versions; for this to work, we must make sure to
3489 * perform the device lookup before any generic errors that may occur in a
3490 * scenario in which all optional arguments are omitted. */
3491 bs = qmp_get_root_bs(device, &local_err);
3492 if (!bs) {
3493 bs = bdrv_lookup_bs(device, device, NULL);
3494 if (!bs) {
3495 error_free(local_err);
3496 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
3497 "Device '%s' not found", device);
3498 } else {
3499 error_propagate(errp, local_err);
3500 }
3501 return;
3502 }
3503
3504 aio_context = bdrv_get_aio_context(bs);
3505 aio_context_acquire(aio_context);
3506
3507 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, errp)) {
3508 goto out;
3509 }
3510
3511 /* default top_bs is the active layer */
3512 top_bs = bs;
3513
3514 if (has_top_node && has_top) {
3515 error_setg(errp, "'top-node' and 'top' are mutually exclusive");
3516 goto out;
3517 } else if (has_top_node) {
3518 top_bs = bdrv_lookup_bs(NULL, top_node, errp);
3519 if (top_bs == NULL) {
3520 goto out;
3521 }
3522 if (!bdrv_chain_contains(bs, top_bs)) {
3523 error_setg(errp, "'%s' is not in this backing file chain",
3524 top_node);
3525 goto out;
3526 }
3527 } else if (has_top && top) {
3528 /* This strcmp() is just a shortcut, there is no need to
3529 * refresh @bs's filename. If it mismatches,
3530 * bdrv_find_backing_image() will do the refresh and may still
3531 * return @bs. */
3532 if (strcmp(bs->filename, top) != 0) {
3533 top_bs = bdrv_find_backing_image(bs, top);
3534 }
3535 }
3536
3537 if (top_bs == NULL) {
3538 error_setg(errp, "Top image file %s not found", top ? top : "NULL");
3539 goto out;
3540 }
3541
3542 assert(bdrv_get_aio_context(top_bs) == aio_context);
3543
3544 if (has_base_node && has_base) {
3545 error_setg(errp, "'base-node' and 'base' are mutually exclusive");
3546 goto out;
3547 } else if (has_base_node) {
3548 base_bs = bdrv_lookup_bs(NULL, base_node, errp);
3549 if (base_bs == NULL) {
3550 goto out;
3551 }
3552 if (!bdrv_chain_contains(top_bs, base_bs)) {
3553 error_setg(errp, "'%s' is not in this backing file chain",
3554 base_node);
3555 goto out;
3556 }
3557 } else if (has_base && base) {
3558 base_bs = bdrv_find_backing_image(top_bs, base);
3559 } else {
3560 base_bs = bdrv_find_base(top_bs);
3561 }
3562
3563 if (base_bs == NULL) {
3564 error_setg(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");
3565 goto out;
3566 }
3567
3568 assert(bdrv_get_aio_context(base_bs) == aio_context);
3569
3570 for (iter = top_bs; iter != backing_bs(base_bs); iter = backing_bs(iter)) {
3571 if (bdrv_op_is_blocked(iter, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3572 goto out;
3573 }
3574 }
3575
3576 /* Do not allow attempts to commit an image into itself */
3577 if (top_bs == base_bs) {
3578 error_setg(errp, "cannot commit an image into itself");
3579 goto out;
3580 }
3581
3582 if (top_bs == bs) {
3583 if (has_backing_file) {
3584 error_setg(errp, "'backing-file' specified,"
3585 " but 'top' is the active layer");
3586 goto out;
3587 }
3588 commit_active_start(has_job_id ? job_id : NULL, bs, base_bs,
3589 job_flags, speed, on_error,
3590 filter_node_name, NULL, NULL, false, &local_err);
3591 } else {
3592 BlockDriverState *overlay_bs = bdrv_find_overlay(bs, top_bs);
3593 if (bdrv_op_is_blocked(overlay_bs, BLOCK_OP_TYPE_COMMIT_TARGET, errp)) {
3594 goto out;
3595 }
3596 commit_start(has_job_id ? job_id : NULL, bs, base_bs, top_bs, job_flags,
3597 speed, on_error, has_backing_file ? backing_file : NULL,
3598 filter_node_name, &local_err);
3599 }
3600 if (local_err != NULL) {
3601 error_propagate(errp, local_err);
3602 goto out;
3603 }
3604
3605 out:
3606 aio_context_release(aio_context);
3607 }
3608
3609 /* Common QMP interface for drive-backup and blockdev-backup */
3610 static BlockJob *do_backup_common(BackupCommon *backup,
3611 BlockDriverState *bs,
3612 BlockDriverState *target_bs,
3613 AioContext *aio_context,
3614 JobTxn *txn, Error **errp)
3615 {
3616 BlockJob *job = NULL;
3617 BdrvDirtyBitmap *bmap = NULL;
3618 int job_flags = JOB_DEFAULT;
3619
3620 if (!backup->has_speed) {
3621 backup->speed = 0;
3622 }
3623 if (!backup->has_on_source_error) {
3624 backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3625 }
3626 if (!backup->has_on_target_error) {
3627 backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3628 }
3629 if (!backup->has_job_id) {
3630 backup->job_id = NULL;
3631 }
3632 if (!backup->has_auto_finalize) {
3633 backup->auto_finalize = true;
3634 }
3635 if (!backup->has_auto_dismiss) {
3636 backup->auto_dismiss = true;
3637 }
3638 if (!backup->has_compress) {
3639 backup->compress = false;
3640 }
3641
3642 if ((backup->sync == MIRROR_SYNC_MODE_BITMAP) ||
3643 (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL)) {
3644 /* done before desugaring 'incremental' to print the right message */
3645 if (!backup->has_bitmap) {
3646 error_setg(errp, "must provide a valid bitmap name for "
3647 "'%s' sync mode", MirrorSyncMode_str(backup->sync));
3648 return NULL;
3649 }
3650 }
3651
3652 if (backup->sync == MIRROR_SYNC_MODE_INCREMENTAL) {
3653 if (backup->has_bitmap_mode &&
3654 backup->bitmap_mode != BITMAP_SYNC_MODE_ON_SUCCESS) {
3655 error_setg(errp, "Bitmap sync mode must be '%s' "
3656 "when using sync mode '%s'",
3657 BitmapSyncMode_str(BITMAP_SYNC_MODE_ON_SUCCESS),
3658 MirrorSyncMode_str(backup->sync));
3659 return NULL;
3660 }
3661 backup->has_bitmap_mode = true;
3662 backup->sync = MIRROR_SYNC_MODE_BITMAP;
3663 backup->bitmap_mode = BITMAP_SYNC_MODE_ON_SUCCESS;
3664 }
3665
3666 if (backup->has_bitmap) {
3667 bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);
3668 if (!bmap) {
3669 error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);
3670 return NULL;
3671 }
3672 if (!backup->has_bitmap_mode) {
3673 error_setg(errp, "Bitmap sync mode must be given "
3674 "when providing a bitmap");
3675 return NULL;
3676 }
3677 if (bdrv_dirty_bitmap_check(bmap, BDRV_BITMAP_ALLOW_RO, errp)) {
3678 return NULL;
3679 }
3680
3681 /* This does not produce a useful bitmap artifact: */
3682 if (backup->sync == MIRROR_SYNC_MODE_NONE) {
3683 error_setg(errp, "sync mode '%s' does not produce meaningful bitmap"
3684 " outputs", MirrorSyncMode_str(backup->sync));
3685 return NULL;
3686 }
3687
3688 /* If the bitmap isn't used for input or output, this is useless: */
3689 if (backup->bitmap_mode == BITMAP_SYNC_MODE_NEVER &&
3690 backup->sync != MIRROR_SYNC_MODE_BITMAP) {
3691 error_setg(errp, "Bitmap sync mode '%s' has no meaningful effect"
3692 " when combined with sync mode '%s'",
3693 BitmapSyncMode_str(backup->bitmap_mode),
3694 MirrorSyncMode_str(backup->sync));
3695 return NULL;
3696 }
3697 }
3698
3699 if (!backup->has_bitmap && backup->has_bitmap_mode) {
3700 error_setg(errp, "Cannot specify bitmap sync mode without a bitmap");
3701 return NULL;
3702 }
3703
3704 if (!backup->auto_finalize) {
3705 job_flags |= JOB_MANUAL_FINALIZE;
3706 }
3707 if (!backup->auto_dismiss) {
3708 job_flags |= JOB_MANUAL_DISMISS;
3709 }
3710
3711 job = backup_job_create(backup->job_id, bs, target_bs, backup->speed,
3712 backup->sync, bmap, backup->bitmap_mode,
3713 backup->compress,
3714 backup->filter_node_name,
3715 backup->on_source_error,
3716 backup->on_target_error,
3717 job_flags, NULL, NULL, txn, errp);
3718 return job;
3719 }
3720
3721 void qmp_drive_backup(DriveBackup *backup, Error **errp)
3722 {
3723 TransactionAction action = {
3724 .type = TRANSACTION_ACTION_KIND_DRIVE_BACKUP,
3725 .u.drive_backup.data = backup,
3726 };
3727 blockdev_do_action(&action, errp);
3728 }
3729
3730 BlockDeviceInfoList *qmp_query_named_block_nodes(Error **errp)
3731 {
3732 return bdrv_named_nodes_list(errp);
3733 }
3734
3735 XDbgBlockGraph *qmp_x_debug_query_block_graph(Error **errp)
3736 {
3737 return bdrv_get_xdbg_block_graph(errp);
3738 }
3739
3740 void qmp_blockdev_backup(BlockdevBackup *backup, Error **errp)
3741 {
3742 TransactionAction action = {
3743 .type = TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP,
3744 .u.blockdev_backup.data = backup,
3745 };
3746 blockdev_do_action(&action, errp);
3747 }
3748
3749 /* Parameter check and block job starting for drive mirroring.
3750 * Caller should hold @device and @target's aio context (must be the same).
3751 **/
3752 static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
3753 BlockDriverState *target,
3754 bool has_replaces, const char *replaces,
3755 enum MirrorSyncMode sync,
3756 BlockMirrorBackingMode backing_mode,
3757 bool zero_target,
3758 bool has_speed, int64_t speed,
3759 bool has_granularity, uint32_t granularity,
3760 bool has_buf_size, int64_t buf_size,
3761 bool has_on_source_error,
3762 BlockdevOnError on_source_error,
3763 bool has_on_target_error,
3764 BlockdevOnError on_target_error,
3765 bool has_unmap, bool unmap,
3766 bool has_filter_node_name,
3767 const char *filter_node_name,
3768 bool has_copy_mode, MirrorCopyMode copy_mode,
3769 bool has_auto_finalize, bool auto_finalize,
3770 bool has_auto_dismiss, bool auto_dismiss,
3771 Error **errp)
3772 {
3773 int job_flags = JOB_DEFAULT;
3774
3775 if (!has_speed) {
3776 speed = 0;
3777 }
3778 if (!has_on_source_error) {
3779 on_source_error = BLOCKDEV_ON_ERROR_REPORT;
3780 }
3781 if (!has_on_target_error) {
3782 on_target_error = BLOCKDEV_ON_ERROR_REPORT;
3783 }
3784 if (!has_granularity) {
3785 granularity = 0;
3786 }
3787 if (!has_buf_size) {
3788 buf_size = 0;
3789 }
3790 if (!has_unmap) {
3791 unmap = true;
3792 }
3793 if (!has_filter_node_name) {
3794 filter_node_name = NULL;
3795 }
3796 if (!has_copy_mode) {
3797 copy_mode = MIRROR_COPY_MODE_BACKGROUND;
3798 }
3799 if (has_auto_finalize && !auto_finalize) {
3800 job_flags |= JOB_MANUAL_FINALIZE;
3801 }
3802 if (has_auto_dismiss && !auto_dismiss) {
3803 job_flags |= JOB_MANUAL_DISMISS;
3804 }
3805
3806 if (granularity != 0 && (granularity < 512 || granularity > 1048576 * 64)) {
3807 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3808 "a value in range [512B, 64MB]");
3809 return;
3810 }
3811 if (granularity & (granularity - 1)) {
3812 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "granularity",
3813 "power of 2");
3814 return;
3815 }
3816
3817 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3818 return;
3819 }
3820 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_MIRROR_TARGET, errp)) {
3821 return;
3822 }
3823
3824 if (!bs->backing && sync == MIRROR_SYNC_MODE_TOP) {
3825 sync = MIRROR_SYNC_MODE_FULL;
3826 }
3827
3828 if (has_replaces) {
3829 BlockDriverState *to_replace_bs;
3830 AioContext *replace_aio_context;
3831 int64_t bs_size, replace_size;
3832
3833 bs_size = bdrv_getlength(bs);
3834 if (bs_size < 0) {
3835 error_setg_errno(errp, -bs_size, "Failed to query device's size");
3836 return;
3837 }
3838
3839 to_replace_bs = check_to_replace_node(bs, replaces, errp);
3840 if (!to_replace_bs) {
3841 return;
3842 }
3843
3844 replace_aio_context = bdrv_get_aio_context(to_replace_bs);
3845 aio_context_acquire(replace_aio_context);
3846 replace_size = bdrv_getlength(to_replace_bs);
3847 aio_context_release(replace_aio_context);
3848
3849 if (replace_size < 0) {
3850 error_setg_errno(errp, -replace_size,
3851 "Failed to query the replacement node's size");
3852 return;
3853 }
3854 if (bs_size != replace_size) {
3855 error_setg(errp, "cannot replace image with a mirror image of "
3856 "different size");
3857 return;
3858 }
3859 }
3860
3861 /* pass the node name to replace to mirror start since it's loose coupling
3862 * and will allow to check whether the node still exist at mirror completion
3863 */
3864 mirror_start(job_id, bs, target,
3865 has_replaces ? replaces : NULL, job_flags,
3866 speed, granularity, buf_size, sync, backing_mode, zero_target,
3867 on_source_error, on_target_error, unmap, filter_node_name,
3868 copy_mode, errp);
3869 }
3870
3871 void qmp_drive_mirror(DriveMirror *arg, Error **errp)
3872 {
3873 BlockDriverState *bs;
3874 BlockDriverState *source, *target_bs;
3875 AioContext *aio_context;
3876 AioContext *old_context;
3877 BlockMirrorBackingMode backing_mode;
3878 Error *local_err = NULL;
3879 QDict *options = NULL;
3880 int flags;
3881 int64_t size;
3882 const char *format = arg->format;
3883 bool zero_target;
3884 int ret;
3885
3886 bs = qmp_get_root_bs(arg->device, errp);
3887 if (!bs) {
3888 return;
3889 }
3890
3891 /* Early check to avoid creating target */
3892 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_MIRROR_SOURCE, errp)) {
3893 return;
3894 }
3895
3896 aio_context = bdrv_get_aio_context(bs);
3897 aio_context_acquire(aio_context);
3898
3899 if (!arg->has_mode) {
3900 arg->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;
3901 }
3902
3903 if (!arg->has_format) {
3904 format = (arg->mode == NEW_IMAGE_MODE_EXISTING
3905 ? NULL : bs->drv->format_name);
3906 }
3907
3908 flags = bs->open_flags | BDRV_O_RDWR;
3909 source = backing_bs(bs);
3910 if (!source && arg->sync == MIRROR_SYNC_MODE_TOP) {
3911 arg->sync = MIRROR_SYNC_MODE_FULL;
3912 }
3913 if (arg->sync == MIRROR_SYNC_MODE_NONE) {
3914 source = bs;
3915 }
3916
3917 size = bdrv_getlength(bs);
3918 if (size < 0) {
3919 error_setg_errno(errp, -size, "bdrv_getlength failed");
3920 goto out;
3921 }
3922
3923 if (arg->has_replaces) {
3924 if (!arg->has_node_name) {
3925 error_setg(errp, "a node-name must be provided when replacing a"
3926 " named node of the graph");
3927 goto out;
3928 }
3929 }
3930
3931 if (arg->mode == NEW_IMAGE_MODE_ABSOLUTE_PATHS) {
3932 backing_mode = MIRROR_SOURCE_BACKING_CHAIN;
3933 } else {
3934 backing_mode = MIRROR_OPEN_BACKING_CHAIN;
3935 }
3936
3937 /* Don't open backing image in create() */
3938 flags |= BDRV_O_NO_BACKING;
3939
3940 if ((arg->sync == MIRROR_SYNC_MODE_FULL || !source)
3941 && arg->mode != NEW_IMAGE_MODE_EXISTING)
3942 {
3943 /* create new image w/o backing file */
3944 assert(format);
3945 bdrv_img_create(arg->target, format,
3946 NULL, NULL, NULL, size, flags, false, &local_err);
3947 } else {
3948 switch (arg->mode) {
3949 case NEW_IMAGE_MODE_EXISTING:
3950 break;
3951 case NEW_IMAGE_MODE_ABSOLUTE_PATHS:
3952 /* create new image with backing file */
3953 bdrv_refresh_filename(source);
3954 bdrv_img_create(arg->target, format,
3955 source->filename,
3956 source->drv->format_name,
3957 NULL, size, flags, false, &local_err);
3958 break;
3959 default:
3960 abort();
3961 }
3962 }
3963
3964 if (local_err) {
3965 error_propagate(errp, local_err);
3966 goto out;
3967 }
3968
3969 options = qdict_new();
3970 if (arg->has_node_name) {
3971 qdict_put_str(options, "node-name", arg->node_name);
3972 }
3973 if (format) {
3974 qdict_put_str(options, "driver", format);
3975 }
3976
3977 /* Mirroring takes care of copy-on-write using the source's backing
3978 * file.
3979 */
3980 target_bs = bdrv_open(arg->target, NULL, options, flags, errp);
3981 if (!target_bs) {
3982 goto out;
3983 }
3984
3985 zero_target = (arg->sync == MIRROR_SYNC_MODE_FULL &&
3986 (arg->mode == NEW_IMAGE_MODE_EXISTING ||
3987 !bdrv_has_zero_init(target_bs)));
3988
3989
3990 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
3991 old_context = bdrv_get_aio_context(target_bs);
3992 aio_context_release(aio_context);
3993 aio_context_acquire(old_context);
3994
3995 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
3996 if (ret < 0) {
3997 bdrv_unref(target_bs);
3998 aio_context_release(old_context);
3999 return;
4000 }
4001
4002 aio_context_release(old_context);
4003 aio_context_acquire(aio_context);
4004
4005 blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
4006 arg->has_replaces, arg->replaces, arg->sync,
4007 backing_mode, zero_target,
4008 arg->has_speed, arg->speed,
4009 arg->has_granularity, arg->granularity,
4010 arg->has_buf_size, arg->buf_size,
4011 arg->has_on_source_error, arg->on_source_error,
4012 arg->has_on_target_error, arg->on_target_error,
4013 arg->has_unmap, arg->unmap,
4014 false, NULL,
4015 arg->has_copy_mode, arg->copy_mode,
4016 arg->has_auto_finalize, arg->auto_finalize,
4017 arg->has_auto_dismiss, arg->auto_dismiss,
4018 &local_err);
4019 bdrv_unref(target_bs);
4020 error_propagate(errp, local_err);
4021 out:
4022 aio_context_release(aio_context);
4023 }
4024
4025 void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
4026 const char *device, const char *target,
4027 bool has_replaces, const char *replaces,
4028 MirrorSyncMode sync,
4029 bool has_speed, int64_t speed,
4030 bool has_granularity, uint32_t granularity,
4031 bool has_buf_size, int64_t buf_size,
4032 bool has_on_source_error,
4033 BlockdevOnError on_source_error,
4034 bool has_on_target_error,
4035 BlockdevOnError on_target_error,
4036 bool has_filter_node_name,
4037 const char *filter_node_name,
4038 bool has_copy_mode, MirrorCopyMode copy_mode,
4039 bool has_auto_finalize, bool auto_finalize,
4040 bool has_auto_dismiss, bool auto_dismiss,
4041 Error **errp)
4042 {
4043 BlockDriverState *bs;
4044 BlockDriverState *target_bs;
4045 AioContext *aio_context;
4046 AioContext *old_context;
4047 BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;
4048 Error *local_err = NULL;
4049 bool zero_target;
4050 int ret;
4051
4052 bs = qmp_get_root_bs(device, errp);
4053 if (!bs) {
4054 return;
4055 }
4056
4057 target_bs = bdrv_lookup_bs(target, target, errp);
4058 if (!target_bs) {
4059 return;
4060 }
4061
4062 zero_target = (sync == MIRROR_SYNC_MODE_FULL);
4063
4064 /* Honor bdrv_try_set_aio_context() context acquisition requirements. */
4065 old_context = bdrv_get_aio_context(target_bs);
4066 aio_context = bdrv_get_aio_context(bs);
4067 aio_context_acquire(old_context);
4068
4069 ret = bdrv_try_set_aio_context(target_bs, aio_context, errp);
4070
4071 aio_context_release(old_context);
4072 aio_context_acquire(aio_context);
4073
4074 if (ret < 0) {
4075 goto out;
4076 }
4077
4078 blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
4079 has_replaces, replaces, sync, backing_mode,
4080 zero_target, has_speed, speed,
4081 has_granularity, granularity,
4082 has_buf_size, buf_size,
4083 has_on_source_error, on_source_error,
4084 has_on_target_error, on_target_error,
4085 true, true,
4086 has_filter_node_name, filter_node_name,
4087 has_copy_mode, copy_mode,
4088 has_auto_finalize, auto_finalize,
4089 has_auto_dismiss, auto_dismiss,
4090 &local_err);
4091 error_propagate(errp, local_err);
4092 out:
4093 aio_context_release(aio_context);
4094 }
4095
4096 /* Get a block job using its ID and acquire its AioContext */
4097 static BlockJob *find_block_job(const char *id, AioContext **aio_context,
4098 Error **errp)
4099 {
4100 BlockJob *job;
4101
4102 assert(id != NULL);
4103
4104 *aio_context = NULL;
4105
4106 job = block_job_get(id);
4107
4108 if (!job) {
4109 error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,
4110 "Block job '%s' not found", id);
4111 return NULL;
4112 }
4113
4114 *aio_context = blk_get_aio_context(job->blk);
4115 aio_context_acquire(*aio_context);
4116
4117 return job;
4118 }
4119
4120 void qmp_block_job_set_speed(const char *device, int64_t speed, 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 block_job_set_speed(job, speed, errp);
4130 aio_context_release(aio_context);
4131 }
4132
4133 void qmp_block_job_cancel(const char *device,
4134 bool has_force, bool force, Error **errp)
4135 {
4136 AioContext *aio_context;
4137 BlockJob *job = find_block_job(device, &aio_context, errp);
4138
4139 if (!job) {
4140 return;
4141 }
4142
4143 if (!has_force) {
4144 force = false;
4145 }
4146
4147 if (job_user_paused(&job->job) && !force) {
4148 error_setg(errp, "The block job for device '%s' is currently paused",
4149 device);
4150 goto out;
4151 }
4152
4153 trace_qmp_block_job_cancel(job);
4154 job_user_cancel(&job->job, force, errp);
4155 out:
4156 aio_context_release(aio_context);
4157 }
4158
4159 void qmp_block_job_pause(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_pause(job);
4169 job_user_pause(&job->job, errp);
4170 aio_context_release(aio_context);
4171 }
4172
4173 void qmp_block_job_resume(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_resume(job);
4183 job_user_resume(&job->job, errp);
4184 aio_context_release(aio_context);
4185 }
4186
4187 void qmp_block_job_complete(const char *device, Error **errp)
4188 {
4189 AioContext *aio_context;
4190 BlockJob *job = find_block_job(device, &aio_context, errp);
4191
4192 if (!job) {
4193 return;
4194 }
4195
4196 trace_qmp_block_job_complete(job);
4197 job_complete(&job->job, errp);
4198 aio_context_release(aio_context);
4199 }
4200
4201 void qmp_block_job_finalize(const char *id, Error **errp)
4202 {
4203 AioContext *aio_context;
4204 BlockJob *job = find_block_job(id, &aio_context, errp);
4205
4206 if (!job) {
4207 return;
4208 }
4209
4210 trace_qmp_block_job_finalize(job);
4211 job_finalize(&job->job, errp);
4212 aio_context_release(aio_context);
4213 }
4214
4215 void qmp_block_job_dismiss(const char *id, Error **errp)
4216 {
4217 AioContext *aio_context;
4218 BlockJob *bjob = find_block_job(id, &aio_context, errp);
4219 Job *job;
4220
4221 if (!bjob) {
4222 return;
4223 }
4224
4225 trace_qmp_block_job_dismiss(bjob);
4226 job = &bjob->job;
4227 job_dismiss(&job, errp);
4228 aio_context_release(aio_context);
4229 }
4230
4231 void qmp_change_backing_file(const char *device,
4232 const char *image_node_name,
4233 const char *backing_file,
4234 Error **errp)
4235 {
4236 BlockDriverState *bs = NULL;
4237 AioContext *aio_context;
4238 BlockDriverState *image_bs = NULL;
4239 Error *local_err = NULL;
4240 bool ro;
4241 int ret;
4242
4243 bs = qmp_get_root_bs(device, errp);
4244 if (!bs) {
4245 return;
4246 }
4247
4248 aio_context = bdrv_get_aio_context(bs);
4249 aio_context_acquire(aio_context);
4250
4251 image_bs = bdrv_lookup_bs(NULL, image_node_name, &local_err);
4252 if (local_err) {
4253 error_propagate(errp, local_err);
4254 goto out;
4255 }
4256
4257 if (!image_bs) {
4258 error_setg(errp, "image file not found");
4259 goto out;
4260 }
4261
4262 if (bdrv_find_base(image_bs) == image_bs) {
4263 error_setg(errp, "not allowing backing file change on an image "
4264 "without a backing file");
4265 goto out;
4266 }
4267
4268 /* even though we are not necessarily operating on bs, we need it to
4269 * determine if block ops are currently prohibited on the chain */
4270 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_CHANGE, errp)) {
4271 goto out;
4272 }
4273
4274 /* final sanity check */
4275 if (!bdrv_chain_contains(bs, image_bs)) {
4276 error_setg(errp, "'%s' and image file are not in the same chain",
4277 device);
4278 goto out;
4279 }
4280
4281 /* if not r/w, reopen to make r/w */
4282 ro = bdrv_is_read_only(image_bs);
4283
4284 if (ro) {
4285 if (bdrv_reopen_set_read_only(image_bs, false, errp) != 0) {
4286 goto out;
4287 }
4288 }
4289
4290 ret = bdrv_change_backing_file(image_bs, backing_file,
4291 image_bs->drv ? image_bs->drv->format_name : "");
4292
4293 if (ret < 0) {
4294 error_setg_errno(errp, -ret, "Could not change backing file to '%s'",
4295 backing_file);
4296 /* don't exit here, so we can try to restore open flags if
4297 * appropriate */
4298 }
4299
4300 if (ro) {
4301 bdrv_reopen_set_read_only(image_bs, true, &local_err);
4302 error_propagate(errp, local_err);
4303 }
4304
4305 out:
4306 aio_context_release(aio_context);
4307 }
4308
4309 void hmp_drive_add_node(Monitor *mon, const char *optstr)
4310 {
4311 QemuOpts *opts;
4312 QDict *qdict;
4313 Error *local_err = NULL;
4314
4315 opts = qemu_opts_parse_noisily(&qemu_drive_opts, optstr, false);
4316 if (!opts) {
4317 return;
4318 }
4319
4320 qdict = qemu_opts_to_qdict(opts, NULL);
4321
4322 if (!qdict_get_try_str(qdict, "node-name")) {
4323 qobject_unref(qdict);
4324 error_report("'node-name' needs to be specified");
4325 goto out;
4326 }
4327
4328 BlockDriverState *bs = bds_tree_init(qdict, &local_err);
4329 if (!bs) {
4330 error_report_err(local_err);
4331 goto out;
4332 }
4333
4334 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4335
4336 out:
4337 qemu_opts_del(opts);
4338 }
4339
4340 void qmp_blockdev_add(BlockdevOptions *options, Error **errp)
4341 {
4342 BlockDriverState *bs;
4343 QObject *obj;
4344 Visitor *v = qobject_output_visitor_new(&obj);
4345 QDict *qdict;
4346 Error *local_err = NULL;
4347
4348 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
4349 if (local_err) {
4350 error_propagate(errp, local_err);
4351 goto fail;
4352 }
4353
4354 visit_complete(v, &obj);
4355 qdict = qobject_to(QDict, obj);
4356
4357 qdict_flatten(qdict);
4358
4359 if (!qdict_get_try_str(qdict, "node-name")) {
4360 error_setg(errp, "'node-name' must be specified for the root node");
4361 goto fail;
4362 }
4363
4364 bs = bds_tree_init(qdict, errp);
4365 if (!bs) {
4366 goto fail;
4367 }
4368
4369 QTAILQ_INSERT_TAIL(&monitor_bdrv_states, bs, monitor_list);
4370
4371 fail:
4372 visit_free(v);
4373 }
4374
4375 void qmp_x_blockdev_reopen(BlockdevOptions *options, Error **errp)
4376 {
4377 BlockDriverState *bs;
4378 AioContext *ctx;
4379 QObject *obj;
4380 Visitor *v = qobject_output_visitor_new(&obj);
4381 Error *local_err = NULL;
4382 BlockReopenQueue *queue;
4383 QDict *qdict;
4384
4385 /* Check for the selected node name */
4386 if (!options->has_node_name) {
4387 error_setg(errp, "Node name not specified");
4388 goto fail;
4389 }
4390
4391 bs = bdrv_find_node(options->node_name);
4392 if (!bs) {
4393 error_setg(errp, "Cannot find node named '%s'", options->node_name);
4394 goto fail;
4395 }
4396
4397 /* Put all options in a QDict and flatten it */
4398 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
4399 if (local_err) {
4400 error_propagate(errp, local_err);
4401 goto fail;
4402 }
4403
4404 visit_complete(v, &obj);
4405 qdict = qobject_to(QDict, obj);
4406
4407 qdict_flatten(qdict);
4408
4409 /* Perform the reopen operation */
4410 ctx = bdrv_get_aio_context(bs);
4411 aio_context_acquire(ctx);
4412 bdrv_subtree_drained_begin(bs);
4413 queue = bdrv_reopen_queue(NULL, bs, qdict, false);
4414 bdrv_reopen_multiple(queue, errp);
4415 bdrv_subtree_drained_end(bs);
4416 aio_context_release(ctx);
4417
4418 fail:
4419 visit_free(v);
4420 }
4421
4422 void qmp_blockdev_del(const char *node_name, Error **errp)
4423 {
4424 AioContext *aio_context;
4425 BlockDriverState *bs;
4426
4427 bs = bdrv_find_node(node_name);
4428 if (!bs) {
4429 error_setg(errp, "Cannot find node %s", node_name);
4430 return;
4431 }
4432 if (bdrv_has_blk(bs)) {
4433 error_setg(errp, "Node %s is in use", node_name);
4434 return;
4435 }
4436 aio_context = bdrv_get_aio_context(bs);
4437 aio_context_acquire(aio_context);
4438
4439 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_DRIVE_DEL, errp)) {
4440 goto out;
4441 }
4442
4443 if (!QTAILQ_IN_USE(bs, monitor_list)) {
4444 error_setg(errp, "Node %s is not owned by the monitor",
4445 bs->node_name);
4446 goto out;
4447 }
4448
4449 if (bs->refcnt > 1) {
4450 error_setg(errp, "Block device %s is in use",
4451 bdrv_get_device_or_node_name(bs));
4452 goto out;
4453 }
4454
4455 QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);
4456 bdrv_unref(bs);
4457
4458 out:
4459 aio_context_release(aio_context);
4460 }
4461
4462 static BdrvChild *bdrv_find_child(BlockDriverState *parent_bs,
4463 const char *child_name)
4464 {
4465 BdrvChild *child;
4466
4467 QLIST_FOREACH(child, &parent_bs->children, next) {
4468 if (strcmp(child->name, child_name) == 0) {
4469 return child;
4470 }
4471 }
4472
4473 return NULL;
4474 }
4475
4476 void qmp_x_blockdev_change(const char *parent, bool has_child,
4477 const char *child, bool has_node,
4478 const char *node, Error **errp)
4479 {
4480 BlockDriverState *parent_bs, *new_bs = NULL;
4481 BdrvChild *p_child;
4482
4483 parent_bs = bdrv_lookup_bs(parent, parent, errp);
4484 if (!parent_bs) {
4485 return;
4486 }
4487
4488 if (has_child == has_node) {
4489 if (has_child) {
4490 error_setg(errp, "The parameters child and node are in conflict");
4491 } else {
4492 error_setg(errp, "Either child or node must be specified");
4493 }
4494 return;
4495 }
4496
4497 if (has_child) {
4498 p_child = bdrv_find_child(parent_bs, child);
4499 if (!p_child) {
4500 error_setg(errp, "Node '%s' does not have child '%s'",
4501 parent, child);
4502 return;
4503 }
4504 bdrv_del_child(parent_bs, p_child, errp);
4505 }
4506
4507 if (has_node) {
4508 new_bs = bdrv_find_node(node);
4509 if (!new_bs) {
4510 error_setg(errp, "Node '%s' not found", node);
4511 return;
4512 }
4513 bdrv_add_child(parent_bs, new_bs, errp);
4514 }
4515 }
4516
4517 BlockJobInfoList *qmp_query_block_jobs(Error **errp)
4518 {
4519 BlockJobInfoList *head = NULL, **p_next = &head;
4520 BlockJob *job;
4521
4522 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4523 BlockJobInfoList *elem;
4524 AioContext *aio_context;
4525
4526 if (block_job_is_internal(job)) {
4527 continue;
4528 }
4529 elem = g_new0(BlockJobInfoList, 1);
4530 aio_context = blk_get_aio_context(job->blk);
4531 aio_context_acquire(aio_context);
4532 elem->value = block_job_query(job, errp);
4533 aio_context_release(aio_context);
4534 if (!elem->value) {
4535 g_free(elem);
4536 qapi_free_BlockJobInfoList(head);
4537 return NULL;
4538 }
4539 *p_next = elem;
4540 p_next = &elem->next;
4541 }
4542
4543 return head;
4544 }
4545
4546 void qmp_x_blockdev_set_iothread(const char *node_name, StrOrNull *iothread,
4547 bool has_force, bool force, Error **errp)
4548 {
4549 AioContext *old_context;
4550 AioContext *new_context;
4551 BlockDriverState *bs;
4552
4553 bs = bdrv_find_node(node_name);
4554 if (!bs) {
4555 error_setg(errp, "Cannot find node %s", node_name);
4556 return;
4557 }
4558
4559 /* Protects against accidents. */
4560 if (!(has_force && force) && bdrv_has_blk(bs)) {
4561 error_setg(errp, "Node %s is associated with a BlockBackend and could "
4562 "be in use (use force=true to override this check)",
4563 node_name);
4564 return;
4565 }
4566
4567 if (iothread->type == QTYPE_QSTRING) {
4568 IOThread *obj = iothread_by_id(iothread->u.s);
4569 if (!obj) {
4570 error_setg(errp, "Cannot find iothread %s", iothread->u.s);
4571 return;
4572 }
4573
4574 new_context = iothread_get_aio_context(obj);
4575 } else {
4576 new_context = qemu_get_aio_context();
4577 }
4578
4579 old_context = bdrv_get_aio_context(bs);
4580 aio_context_acquire(old_context);
4581
4582 bdrv_try_set_aio_context(bs, new_context, errp);
4583
4584 aio_context_release(old_context);
4585 }
4586
4587 void qmp_block_latency_histogram_set(
4588 const char *id,
4589 bool has_boundaries, uint64List *boundaries,
4590 bool has_boundaries_read, uint64List *boundaries_read,
4591 bool has_boundaries_write, uint64List *boundaries_write,
4592 bool has_boundaries_flush, uint64List *boundaries_flush,
4593 Error **errp)
4594 {
4595 BlockBackend *blk = qmp_get_blk(NULL, id, errp);
4596 BlockAcctStats *stats;
4597 int ret;
4598
4599 if (!blk) {
4600 return;
4601 }
4602
4603 stats = blk_get_stats(blk);
4604
4605 if (!has_boundaries && !has_boundaries_read && !has_boundaries_write &&
4606 !has_boundaries_flush)
4607 {
4608 block_latency_histograms_clear(stats);
4609 return;
4610 }
4611
4612 if (has_boundaries || has_boundaries_read) {
4613 ret = block_latency_histogram_set(
4614 stats, BLOCK_ACCT_READ,
4615 has_boundaries_read ? boundaries_read : boundaries);
4616 if (ret) {
4617 error_setg(errp, "Device '%s' set read boundaries fail", id);
4618 return;
4619 }
4620 }
4621
4622 if (has_boundaries || has_boundaries_write) {
4623 ret = block_latency_histogram_set(
4624 stats, BLOCK_ACCT_WRITE,
4625 has_boundaries_write ? boundaries_write : boundaries);
4626 if (ret) {
4627 error_setg(errp, "Device '%s' set write boundaries fail", id);
4628 return;
4629 }
4630 }
4631
4632 if (has_boundaries || has_boundaries_flush) {
4633 ret = block_latency_histogram_set(
4634 stats, BLOCK_ACCT_FLUSH,
4635 has_boundaries_flush ? boundaries_flush : boundaries);
4636 if (ret) {
4637 error_setg(errp, "Device '%s' set flush boundaries fail", id);
4638 return;
4639 }
4640 }
4641 }
4642
4643 QemuOptsList qemu_common_drive_opts = {
4644 .name = "drive",
4645 .head = QTAILQ_HEAD_INITIALIZER(qemu_common_drive_opts.head),
4646 .desc = {
4647 {
4648 .name = "snapshot",
4649 .type = QEMU_OPT_BOOL,
4650 .help = "enable/disable snapshot mode",
4651 },{
4652 .name = "aio",
4653 .type = QEMU_OPT_STRING,
4654 .help = "host AIO implementation (threads, native)",
4655 },{
4656 .name = BDRV_OPT_CACHE_WB,
4657 .type = QEMU_OPT_BOOL,
4658 .help = "Enable writeback mode",
4659 },{
4660 .name = "format",
4661 .type = QEMU_OPT_STRING,
4662 .help = "disk format (raw, qcow2, ...)",
4663 },{
4664 .name = "rerror",
4665 .type = QEMU_OPT_STRING,
4666 .help = "read error action",
4667 },{
4668 .name = "werror",
4669 .type = QEMU_OPT_STRING,
4670 .help = "write error action",
4671 },{
4672 .name = BDRV_OPT_READ_ONLY,
4673 .type = QEMU_OPT_BOOL,
4674 .help = "open drive file as read-only",
4675 },
4676
4677 THROTTLE_OPTS,
4678
4679 {
4680 .name = "throttling.group",
4681 .type = QEMU_OPT_STRING,
4682 .help = "name of the block throttling group",
4683 },{
4684 .name = "copy-on-read",
4685 .type = QEMU_OPT_BOOL,
4686 .help = "copy read data from backing file into image file",
4687 },{
4688 .name = "detect-zeroes",
4689 .type = QEMU_OPT_STRING,
4690 .help = "try to optimize zero writes (off, on, unmap)",
4691 },{
4692 .name = "stats-account-invalid",
4693 .type = QEMU_OPT_BOOL,
4694 .help = "whether to account for invalid I/O operations "
4695 "in the statistics",
4696 },{
4697 .name = "stats-account-failed",
4698 .type = QEMU_OPT_BOOL,
4699 .help = "whether to account for failed I/O operations "
4700 "in the statistics",
4701 },
4702 { /* end of list */ }
4703 },
4704 };
4705
4706 QemuOptsList qemu_drive_opts = {
4707 .name = "drive",
4708 .head = QTAILQ_HEAD_INITIALIZER(qemu_drive_opts.head),
4709 .desc = {
4710 /*
4711 * no elements => accept any params
4712 * validation will happen later
4713 */
4714 { /* end of list */ }
4715 },
4716 };