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