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