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