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