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