2 * QEMU System Emulator block driver
4 * Copyright (c) 2003 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 #include "config-host.h"
25 #include "qemu-common.h"
28 #include "block_int.h"
30 #include "qemu-objects.h"
31 #include "qemu-coroutine.h"
34 #include <sys/types.h>
36 #include <sys/ioctl.h>
37 #include <sys/queue.h>
47 static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
48 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
49 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
50 BlockDriverCompletionFunc *cb, void *opaque);
51 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
52 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
53 BlockDriverCompletionFunc *cb, void *opaque);
54 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
55 BlockDriverCompletionFunc *cb, void *opaque);
56 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
57 BlockDriverCompletionFunc *cb, void *opaque);
58 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
59 uint8_t *buf, int nb_sectors);
60 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
61 const uint8_t *buf, int nb_sectors);
62 static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
63 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
64 BlockDriverCompletionFunc *cb, void *opaque);
65 static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
66 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
67 BlockDriverCompletionFunc *cb, void *opaque);
68 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
69 int64_t sector_num, int nb_sectors,
71 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
72 int64_t sector_num, int nb_sectors,
74 static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs);
76 static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
77 QTAILQ_HEAD_INITIALIZER(bdrv_states);
79 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
80 QLIST_HEAD_INITIALIZER(bdrv_drivers);
82 /* The device to use for VM snapshots */
83 static BlockDriverState *bs_snapshots;
85 /* If non-zero, use only whitelisted block drivers */
86 static int use_bdrv_whitelist;
89 static int is_windows_drive_prefix(const char *filename)
91 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
92 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
96 int is_windows_drive(const char *filename)
98 if (is_windows_drive_prefix(filename) &&
101 if (strstart(filename, "\\\\.\\", NULL) ||
102 strstart(filename, "//./", NULL))
108 /* check if the path starts with "<protocol>:" */
109 static int path_has_protocol(const char *path)
112 if (is_windows_drive(path) ||
113 is_windows_drive_prefix(path)) {
118 return strchr(path, ':') != NULL;
121 int path_is_absolute(const char *path)
125 /* specific case for names like: "\\.\d:" */
126 if (*path == '/' || *path == '\\')
129 p = strchr(path, ':');
135 return (*p == '/' || *p == '\\');
141 /* if filename is absolute, just copy it to dest. Otherwise, build a
142 path to it by considering it is relative to base_path. URL are
144 void path_combine(char *dest, int dest_size,
145 const char *base_path,
146 const char *filename)
153 if (path_is_absolute(filename)) {
154 pstrcpy(dest, dest_size, filename);
156 p = strchr(base_path, ':');
161 p1 = strrchr(base_path, '/');
165 p2 = strrchr(base_path, '\\');
177 if (len > dest_size - 1)
179 memcpy(dest, base_path, len);
181 pstrcat(dest, dest_size, filename);
185 void bdrv_register(BlockDriver *bdrv)
187 if (bdrv->bdrv_co_readv) {
188 /* Emulate AIO by coroutines, and sync by AIO */
189 bdrv->bdrv_aio_readv = bdrv_co_aio_readv_em;
190 bdrv->bdrv_aio_writev = bdrv_co_aio_writev_em;
191 bdrv->bdrv_read = bdrv_read_em;
192 bdrv->bdrv_write = bdrv_write_em;
194 bdrv->bdrv_co_readv = bdrv_co_readv_em;
195 bdrv->bdrv_co_writev = bdrv_co_writev_em;
197 if (!bdrv->bdrv_aio_readv) {
198 /* add AIO emulation layer */
199 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
200 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
201 } else if (!bdrv->bdrv_read) {
202 /* add synchronous IO emulation layer */
203 bdrv->bdrv_read = bdrv_read_em;
204 bdrv->bdrv_write = bdrv_write_em;
208 if (!bdrv->bdrv_aio_flush)
209 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
211 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
214 /* create a new block device (by default it is empty) */
215 BlockDriverState *bdrv_new(const char *device_name)
217 BlockDriverState *bs;
219 bs = g_malloc0(sizeof(BlockDriverState));
220 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
221 if (device_name[0] != '\0') {
222 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
227 BlockDriver *bdrv_find_format(const char *format_name)
230 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
231 if (!strcmp(drv1->format_name, format_name)) {
238 static int bdrv_is_whitelisted(BlockDriver *drv)
240 static const char *whitelist[] = {
241 CONFIG_BDRV_WHITELIST
246 return 1; /* no whitelist, anything goes */
248 for (p = whitelist; *p; p++) {
249 if (!strcmp(drv->format_name, *p)) {
256 BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
258 BlockDriver *drv = bdrv_find_format(format_name);
259 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
262 int bdrv_create(BlockDriver *drv, const char* filename,
263 QEMUOptionParameter *options)
265 if (!drv->bdrv_create)
268 return drv->bdrv_create(filename, options);
271 int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
275 drv = bdrv_find_protocol(filename);
280 return bdrv_create(drv, filename, options);
284 void get_tmp_filename(char *filename, int size)
286 char temp_dir[MAX_PATH];
288 GetTempPath(MAX_PATH, temp_dir);
289 GetTempFileName(temp_dir, "qem", 0, filename);
292 void get_tmp_filename(char *filename, int size)
296 /* XXX: race condition possible */
297 tmpdir = getenv("TMPDIR");
300 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
301 fd = mkstemp(filename);
307 * Detect host devices. By convention, /dev/cdrom[N] is always
308 * recognized as a host CDROM.
310 static BlockDriver *find_hdev_driver(const char *filename)
312 int score_max = 0, score;
313 BlockDriver *drv = NULL, *d;
315 QLIST_FOREACH(d, &bdrv_drivers, list) {
316 if (d->bdrv_probe_device) {
317 score = d->bdrv_probe_device(filename);
318 if (score > score_max) {
328 BlockDriver *bdrv_find_protocol(const char *filename)
335 /* TODO Drivers without bdrv_file_open must be specified explicitly */
338 * XXX(hch): we really should not let host device detection
339 * override an explicit protocol specification, but moving this
340 * later breaks access to device names with colons in them.
341 * Thanks to the brain-dead persistent naming schemes on udev-
342 * based Linux systems those actually are quite common.
344 drv1 = find_hdev_driver(filename);
349 if (!path_has_protocol(filename)) {
350 return bdrv_find_format("file");
352 p = strchr(filename, ':');
355 if (len > sizeof(protocol) - 1)
356 len = sizeof(protocol) - 1;
357 memcpy(protocol, filename, len);
358 protocol[len] = '\0';
359 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
360 if (drv1->protocol_name &&
361 !strcmp(drv1->protocol_name, protocol)) {
368 static int find_image_format(const char *filename, BlockDriver **pdrv)
370 int ret, score, score_max;
371 BlockDriver *drv1, *drv;
373 BlockDriverState *bs;
375 ret = bdrv_file_open(&bs, filename, 0);
381 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
382 if (bs->sg || !bdrv_is_inserted(bs)) {
384 drv = bdrv_find_format("raw");
392 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
401 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
402 if (drv1->bdrv_probe) {
403 score = drv1->bdrv_probe(buf, ret, filename);
404 if (score > score_max) {
418 * Set the current 'total_sectors' value
420 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
422 BlockDriver *drv = bs->drv;
424 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
428 /* query actual device if possible, otherwise just trust the hint */
429 if (drv->bdrv_getlength) {
430 int64_t length = drv->bdrv_getlength(bs);
434 hint = length >> BDRV_SECTOR_BITS;
437 bs->total_sectors = hint;
442 * Set open flags for a given cache mode
444 * Return 0 on success, -1 if the cache mode was invalid.
446 int bdrv_parse_cache_flags(const char *mode, int *flags)
448 *flags &= ~BDRV_O_CACHE_MASK;
450 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
451 *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
452 } else if (!strcmp(mode, "directsync")) {
453 *flags |= BDRV_O_NOCACHE;
454 } else if (!strcmp(mode, "writeback")) {
455 *flags |= BDRV_O_CACHE_WB;
456 } else if (!strcmp(mode, "unsafe")) {
457 *flags |= BDRV_O_CACHE_WB;
458 *flags |= BDRV_O_NO_FLUSH;
459 } else if (!strcmp(mode, "writethrough")) {
460 /* this is the default */
469 * Common part for opening disk images and files
471 static int bdrv_open_common(BlockDriverState *bs, const char *filename,
472 int flags, BlockDriver *drv)
478 trace_bdrv_open_common(bs, filename, flags, drv->format_name);
481 bs->total_sectors = 0;
484 bs->open_flags = flags;
485 bs->buffer_alignment = 512;
487 pstrcpy(bs->filename, sizeof(bs->filename), filename);
489 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
494 bs->opaque = g_malloc0(drv->instance_size);
496 if (flags & BDRV_O_CACHE_WB)
497 bs->enable_write_cache = 1;
500 * Clear flags that are internal to the block layer before opening the
503 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
506 * Snapshots should be writable.
508 if (bs->is_temporary) {
509 open_flags |= BDRV_O_RDWR;
512 /* Open the image, either directly or using a protocol */
513 if (drv->bdrv_file_open) {
514 ret = drv->bdrv_file_open(bs, filename, open_flags);
516 ret = bdrv_file_open(&bs->file, filename, open_flags);
518 ret = drv->bdrv_open(bs, open_flags);
526 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
528 ret = refresh_total_sectors(bs, bs->total_sectors);
534 if (bs->is_temporary) {
542 bdrv_delete(bs->file);
552 * Opens a file using a protocol (file, host_device, nbd, ...)
554 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
556 BlockDriverState *bs;
560 drv = bdrv_find_protocol(filename);
566 ret = bdrv_open_common(bs, filename, flags, drv);
577 * Opens a disk image (raw, qcow2, vmdk, ...)
579 int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
584 if (flags & BDRV_O_SNAPSHOT) {
585 BlockDriverState *bs1;
588 BlockDriver *bdrv_qcow2;
589 QEMUOptionParameter *options;
590 char tmp_filename[PATH_MAX];
591 char backing_filename[PATH_MAX];
593 /* if snapshot, we create a temporary backing file and open it
594 instead of opening 'filename' directly */
596 /* if there is a backing file, use it */
598 ret = bdrv_open(bs1, filename, 0, drv);
603 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
605 if (bs1->drv && bs1->drv->protocol_name)
610 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
612 /* Real path is meaningless for protocols */
614 snprintf(backing_filename, sizeof(backing_filename),
616 else if (!realpath(filename, backing_filename))
619 bdrv_qcow2 = bdrv_find_format("qcow2");
620 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
622 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
623 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
625 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
629 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
630 free_option_parameters(options);
635 filename = tmp_filename;
637 bs->is_temporary = 1;
640 /* Find the right image format driver */
642 ret = find_image_format(filename, &drv);
646 goto unlink_and_fail;
650 ret = bdrv_open_common(bs, filename, flags, drv);
652 goto unlink_and_fail;
655 /* If there is a backing file, use it */
656 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
657 char backing_filename[PATH_MAX];
659 BlockDriver *back_drv = NULL;
661 bs->backing_hd = bdrv_new("");
663 if (path_has_protocol(bs->backing_file)) {
664 pstrcpy(backing_filename, sizeof(backing_filename),
667 path_combine(backing_filename, sizeof(backing_filename),
668 filename, bs->backing_file);
671 if (bs->backing_format[0] != '\0') {
672 back_drv = bdrv_find_format(bs->backing_format);
675 /* backing files always opened read-only */
677 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
679 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
684 if (bs->is_temporary) {
685 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
687 /* base image inherits from "parent" */
688 bs->backing_hd->keep_read_only = bs->keep_read_only;
692 if (!bdrv_key_required(bs)) {
693 bdrv_dev_change_media_cb(bs, true);
699 if (bs->is_temporary) {
705 void bdrv_close(BlockDriverState *bs)
708 if (bs == bs_snapshots) {
711 if (bs->backing_hd) {
712 bdrv_delete(bs->backing_hd);
713 bs->backing_hd = NULL;
715 bs->drv->bdrv_close(bs);
718 if (bs->is_temporary) {
719 unlink(bs->filename);
725 if (bs->file != NULL) {
726 bdrv_close(bs->file);
729 bdrv_dev_change_media_cb(bs, false);
733 void bdrv_close_all(void)
735 BlockDriverState *bs;
737 QTAILQ_FOREACH(bs, &bdrv_states, list) {
742 /* make a BlockDriverState anonymous by removing from bdrv_state list.
743 Also, NULL terminate the device_name to prevent double remove */
744 void bdrv_make_anon(BlockDriverState *bs)
746 if (bs->device_name[0] != '\0') {
747 QTAILQ_REMOVE(&bdrv_states, bs, list);
749 bs->device_name[0] = '\0';
752 void bdrv_delete(BlockDriverState *bs)
756 /* remove from list, if necessary */
760 if (bs->file != NULL) {
761 bdrv_delete(bs->file);
764 assert(bs != bs_snapshots);
768 int bdrv_attach_dev(BlockDriverState *bs, void *dev)
769 /* TODO change to DeviceState *dev when all users are qdevified */
778 /* TODO qdevified devices don't use this, remove when devices are qdevified */
779 void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
781 if (bdrv_attach_dev(bs, dev) < 0) {
786 void bdrv_detach_dev(BlockDriverState *bs, void *dev)
787 /* TODO change to DeviceState *dev when all users are qdevified */
789 assert(bs->dev == dev);
792 bs->dev_opaque = NULL;
793 bs->buffer_alignment = 512;
796 /* TODO change to return DeviceState * when all users are qdevified */
797 void *bdrv_get_attached_dev(BlockDriverState *bs)
802 void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
806 bs->dev_opaque = opaque;
807 if (bdrv_dev_has_removable_media(bs) && bs == bs_snapshots) {
812 static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
814 if (bs->dev_ops && bs->dev_ops->change_media_cb) {
815 bs->dev_ops->change_media_cb(bs->dev_opaque, load);
819 bool bdrv_dev_has_removable_media(BlockDriverState *bs)
821 return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
824 bool bdrv_dev_is_tray_open(BlockDriverState *bs)
826 if (bs->dev_ops && bs->dev_ops->is_tray_open) {
827 return bs->dev_ops->is_tray_open(bs->dev_opaque);
832 static void bdrv_dev_resize_cb(BlockDriverState *bs)
834 if (bs->dev_ops && bs->dev_ops->resize_cb) {
835 bs->dev_ops->resize_cb(bs->dev_opaque);
839 bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
841 if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
842 return bs->dev_ops->is_medium_locked(bs->dev_opaque);
848 * Run consistency checks on an image
850 * Returns 0 if the check could be completed (it doesn't mean that the image is
851 * free of errors) or -errno when an internal error occurred. The results of the
852 * check are stored in res.
854 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res)
856 if (bs->drv->bdrv_check == NULL) {
860 memset(res, 0, sizeof(*res));
861 return bs->drv->bdrv_check(bs, res);
864 #define COMMIT_BUF_SECTORS 2048
866 /* commit COW file into the raw image */
867 int bdrv_commit(BlockDriverState *bs)
869 BlockDriver *drv = bs->drv;
870 BlockDriver *backing_drv;
871 int64_t sector, total_sectors;
872 int n, ro, open_flags;
873 int ret = 0, rw_ret = 0;
876 BlockDriverState *bs_rw, *bs_ro;
881 if (!bs->backing_hd) {
885 if (bs->backing_hd->keep_read_only) {
889 backing_drv = bs->backing_hd->drv;
890 ro = bs->backing_hd->read_only;
891 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
892 open_flags = bs->backing_hd->open_flags;
896 bdrv_delete(bs->backing_hd);
897 bs->backing_hd = NULL;
898 bs_rw = bdrv_new("");
899 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR,
903 /* try to re-open read-only */
904 bs_ro = bdrv_new("");
905 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
909 /* drive not functional anymore */
913 bs->backing_hd = bs_ro;
916 bs->backing_hd = bs_rw;
919 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
920 buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
922 for (sector = 0; sector < total_sectors; sector += n) {
923 if (drv->bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {
925 if (bdrv_read(bs, sector, buf, n) != 0) {
930 if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {
937 if (drv->bdrv_make_empty) {
938 ret = drv->bdrv_make_empty(bs);
943 * Make sure all data we wrote to the backing device is actually
947 bdrv_flush(bs->backing_hd);
954 bdrv_delete(bs->backing_hd);
955 bs->backing_hd = NULL;
956 bs_ro = bdrv_new("");
957 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR,
961 /* drive not functional anymore */
965 bs->backing_hd = bs_ro;
966 bs->backing_hd->keep_read_only = 0;
972 void bdrv_commit_all(void)
974 BlockDriverState *bs;
976 QTAILQ_FOREACH(bs, &bdrv_states, list) {
984 * -EINVAL - backing format specified, but no file
985 * -ENOSPC - can't update the backing file because no space is left in the
987 * -ENOTSUP - format driver doesn't support changing the backing file
989 int bdrv_change_backing_file(BlockDriverState *bs,
990 const char *backing_file, const char *backing_fmt)
992 BlockDriver *drv = bs->drv;
994 if (drv->bdrv_change_backing_file != NULL) {
995 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
1001 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
1006 if (!bdrv_is_inserted(bs))
1012 len = bdrv_getlength(bs);
1017 if ((offset > len) || (len - offset < size))
1023 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
1026 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
1027 nb_sectors * BDRV_SECTOR_SIZE);
1030 static inline bool bdrv_has_async_rw(BlockDriver *drv)
1032 return drv->bdrv_co_readv != bdrv_co_readv_em
1033 || drv->bdrv_aio_readv != bdrv_aio_readv_em;
1036 static inline bool bdrv_has_async_flush(BlockDriver *drv)
1038 return drv->bdrv_aio_flush != bdrv_aio_flush_em;
1041 /* return < 0 if error. See bdrv_write() for the return codes */
1042 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
1043 uint8_t *buf, int nb_sectors)
1045 BlockDriver *drv = bs->drv;
1050 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1052 struct iovec iov = {
1053 .iov_base = (void *)buf,
1054 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1057 qemu_iovec_init_external(&qiov, &iov, 1);
1058 return bdrv_co_readv(bs, sector_num, nb_sectors, &qiov);
1061 if (bdrv_check_request(bs, sector_num, nb_sectors))
1064 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
1067 static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
1068 int nb_sectors, int dirty)
1071 unsigned long val, idx, bit;
1073 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
1074 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
1076 for (; start <= end; start++) {
1077 idx = start / (sizeof(unsigned long) * 8);
1078 bit = start % (sizeof(unsigned long) * 8);
1079 val = bs->dirty_bitmap[idx];
1081 if (!(val & (1UL << bit))) {
1086 if (val & (1UL << bit)) {
1088 val &= ~(1UL << bit);
1091 bs->dirty_bitmap[idx] = val;
1095 /* Return < 0 if error. Important errors are:
1096 -EIO generic I/O error (may happen for all errors)
1097 -ENOMEDIUM No media inserted.
1098 -EINVAL Invalid sector number or nb_sectors
1099 -EACCES Trying to write a read-only device
1101 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
1102 const uint8_t *buf, int nb_sectors)
1104 BlockDriver *drv = bs->drv;
1109 if (bdrv_has_async_rw(drv) && qemu_in_coroutine()) {
1111 struct iovec iov = {
1112 .iov_base = (void *)buf,
1113 .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
1116 qemu_iovec_init_external(&qiov, &iov, 1);
1117 return bdrv_co_writev(bs, sector_num, nb_sectors, &qiov);
1122 if (bdrv_check_request(bs, sector_num, nb_sectors))
1125 if (bs->dirty_bitmap) {
1126 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1129 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1130 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1133 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
1136 int bdrv_pread(BlockDriverState *bs, int64_t offset,
1137 void *buf, int count1)
1139 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1140 int len, nb_sectors, count;
1145 /* first read to align to sector start */
1146 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1149 sector_num = offset >> BDRV_SECTOR_BITS;
1151 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1153 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
1161 /* read the sectors "in place" */
1162 nb_sectors = count >> BDRV_SECTOR_BITS;
1163 if (nb_sectors > 0) {
1164 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
1166 sector_num += nb_sectors;
1167 len = nb_sectors << BDRV_SECTOR_BITS;
1172 /* add data from the last sector */
1174 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1176 memcpy(buf, tmp_buf, count);
1181 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
1182 const void *buf, int count1)
1184 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
1185 int len, nb_sectors, count;
1190 /* first write to align to sector start */
1191 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
1194 sector_num = offset >> BDRV_SECTOR_BITS;
1196 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1198 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
1199 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1208 /* write the sectors "in place" */
1209 nb_sectors = count >> BDRV_SECTOR_BITS;
1210 if (nb_sectors > 0) {
1211 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
1213 sector_num += nb_sectors;
1214 len = nb_sectors << BDRV_SECTOR_BITS;
1219 /* add data from the last sector */
1221 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1223 memcpy(tmp_buf, buf, count);
1224 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1231 * Writes to the file and ensures that no writes are reordered across this
1232 * request (acts as a barrier)
1234 * Returns 0 on success, -errno in error cases.
1236 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1237 const void *buf, int count)
1241 ret = bdrv_pwrite(bs, offset, buf, count);
1246 /* No flush needed for cache modes that use O_DSYNC */
1247 if ((bs->open_flags & BDRV_O_CACHE_WB) != 0) {
1254 int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
1255 int nb_sectors, QEMUIOVector *qiov)
1257 BlockDriver *drv = bs->drv;
1259 trace_bdrv_co_readv(bs, sector_num, nb_sectors);
1264 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1268 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1271 int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
1272 int nb_sectors, QEMUIOVector *qiov)
1274 BlockDriver *drv = bs->drv;
1276 trace_bdrv_co_writev(bs, sector_num, nb_sectors);
1281 if (bs->read_only) {
1284 if (bdrv_check_request(bs, sector_num, nb_sectors)) {
1288 if (bs->dirty_bitmap) {
1289 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1292 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1293 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1296 return drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
1300 * Truncate file to 'offset' bytes (needed only for file protocols)
1302 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1304 BlockDriver *drv = bs->drv;
1308 if (!drv->bdrv_truncate)
1312 if (bdrv_in_use(bs))
1314 ret = drv->bdrv_truncate(bs, offset);
1316 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1317 bdrv_dev_resize_cb(bs);
1323 * Length of a allocated file in bytes. Sparse files are counted by actual
1324 * allocated space. Return < 0 if error or unknown.
1326 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
1328 BlockDriver *drv = bs->drv;
1332 if (drv->bdrv_get_allocated_file_size) {
1333 return drv->bdrv_get_allocated_file_size(bs);
1336 return bdrv_get_allocated_file_size(bs->file);
1342 * Length of a file in bytes. Return < 0 if error or unknown.
1344 int64_t bdrv_getlength(BlockDriverState *bs)
1346 BlockDriver *drv = bs->drv;
1350 if (bs->growable || bdrv_dev_has_removable_media(bs)) {
1351 if (drv->bdrv_getlength) {
1352 return drv->bdrv_getlength(bs);
1355 return bs->total_sectors * BDRV_SECTOR_SIZE;
1358 /* return 0 as number of sectors if no device present or error */
1359 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1362 length = bdrv_getlength(bs);
1366 length = length >> BDRV_SECTOR_BITS;
1367 *nb_sectors_ptr = length;
1371 uint8_t boot_ind; /* 0x80 - active */
1372 uint8_t head; /* starting head */
1373 uint8_t sector; /* starting sector */
1374 uint8_t cyl; /* starting cylinder */
1375 uint8_t sys_ind; /* What partition type */
1376 uint8_t end_head; /* end head */
1377 uint8_t end_sector; /* end sector */
1378 uint8_t end_cyl; /* end cylinder */
1379 uint32_t start_sect; /* starting sector counting from 0 */
1380 uint32_t nr_sects; /* nr of sectors in partition */
1383 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1384 static int guess_disk_lchs(BlockDriverState *bs,
1385 int *pcylinders, int *pheads, int *psectors)
1387 uint8_t buf[BDRV_SECTOR_SIZE];
1388 int ret, i, heads, sectors, cylinders;
1389 struct partition *p;
1391 uint64_t nb_sectors;
1393 bdrv_get_geometry(bs, &nb_sectors);
1395 ret = bdrv_read(bs, 0, buf, 1);
1398 /* test msdos magic */
1399 if (buf[510] != 0x55 || buf[511] != 0xaa)
1401 for(i = 0; i < 4; i++) {
1402 p = ((struct partition *)(buf + 0x1be)) + i;
1403 nr_sects = le32_to_cpu(p->nr_sects);
1404 if (nr_sects && p->end_head) {
1405 /* We make the assumption that the partition terminates on
1406 a cylinder boundary */
1407 heads = p->end_head + 1;
1408 sectors = p->end_sector & 63;
1411 cylinders = nb_sectors / (heads * sectors);
1412 if (cylinders < 1 || cylinders > 16383)
1415 *psectors = sectors;
1416 *pcylinders = cylinders;
1418 printf("guessed geometry: LCHS=%d %d %d\n",
1419 cylinders, heads, sectors);
1427 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1429 int translation, lba_detected = 0;
1430 int cylinders, heads, secs;
1431 uint64_t nb_sectors;
1433 /* if a geometry hint is available, use it */
1434 bdrv_get_geometry(bs, &nb_sectors);
1435 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1436 translation = bdrv_get_translation_hint(bs);
1437 if (cylinders != 0) {
1442 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1444 /* if heads > 16, it means that a BIOS LBA
1445 translation was active, so the default
1446 hardware geometry is OK */
1448 goto default_geometry;
1453 /* disable any translation to be in sync with
1454 the logical geometry */
1455 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1456 bdrv_set_translation_hint(bs,
1457 BIOS_ATA_TRANSLATION_NONE);
1462 /* if no geometry, use a standard physical disk geometry */
1463 cylinders = nb_sectors / (16 * 63);
1465 if (cylinders > 16383)
1467 else if (cylinders < 2)
1472 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1473 if ((*pcyls * *pheads) <= 131072) {
1474 bdrv_set_translation_hint(bs,
1475 BIOS_ATA_TRANSLATION_LARGE);
1477 bdrv_set_translation_hint(bs,
1478 BIOS_ATA_TRANSLATION_LBA);
1482 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1486 void bdrv_set_geometry_hint(BlockDriverState *bs,
1487 int cyls, int heads, int secs)
1494 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1496 bs->translation = translation;
1499 void bdrv_get_geometry_hint(BlockDriverState *bs,
1500 int *pcyls, int *pheads, int *psecs)
1503 *pheads = bs->heads;
1507 /* Recognize floppy formats */
1508 typedef struct FDFormat {
1515 static const FDFormat fd_formats[] = {
1516 /* First entry is default format */
1517 /* 1.44 MB 3"1/2 floppy disks */
1518 { FDRIVE_DRV_144, 18, 80, 1, },
1519 { FDRIVE_DRV_144, 20, 80, 1, },
1520 { FDRIVE_DRV_144, 21, 80, 1, },
1521 { FDRIVE_DRV_144, 21, 82, 1, },
1522 { FDRIVE_DRV_144, 21, 83, 1, },
1523 { FDRIVE_DRV_144, 22, 80, 1, },
1524 { FDRIVE_DRV_144, 23, 80, 1, },
1525 { FDRIVE_DRV_144, 24, 80, 1, },
1526 /* 2.88 MB 3"1/2 floppy disks */
1527 { FDRIVE_DRV_288, 36, 80, 1, },
1528 { FDRIVE_DRV_288, 39, 80, 1, },
1529 { FDRIVE_DRV_288, 40, 80, 1, },
1530 { FDRIVE_DRV_288, 44, 80, 1, },
1531 { FDRIVE_DRV_288, 48, 80, 1, },
1532 /* 720 kB 3"1/2 floppy disks */
1533 { FDRIVE_DRV_144, 9, 80, 1, },
1534 { FDRIVE_DRV_144, 10, 80, 1, },
1535 { FDRIVE_DRV_144, 10, 82, 1, },
1536 { FDRIVE_DRV_144, 10, 83, 1, },
1537 { FDRIVE_DRV_144, 13, 80, 1, },
1538 { FDRIVE_DRV_144, 14, 80, 1, },
1539 /* 1.2 MB 5"1/4 floppy disks */
1540 { FDRIVE_DRV_120, 15, 80, 1, },
1541 { FDRIVE_DRV_120, 18, 80, 1, },
1542 { FDRIVE_DRV_120, 18, 82, 1, },
1543 { FDRIVE_DRV_120, 18, 83, 1, },
1544 { FDRIVE_DRV_120, 20, 80, 1, },
1545 /* 720 kB 5"1/4 floppy disks */
1546 { FDRIVE_DRV_120, 9, 80, 1, },
1547 { FDRIVE_DRV_120, 11, 80, 1, },
1548 /* 360 kB 5"1/4 floppy disks */
1549 { FDRIVE_DRV_120, 9, 40, 1, },
1550 { FDRIVE_DRV_120, 9, 40, 0, },
1551 { FDRIVE_DRV_120, 10, 41, 1, },
1552 { FDRIVE_DRV_120, 10, 42, 1, },
1553 /* 320 kB 5"1/4 floppy disks */
1554 { FDRIVE_DRV_120, 8, 40, 1, },
1555 { FDRIVE_DRV_120, 8, 40, 0, },
1556 /* 360 kB must match 5"1/4 better than 3"1/2... */
1557 { FDRIVE_DRV_144, 9, 80, 0, },
1559 { FDRIVE_DRV_NONE, -1, -1, 0, },
1562 void bdrv_get_floppy_geometry_hint(BlockDriverState *bs, int *nb_heads,
1563 int *max_track, int *last_sect,
1564 FDriveType drive_in, FDriveType *drive)
1566 const FDFormat *parse;
1567 uint64_t nb_sectors, size;
1568 int i, first_match, match;
1570 bdrv_get_geometry_hint(bs, nb_heads, max_track, last_sect);
1571 if (*nb_heads != 0 && *max_track != 0 && *last_sect != 0) {
1572 /* User defined disk */
1574 bdrv_get_geometry(bs, &nb_sectors);
1577 for (i = 0; ; i++) {
1578 parse = &fd_formats[i];
1579 if (parse->drive == FDRIVE_DRV_NONE) {
1582 if (drive_in == parse->drive ||
1583 drive_in == FDRIVE_DRV_NONE) {
1584 size = (parse->max_head + 1) * parse->max_track *
1586 if (nb_sectors == size) {
1590 if (first_match == -1) {
1596 if (first_match == -1) {
1599 match = first_match;
1601 parse = &fd_formats[match];
1603 *nb_heads = parse->max_head + 1;
1604 *max_track = parse->max_track;
1605 *last_sect = parse->last_sect;
1606 *drive = parse->drive;
1610 int bdrv_get_translation_hint(BlockDriverState *bs)
1612 return bs->translation;
1615 void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1616 BlockErrorAction on_write_error)
1618 bs->on_read_error = on_read_error;
1619 bs->on_write_error = on_write_error;
1622 BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1624 return is_read ? bs->on_read_error : bs->on_write_error;
1627 int bdrv_is_read_only(BlockDriverState *bs)
1629 return bs->read_only;
1632 int bdrv_is_sg(BlockDriverState *bs)
1637 int bdrv_enable_write_cache(BlockDriverState *bs)
1639 return bs->enable_write_cache;
1642 int bdrv_is_encrypted(BlockDriverState *bs)
1644 if (bs->backing_hd && bs->backing_hd->encrypted)
1646 return bs->encrypted;
1649 int bdrv_key_required(BlockDriverState *bs)
1651 BlockDriverState *backing_hd = bs->backing_hd;
1653 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1655 return (bs->encrypted && !bs->valid_key);
1658 int bdrv_set_key(BlockDriverState *bs, const char *key)
1661 if (bs->backing_hd && bs->backing_hd->encrypted) {
1662 ret = bdrv_set_key(bs->backing_hd, key);
1668 if (!bs->encrypted) {
1670 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1673 ret = bs->drv->bdrv_set_key(bs, key);
1676 } else if (!bs->valid_key) {
1678 /* call the change callback now, we skipped it on open */
1679 bdrv_dev_change_media_cb(bs, true);
1684 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1689 pstrcpy(buf, buf_size, bs->drv->format_name);
1693 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1698 QLIST_FOREACH(drv, &bdrv_drivers, list) {
1699 it(opaque, drv->format_name);
1703 BlockDriverState *bdrv_find(const char *name)
1705 BlockDriverState *bs;
1707 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1708 if (!strcmp(name, bs->device_name)) {
1715 BlockDriverState *bdrv_next(BlockDriverState *bs)
1718 return QTAILQ_FIRST(&bdrv_states);
1720 return QTAILQ_NEXT(bs, list);
1723 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1725 BlockDriverState *bs;
1727 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1732 const char *bdrv_get_device_name(BlockDriverState *bs)
1734 return bs->device_name;
1737 int bdrv_flush(BlockDriverState *bs)
1739 if (bs->open_flags & BDRV_O_NO_FLUSH) {
1743 if (bs->drv && bdrv_has_async_flush(bs->drv) && qemu_in_coroutine()) {
1744 return bdrv_co_flush_em(bs);
1747 if (bs->drv && bs->drv->bdrv_flush) {
1748 return bs->drv->bdrv_flush(bs);
1752 * Some block drivers always operate in either writethrough or unsafe mode
1753 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1754 * the server works (because the behaviour is hardcoded or depends on
1755 * server-side configuration), so we can't ensure that everything is safe
1756 * on disk. Returning an error doesn't work because that would break guests
1757 * even if the server operates in writethrough mode.
1759 * Let's hope the user knows what he's doing.
1764 void bdrv_flush_all(void)
1766 BlockDriverState *bs;
1768 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1769 if (!bdrv_is_read_only(bs) && bdrv_is_inserted(bs)) {
1775 int bdrv_has_zero_init(BlockDriverState *bs)
1779 if (bs->drv->bdrv_has_zero_init) {
1780 return bs->drv->bdrv_has_zero_init(bs);
1786 int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
1791 if (!bs->drv->bdrv_discard) {
1794 return bs->drv->bdrv_discard(bs, sector_num, nb_sectors);
1798 * Returns true iff the specified sector is present in the disk image. Drivers
1799 * not implementing the functionality are assumed to not support backing files,
1800 * hence all their sectors are reported as allocated.
1802 * 'pnum' is set to the number of sectors (including and immediately following
1803 * the specified sector) that are known to be in the same
1804 * allocated/unallocated state.
1806 * 'nb_sectors' is the max value 'pnum' should be set to.
1808 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1812 if (!bs->drv->bdrv_is_allocated) {
1813 if (sector_num >= bs->total_sectors) {
1817 n = bs->total_sectors - sector_num;
1818 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1821 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1824 void bdrv_mon_event(const BlockDriverState *bdrv,
1825 BlockMonEventAction action, int is_read)
1828 const char *action_str;
1831 case BDRV_ACTION_REPORT:
1832 action_str = "report";
1834 case BDRV_ACTION_IGNORE:
1835 action_str = "ignore";
1837 case BDRV_ACTION_STOP:
1838 action_str = "stop";
1844 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1847 is_read ? "read" : "write");
1848 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1850 qobject_decref(data);
1853 static void bdrv_print_dict(QObject *obj, void *opaque)
1856 Monitor *mon = opaque;
1858 bs_dict = qobject_to_qdict(obj);
1860 monitor_printf(mon, "%s: removable=%d",
1861 qdict_get_str(bs_dict, "device"),
1862 qdict_get_bool(bs_dict, "removable"));
1864 if (qdict_get_bool(bs_dict, "removable")) {
1865 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1866 monitor_printf(mon, " tray-open=%d",
1867 qdict_get_bool(bs_dict, "tray-open"));
1869 if (qdict_haskey(bs_dict, "inserted")) {
1870 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1872 monitor_printf(mon, " file=");
1873 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1874 if (qdict_haskey(qdict, "backing_file")) {
1875 monitor_printf(mon, " backing_file=");
1876 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1878 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1879 qdict_get_bool(qdict, "ro"),
1880 qdict_get_str(qdict, "drv"),
1881 qdict_get_bool(qdict, "encrypted"));
1883 monitor_printf(mon, " [not inserted]");
1886 monitor_printf(mon, "\n");
1889 void bdrv_info_print(Monitor *mon, const QObject *data)
1891 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1894 void bdrv_info(Monitor *mon, QObject **ret_data)
1897 BlockDriverState *bs;
1899 bs_list = qlist_new();
1901 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1905 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
1906 "'removable': %i, 'locked': %i }",
1908 bdrv_dev_has_removable_media(bs),
1909 bdrv_dev_is_medium_locked(bs));
1910 bs_dict = qobject_to_qdict(bs_obj);
1912 if (bdrv_dev_has_removable_media(bs)) {
1913 qdict_put(bs_dict, "tray-open",
1914 qbool_from_int(bdrv_dev_is_tray_open(bs)));
1919 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1920 "'encrypted': %i }",
1921 bs->filename, bs->read_only,
1922 bs->drv->format_name,
1923 bdrv_is_encrypted(bs));
1924 if (bs->backing_file[0] != '\0') {
1925 QDict *qdict = qobject_to_qdict(obj);
1926 qdict_put(qdict, "backing_file",
1927 qstring_from_str(bs->backing_file));
1930 qdict_put_obj(bs_dict, "inserted", obj);
1932 qlist_append_obj(bs_list, bs_obj);
1935 *ret_data = QOBJECT(bs_list);
1938 static void bdrv_stats_iter(QObject *data, void *opaque)
1941 Monitor *mon = opaque;
1943 qdict = qobject_to_qdict(data);
1944 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1946 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1947 monitor_printf(mon, " rd_bytes=%" PRId64
1948 " wr_bytes=%" PRId64
1949 " rd_operations=%" PRId64
1950 " wr_operations=%" PRId64
1951 " flush_operations=%" PRId64
1952 " wr_total_time_ns=%" PRId64
1953 " rd_total_time_ns=%" PRId64
1954 " flush_total_time_ns=%" PRId64
1956 qdict_get_int(qdict, "rd_bytes"),
1957 qdict_get_int(qdict, "wr_bytes"),
1958 qdict_get_int(qdict, "rd_operations"),
1959 qdict_get_int(qdict, "wr_operations"),
1960 qdict_get_int(qdict, "flush_operations"),
1961 qdict_get_int(qdict, "wr_total_time_ns"),
1962 qdict_get_int(qdict, "rd_total_time_ns"),
1963 qdict_get_int(qdict, "flush_total_time_ns"));
1966 void bdrv_stats_print(Monitor *mon, const QObject *data)
1968 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1971 static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1976 res = qobject_from_jsonf("{ 'stats': {"
1977 "'rd_bytes': %" PRId64 ","
1978 "'wr_bytes': %" PRId64 ","
1979 "'rd_operations': %" PRId64 ","
1980 "'wr_operations': %" PRId64 ","
1981 "'wr_highest_offset': %" PRId64 ","
1982 "'flush_operations': %" PRId64 ","
1983 "'wr_total_time_ns': %" PRId64 ","
1984 "'rd_total_time_ns': %" PRId64 ","
1985 "'flush_total_time_ns': %" PRId64
1987 bs->nr_bytes[BDRV_ACCT_READ],
1988 bs->nr_bytes[BDRV_ACCT_WRITE],
1989 bs->nr_ops[BDRV_ACCT_READ],
1990 bs->nr_ops[BDRV_ACCT_WRITE],
1991 bs->wr_highest_sector *
1992 (uint64_t)BDRV_SECTOR_SIZE,
1993 bs->nr_ops[BDRV_ACCT_FLUSH],
1994 bs->total_time_ns[BDRV_ACCT_WRITE],
1995 bs->total_time_ns[BDRV_ACCT_READ],
1996 bs->total_time_ns[BDRV_ACCT_FLUSH]);
1997 dict = qobject_to_qdict(res);
1999 if (*bs->device_name) {
2000 qdict_put(dict, "device", qstring_from_str(bs->device_name));
2004 QObject *parent = bdrv_info_stats_bs(bs->file);
2005 qdict_put_obj(dict, "parent", parent);
2011 void bdrv_info_stats(Monitor *mon, QObject **ret_data)
2015 BlockDriverState *bs;
2017 devices = qlist_new();
2019 QTAILQ_FOREACH(bs, &bdrv_states, list) {
2020 obj = bdrv_info_stats_bs(bs);
2021 qlist_append_obj(devices, obj);
2024 *ret_data = QOBJECT(devices);
2027 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2029 if (bs->backing_hd && bs->backing_hd->encrypted)
2030 return bs->backing_file;
2031 else if (bs->encrypted)
2032 return bs->filename;
2037 void bdrv_get_backing_filename(BlockDriverState *bs,
2038 char *filename, int filename_size)
2040 if (!bs->backing_file) {
2041 pstrcpy(filename, filename_size, "");
2043 pstrcpy(filename, filename_size, bs->backing_file);
2047 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
2048 const uint8_t *buf, int nb_sectors)
2050 BlockDriver *drv = bs->drv;
2053 if (!drv->bdrv_write_compressed)
2055 if (bdrv_check_request(bs, sector_num, nb_sectors))
2058 if (bs->dirty_bitmap) {
2059 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
2062 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
2065 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2067 BlockDriver *drv = bs->drv;
2070 if (!drv->bdrv_get_info)
2072 memset(bdi, 0, sizeof(*bdi));
2073 return drv->bdrv_get_info(bs, bdi);
2076 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2077 int64_t pos, int size)
2079 BlockDriver *drv = bs->drv;
2082 if (drv->bdrv_save_vmstate)
2083 return drv->bdrv_save_vmstate(bs, buf, pos, size);
2085 return bdrv_save_vmstate(bs->file, buf, pos, size);
2089 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2090 int64_t pos, int size)
2092 BlockDriver *drv = bs->drv;
2095 if (drv->bdrv_load_vmstate)
2096 return drv->bdrv_load_vmstate(bs, buf, pos, size);
2098 return bdrv_load_vmstate(bs->file, buf, pos, size);
2102 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
2104 BlockDriver *drv = bs->drv;
2106 if (!drv || !drv->bdrv_debug_event) {
2110 return drv->bdrv_debug_event(bs, event);
2114 /**************************************************************/
2115 /* handling of snapshots */
2117 int bdrv_can_snapshot(BlockDriverState *bs)
2119 BlockDriver *drv = bs->drv;
2120 if (!drv || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
2124 if (!drv->bdrv_snapshot_create) {
2125 if (bs->file != NULL) {
2126 return bdrv_can_snapshot(bs->file);
2134 int bdrv_is_snapshot(BlockDriverState *bs)
2136 return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2139 BlockDriverState *bdrv_snapshots(void)
2141 BlockDriverState *bs;
2144 return bs_snapshots;
2148 while ((bs = bdrv_next(bs))) {
2149 if (bdrv_can_snapshot(bs)) {
2157 int bdrv_snapshot_create(BlockDriverState *bs,
2158 QEMUSnapshotInfo *sn_info)
2160 BlockDriver *drv = bs->drv;
2163 if (drv->bdrv_snapshot_create)
2164 return drv->bdrv_snapshot_create(bs, sn_info);
2166 return bdrv_snapshot_create(bs->file, sn_info);
2170 int bdrv_snapshot_goto(BlockDriverState *bs,
2171 const char *snapshot_id)
2173 BlockDriver *drv = bs->drv;
2178 if (drv->bdrv_snapshot_goto)
2179 return drv->bdrv_snapshot_goto(bs, snapshot_id);
2182 drv->bdrv_close(bs);
2183 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
2184 open_ret = drv->bdrv_open(bs, bs->open_flags);
2186 bdrv_delete(bs->file);
2196 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
2198 BlockDriver *drv = bs->drv;
2201 if (drv->bdrv_snapshot_delete)
2202 return drv->bdrv_snapshot_delete(bs, snapshot_id);
2204 return bdrv_snapshot_delete(bs->file, snapshot_id);
2208 int bdrv_snapshot_list(BlockDriverState *bs,
2209 QEMUSnapshotInfo **psn_info)
2211 BlockDriver *drv = bs->drv;
2214 if (drv->bdrv_snapshot_list)
2215 return drv->bdrv_snapshot_list(bs, psn_info);
2217 return bdrv_snapshot_list(bs->file, psn_info);
2221 int bdrv_snapshot_load_tmp(BlockDriverState *bs,
2222 const char *snapshot_name)
2224 BlockDriver *drv = bs->drv;
2228 if (!bs->read_only) {
2231 if (drv->bdrv_snapshot_load_tmp) {
2232 return drv->bdrv_snapshot_load_tmp(bs, snapshot_name);
2237 #define NB_SUFFIXES 4
2239 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
2241 static const char suffixes[NB_SUFFIXES] = "KMGT";
2246 snprintf(buf, buf_size, "%" PRId64, size);
2249 for(i = 0; i < NB_SUFFIXES; i++) {
2250 if (size < (10 * base)) {
2251 snprintf(buf, buf_size, "%0.1f%c",
2252 (double)size / base,
2255 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
2256 snprintf(buf, buf_size, "%" PRId64 "%c",
2257 ((size + (base >> 1)) / base),
2267 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
2269 char buf1[128], date_buf[128], clock_buf[128];
2279 snprintf(buf, buf_size,
2280 "%-10s%-20s%7s%20s%15s",
2281 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2285 ptm = localtime(&ti);
2286 strftime(date_buf, sizeof(date_buf),
2287 "%Y-%m-%d %H:%M:%S", ptm);
2289 localtime_r(&ti, &tm);
2290 strftime(date_buf, sizeof(date_buf),
2291 "%Y-%m-%d %H:%M:%S", &tm);
2293 secs = sn->vm_clock_nsec / 1000000000;
2294 snprintf(clock_buf, sizeof(clock_buf),
2295 "%02d:%02d:%02d.%03d",
2297 (int)((secs / 60) % 60),
2299 (int)((sn->vm_clock_nsec / 1000000) % 1000));
2300 snprintf(buf, buf_size,
2301 "%-10s%-20s%7s%20s%15s",
2302 sn->id_str, sn->name,
2303 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
2310 /**************************************************************/
2313 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
2314 QEMUIOVector *qiov, int nb_sectors,
2315 BlockDriverCompletionFunc *cb, void *opaque)
2317 BlockDriver *drv = bs->drv;
2319 trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
2323 if (bdrv_check_request(bs, sector_num, nb_sectors))
2326 return drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
2330 typedef struct BlockCompleteData {
2331 BlockDriverCompletionFunc *cb;
2333 BlockDriverState *bs;
2336 } BlockCompleteData;
2338 static void block_complete_cb(void *opaque, int ret)
2340 BlockCompleteData *b = opaque;
2342 if (b->bs->dirty_bitmap) {
2343 set_dirty_bitmap(b->bs, b->sector_num, b->nb_sectors, 1);
2345 b->cb(b->opaque, ret);
2349 static BlockCompleteData *blk_dirty_cb_alloc(BlockDriverState *bs,
2352 BlockDriverCompletionFunc *cb,
2355 BlockCompleteData *blkdata = g_malloc0(sizeof(BlockCompleteData));
2359 blkdata->opaque = opaque;
2360 blkdata->sector_num = sector_num;
2361 blkdata->nb_sectors = nb_sectors;
2366 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
2367 QEMUIOVector *qiov, int nb_sectors,
2368 BlockDriverCompletionFunc *cb, void *opaque)
2370 BlockDriver *drv = bs->drv;
2371 BlockDriverAIOCB *ret;
2372 BlockCompleteData *blk_cb_data;
2374 trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
2380 if (bdrv_check_request(bs, sector_num, nb_sectors))
2383 if (bs->dirty_bitmap) {
2384 blk_cb_data = blk_dirty_cb_alloc(bs, sector_num, nb_sectors, cb,
2386 cb = &block_complete_cb;
2387 opaque = blk_cb_data;
2390 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
2394 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
2395 bs->wr_highest_sector = sector_num + nb_sectors - 1;
2403 typedef struct MultiwriteCB {
2408 BlockDriverCompletionFunc *cb;
2410 QEMUIOVector *free_qiov;
2415 static void multiwrite_user_cb(MultiwriteCB *mcb)
2419 for (i = 0; i < mcb->num_callbacks; i++) {
2420 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
2421 if (mcb->callbacks[i].free_qiov) {
2422 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
2424 g_free(mcb->callbacks[i].free_qiov);
2425 qemu_vfree(mcb->callbacks[i].free_buf);
2429 static void multiwrite_cb(void *opaque, int ret)
2431 MultiwriteCB *mcb = opaque;
2433 trace_multiwrite_cb(mcb, ret);
2435 if (ret < 0 && !mcb->error) {
2439 mcb->num_requests--;
2440 if (mcb->num_requests == 0) {
2441 multiwrite_user_cb(mcb);
2446 static int multiwrite_req_compare(const void *a, const void *b)
2448 const BlockRequest *req1 = a, *req2 = b;
2451 * Note that we can't simply subtract req2->sector from req1->sector
2452 * here as that could overflow the return value.
2454 if (req1->sector > req2->sector) {
2456 } else if (req1->sector < req2->sector) {
2464 * Takes a bunch of requests and tries to merge them. Returns the number of
2465 * requests that remain after merging.
2467 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2468 int num_reqs, MultiwriteCB *mcb)
2472 // Sort requests by start sector
2473 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2475 // Check if adjacent requests touch the same clusters. If so, combine them,
2476 // filling up gaps with zero sectors.
2478 for (i = 1; i < num_reqs; i++) {
2480 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2482 // This handles the cases that are valid for all block drivers, namely
2483 // exactly sequential writes and overlapping writes.
2484 if (reqs[i].sector <= oldreq_last) {
2488 // The block driver may decide that it makes sense to combine requests
2489 // even if there is a gap of some sectors between them. In this case,
2490 // the gap is filled with zeros (therefore only applicable for yet
2491 // unused space in format like qcow2).
2492 if (!merge && bs->drv->bdrv_merge_requests) {
2493 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2496 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2502 QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
2503 qemu_iovec_init(qiov,
2504 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2506 // Add the first request to the merged one. If the requests are
2507 // overlapping, drop the last sectors of the first request.
2508 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2509 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2511 // We might need to add some zeros between the two requests
2512 if (reqs[i].sector > oldreq_last) {
2513 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2514 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2515 memset(buf, 0, zero_bytes);
2516 qemu_iovec_add(qiov, buf, zero_bytes);
2517 mcb->callbacks[i].free_buf = buf;
2520 // Add the second request
2521 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2523 reqs[outidx].nb_sectors = qiov->size >> 9;
2524 reqs[outidx].qiov = qiov;
2526 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2529 reqs[outidx].sector = reqs[i].sector;
2530 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2531 reqs[outidx].qiov = reqs[i].qiov;
2539 * Submit multiple AIO write requests at once.
2541 * On success, the function returns 0 and all requests in the reqs array have
2542 * been submitted. In error case this function returns -1, and any of the
2543 * requests may or may not be submitted yet. In particular, this means that the
2544 * callback will be called for some of the requests, for others it won't. The
2545 * caller must check the error field of the BlockRequest to wait for the right
2546 * callbacks (if error != 0, no callback will be called).
2548 * The implementation may modify the contents of the reqs array, e.g. to merge
2549 * requests. However, the fields opaque and error are left unmodified as they
2550 * are used to signal failure for a single request to the caller.
2552 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2554 BlockDriverAIOCB *acb;
2558 /* don't submit writes if we don't have a medium */
2559 if (bs->drv == NULL) {
2560 for (i = 0; i < num_reqs; i++) {
2561 reqs[i].error = -ENOMEDIUM;
2566 if (num_reqs == 0) {
2570 // Create MultiwriteCB structure
2571 mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
2572 mcb->num_requests = 0;
2573 mcb->num_callbacks = num_reqs;
2575 for (i = 0; i < num_reqs; i++) {
2576 mcb->callbacks[i].cb = reqs[i].cb;
2577 mcb->callbacks[i].opaque = reqs[i].opaque;
2580 // Check for mergable requests
2581 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2583 trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
2586 * Run the aio requests. As soon as one request can't be submitted
2587 * successfully, fail all requests that are not yet submitted (we must
2588 * return failure for all requests anyway)
2590 * num_requests cannot be set to the right value immediately: If
2591 * bdrv_aio_writev fails for some request, num_requests would be too high
2592 * and therefore multiwrite_cb() would never recognize the multiwrite
2593 * request as completed. We also cannot use the loop variable i to set it
2594 * when the first request fails because the callback may already have been
2595 * called for previously submitted requests. Thus, num_requests must be
2596 * incremented for each request that is submitted.
2598 * The problem that callbacks may be called early also means that we need
2599 * to take care that num_requests doesn't become 0 before all requests are
2600 * submitted - multiwrite_cb() would consider the multiwrite request
2601 * completed. A dummy request that is "completed" by a manual call to
2602 * multiwrite_cb() takes care of this.
2604 mcb->num_requests = 1;
2606 // Run the aio requests
2607 for (i = 0; i < num_reqs; i++) {
2608 mcb->num_requests++;
2609 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2610 reqs[i].nb_sectors, multiwrite_cb, mcb);
2613 // We can only fail the whole thing if no request has been
2614 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2615 // complete and report the error in the callback.
2617 trace_bdrv_aio_multiwrite_earlyfail(mcb);
2620 trace_bdrv_aio_multiwrite_latefail(mcb, i);
2621 multiwrite_cb(mcb, -EIO);
2627 /* Complete the dummy request */
2628 multiwrite_cb(mcb, 0);
2633 for (i = 0; i < mcb->num_callbacks; i++) {
2634 reqs[i].error = -EIO;
2640 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2641 BlockDriverCompletionFunc *cb, void *opaque)
2643 BlockDriver *drv = bs->drv;
2645 trace_bdrv_aio_flush(bs, opaque);
2647 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2648 return bdrv_aio_noop_em(bs, cb, opaque);
2653 return drv->bdrv_aio_flush(bs, cb, opaque);
2656 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
2658 acb->pool->cancel(acb);
2662 /**************************************************************/
2663 /* async block device emulation */
2665 typedef struct BlockDriverAIOCBSync {
2666 BlockDriverAIOCB common;
2669 /* vector translation state */
2673 } BlockDriverAIOCBSync;
2675 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2677 BlockDriverAIOCBSync *acb =
2678 container_of(blockacb, BlockDriverAIOCBSync, common);
2679 qemu_bh_delete(acb->bh);
2681 qemu_aio_release(acb);
2684 static AIOPool bdrv_em_aio_pool = {
2685 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2686 .cancel = bdrv_aio_cancel_em,
2689 static void bdrv_aio_bh_cb(void *opaque)
2691 BlockDriverAIOCBSync *acb = opaque;
2694 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2695 qemu_vfree(acb->bounce);
2696 acb->common.cb(acb->common.opaque, acb->ret);
2697 qemu_bh_delete(acb->bh);
2699 qemu_aio_release(acb);
2702 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2706 BlockDriverCompletionFunc *cb,
2711 BlockDriverAIOCBSync *acb;
2713 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2714 acb->is_write = is_write;
2716 acb->bounce = qemu_blockalign(bs, qiov->size);
2719 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2722 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2723 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2725 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2728 qemu_bh_schedule(acb->bh);
2730 return &acb->common;
2733 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2734 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2735 BlockDriverCompletionFunc *cb, void *opaque)
2737 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2740 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2741 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2742 BlockDriverCompletionFunc *cb, void *opaque)
2744 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2748 typedef struct BlockDriverAIOCBCoroutine {
2749 BlockDriverAIOCB common;
2753 } BlockDriverAIOCBCoroutine;
2755 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
2760 static AIOPool bdrv_em_co_aio_pool = {
2761 .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
2762 .cancel = bdrv_aio_co_cancel_em,
2765 static void bdrv_co_rw_bh(void *opaque)
2767 BlockDriverAIOCBCoroutine *acb = opaque;
2769 acb->common.cb(acb->common.opaque, acb->req.error);
2770 qemu_bh_delete(acb->bh);
2771 qemu_aio_release(acb);
2774 static void coroutine_fn bdrv_co_rw(void *opaque)
2776 BlockDriverAIOCBCoroutine *acb = opaque;
2777 BlockDriverState *bs = acb->common.bs;
2779 if (!acb->is_write) {
2780 acb->req.error = bs->drv->bdrv_co_readv(bs, acb->req.sector,
2781 acb->req.nb_sectors, acb->req.qiov);
2783 acb->req.error = bs->drv->bdrv_co_writev(bs, acb->req.sector,
2784 acb->req.nb_sectors, acb->req.qiov);
2787 acb->bh = qemu_bh_new(bdrv_co_rw_bh, acb);
2788 qemu_bh_schedule(acb->bh);
2791 static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
2795 BlockDriverCompletionFunc *cb,
2800 BlockDriverAIOCBCoroutine *acb;
2802 acb = qemu_aio_get(&bdrv_em_co_aio_pool, bs, cb, opaque);
2803 acb->req.sector = sector_num;
2804 acb->req.nb_sectors = nb_sectors;
2805 acb->req.qiov = qiov;
2806 acb->is_write = is_write;
2808 co = qemu_coroutine_create(bdrv_co_rw);
2809 qemu_coroutine_enter(co, acb);
2811 return &acb->common;
2814 static BlockDriverAIOCB *bdrv_co_aio_readv_em(BlockDriverState *bs,
2815 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2816 BlockDriverCompletionFunc *cb, void *opaque)
2818 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2822 static BlockDriverAIOCB *bdrv_co_aio_writev_em(BlockDriverState *bs,
2823 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2824 BlockDriverCompletionFunc *cb, void *opaque)
2826 return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque,
2830 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2831 BlockDriverCompletionFunc *cb, void *opaque)
2833 BlockDriverAIOCBSync *acb;
2835 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2836 acb->is_write = 1; /* don't bounce in the completion hadler */
2842 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2845 qemu_bh_schedule(acb->bh);
2846 return &acb->common;
2849 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2850 BlockDriverCompletionFunc *cb, void *opaque)
2852 BlockDriverAIOCBSync *acb;
2854 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2855 acb->is_write = 1; /* don't bounce in the completion handler */
2861 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2864 qemu_bh_schedule(acb->bh);
2865 return &acb->common;
2868 /**************************************************************/
2869 /* sync block device emulation */
2871 static void bdrv_rw_em_cb(void *opaque, int ret)
2873 *(int *)opaque = ret;
2876 #define NOT_DONE 0x7fffffff
2878 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
2879 uint8_t *buf, int nb_sectors)
2882 BlockDriverAIOCB *acb;
2886 async_ret = NOT_DONE;
2887 iov.iov_base = (void *)buf;
2888 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2889 qemu_iovec_init_external(&qiov, &iov, 1);
2890 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2891 bdrv_rw_em_cb, &async_ret);
2897 while (async_ret == NOT_DONE) {
2906 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2907 const uint8_t *buf, int nb_sectors)
2910 BlockDriverAIOCB *acb;
2914 async_ret = NOT_DONE;
2915 iov.iov_base = (void *)buf;
2916 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2917 qemu_iovec_init_external(&qiov, &iov, 1);
2918 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2919 bdrv_rw_em_cb, &async_ret);
2924 while (async_ret == NOT_DONE) {
2932 void bdrv_init(void)
2934 module_call_init(MODULE_INIT_BLOCK);
2937 void bdrv_init_with_whitelist(void)
2939 use_bdrv_whitelist = 1;
2943 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2944 BlockDriverCompletionFunc *cb, void *opaque)
2946 BlockDriverAIOCB *acb;
2948 if (pool->free_aiocb) {
2949 acb = pool->free_aiocb;
2950 pool->free_aiocb = acb->next;
2952 acb = g_malloc0(pool->aiocb_size);
2957 acb->opaque = opaque;
2961 void qemu_aio_release(void *p)
2963 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2964 AIOPool *pool = acb->pool;
2965 acb->next = pool->free_aiocb;
2966 pool->free_aiocb = acb;
2969 /**************************************************************/
2970 /* Coroutine block device emulation */
2972 typedef struct CoroutineIOCompletion {
2973 Coroutine *coroutine;
2975 } CoroutineIOCompletion;
2977 static void bdrv_co_io_em_complete(void *opaque, int ret)
2979 CoroutineIOCompletion *co = opaque;
2982 qemu_coroutine_enter(co->coroutine, NULL);
2985 static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
2986 int nb_sectors, QEMUIOVector *iov,
2989 CoroutineIOCompletion co = {
2990 .coroutine = qemu_coroutine_self(),
2992 BlockDriverAIOCB *acb;
2995 acb = bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
2996 bdrv_co_io_em_complete, &co);
2998 acb = bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
2999 bdrv_co_io_em_complete, &co);
3002 trace_bdrv_co_io(is_write, acb);
3006 qemu_coroutine_yield();
3011 static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
3012 int64_t sector_num, int nb_sectors,
3015 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
3018 static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
3019 int64_t sector_num, int nb_sectors,
3022 return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
3025 static int coroutine_fn bdrv_co_flush_em(BlockDriverState *bs)
3027 CoroutineIOCompletion co = {
3028 .coroutine = qemu_coroutine_self(),
3030 BlockDriverAIOCB *acb;
3032 acb = bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
3036 qemu_coroutine_yield();
3040 /**************************************************************/
3041 /* removable device support */
3044 * Return TRUE if the media is present
3046 int bdrv_is_inserted(BlockDriverState *bs)
3048 BlockDriver *drv = bs->drv;
3052 if (!drv->bdrv_is_inserted)
3054 return drv->bdrv_is_inserted(bs);
3058 * Return whether the media changed since the last call to this
3059 * function, or -ENOTSUP if we don't know. Most drivers don't know.
3061 int bdrv_media_changed(BlockDriverState *bs)
3063 BlockDriver *drv = bs->drv;
3065 if (drv && drv->bdrv_media_changed) {
3066 return drv->bdrv_media_changed(bs);
3072 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3074 void bdrv_eject(BlockDriverState *bs, int eject_flag)
3076 BlockDriver *drv = bs->drv;
3078 if (drv && drv->bdrv_eject) {
3079 drv->bdrv_eject(bs, eject_flag);
3084 * Lock or unlock the media (if it is locked, the user won't be able
3085 * to eject it manually).
3087 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
3089 BlockDriver *drv = bs->drv;
3091 trace_bdrv_lock_medium(bs, locked);
3093 if (drv && drv->bdrv_lock_medium) {
3094 drv->bdrv_lock_medium(bs, locked);
3098 /* needed for generic scsi interface */
3100 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
3102 BlockDriver *drv = bs->drv;
3104 if (drv && drv->bdrv_ioctl)
3105 return drv->bdrv_ioctl(bs, req, buf);
3109 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
3110 unsigned long int req, void *buf,
3111 BlockDriverCompletionFunc *cb, void *opaque)
3113 BlockDriver *drv = bs->drv;
3115 if (drv && drv->bdrv_aio_ioctl)
3116 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
3120 void bdrv_set_buffer_alignment(BlockDriverState *bs, int align)
3122 bs->buffer_alignment = align;
3125 void *qemu_blockalign(BlockDriverState *bs, size_t size)
3127 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
3130 void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
3132 int64_t bitmap_size;
3134 bs->dirty_count = 0;
3136 if (!bs->dirty_bitmap) {
3137 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
3138 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
3139 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
3141 bs->dirty_bitmap = g_malloc0(bitmap_size);
3144 if (bs->dirty_bitmap) {
3145 g_free(bs->dirty_bitmap);
3146 bs->dirty_bitmap = NULL;
3151 int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
3153 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
3155 if (bs->dirty_bitmap &&
3156 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
3157 return !!(bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
3158 (1UL << (chunk % (sizeof(unsigned long) * 8))));
3164 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3167 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
3170 int64_t bdrv_get_dirty_count(BlockDriverState *bs)
3172 return bs->dirty_count;
3175 void bdrv_set_in_use(BlockDriverState *bs, int in_use)
3177 assert(bs->in_use != in_use);
3178 bs->in_use = in_use;
3181 int bdrv_in_use(BlockDriverState *bs)
3187 bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
3188 enum BlockAcctType type)
3190 assert(type < BDRV_MAX_IOTYPE);
3192 cookie->bytes = bytes;
3193 cookie->start_time_ns = get_clock();
3194 cookie->type = type;
3198 bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
3200 assert(cookie->type < BDRV_MAX_IOTYPE);
3202 bs->nr_bytes[cookie->type] += cookie->bytes;
3203 bs->nr_ops[cookie->type]++;
3204 bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
3207 int bdrv_img_create(const char *filename, const char *fmt,
3208 const char *base_filename, const char *base_fmt,
3209 char *options, uint64_t img_size, int flags)
3211 QEMUOptionParameter *param = NULL, *create_options = NULL;
3212 QEMUOptionParameter *backing_fmt, *backing_file, *size;
3213 BlockDriverState *bs = NULL;
3214 BlockDriver *drv, *proto_drv;
3215 BlockDriver *backing_drv = NULL;
3218 /* Find driver and parse its options */
3219 drv = bdrv_find_format(fmt);
3221 error_report("Unknown file format '%s'", fmt);
3226 proto_drv = bdrv_find_protocol(filename);
3228 error_report("Unknown protocol '%s'", filename);
3233 create_options = append_option_parameters(create_options,
3234 drv->create_options);
3235 create_options = append_option_parameters(create_options,
3236 proto_drv->create_options);
3238 /* Create parameter list with default values */
3239 param = parse_option_parameters("", create_options, param);
3241 set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
3243 /* Parse -o options */
3245 param = parse_option_parameters(options, create_options, param);
3246 if (param == NULL) {
3247 error_report("Invalid options for file format '%s'.", fmt);
3253 if (base_filename) {
3254 if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
3256 error_report("Backing file not supported for file format '%s'",
3264 if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
3265 error_report("Backing file format not supported for file "
3266 "format '%s'", fmt);
3272 backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
3273 if (backing_file && backing_file->value.s) {
3274 if (!strcmp(filename, backing_file->value.s)) {
3275 error_report("Error: Trying to create an image with the "
3276 "same filename as the backing file");
3282 backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
3283 if (backing_fmt && backing_fmt->value.s) {
3284 backing_drv = bdrv_find_format(backing_fmt->value.s);
3286 error_report("Unknown backing file format '%s'",
3287 backing_fmt->value.s);
3293 // The size for the image must always be specified, with one exception:
3294 // If we are using a backing file, we can obtain the size from there
3295 size = get_option_parameter(param, BLOCK_OPT_SIZE);
3296 if (size && size->value.n == -1) {
3297 if (backing_file && backing_file->value.s) {
3303 ret = bdrv_open(bs, backing_file->value.s, flags, backing_drv);
3305 error_report("Could not open '%s'", backing_file->value.s);
3308 bdrv_get_geometry(bs, &size);
3311 snprintf(buf, sizeof(buf), "%" PRId64, size);
3312 set_option_parameter(param, BLOCK_OPT_SIZE, buf);
3314 error_report("Image creation needs a size parameter");
3320 printf("Formatting '%s', fmt=%s ", filename, fmt);
3321 print_option_parameters(param);
3324 ret = bdrv_create(drv, filename, param);
3327 if (ret == -ENOTSUP) {
3328 error_report("Formatting or formatting option not supported for "
3329 "file format '%s'", fmt);
3330 } else if (ret == -EFBIG) {
3331 error_report("The image size is too large for file format '%s'",
3334 error_report("%s: error while creating %s: %s", filename, fmt,
3340 free_option_parameters(create_options);
3341 free_option_parameters(param);