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