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