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