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