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