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"
27 #include "block_int.h"
29 #include "qemu-objects.h"
32 #include <sys/types.h>
34 #include <sys/ioctl.h>
35 #include <sys/queue.h>
45 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
46 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
47 BlockDriverCompletionFunc *cb, void *opaque);
48 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
49 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
50 BlockDriverCompletionFunc *cb, void *opaque);
51 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
52 BlockDriverCompletionFunc *cb, void *opaque);
53 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
54 BlockDriverCompletionFunc *cb, void *opaque);
55 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
56 uint8_t *buf, int nb_sectors);
57 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
58 const uint8_t *buf, int nb_sectors);
60 static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
61 QTAILQ_HEAD_INITIALIZER(bdrv_states);
63 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
64 QLIST_HEAD_INITIALIZER(bdrv_drivers);
66 /* If non-zero, use only whitelisted block drivers */
67 static int use_bdrv_whitelist;
69 int path_is_absolute(const char *path)
73 /* specific case for names like: "\\.\d:" */
74 if (*path == '/' || *path == '\\')
77 p = strchr(path, ':');
83 return (*p == '/' || *p == '\\');
89 /* if filename is absolute, just copy it to dest. Otherwise, build a
90 path to it by considering it is relative to base_path. URL are
92 void path_combine(char *dest, int dest_size,
93 const char *base_path,
101 if (path_is_absolute(filename)) {
102 pstrcpy(dest, dest_size, filename);
104 p = strchr(base_path, ':');
109 p1 = strrchr(base_path, '/');
113 p2 = strrchr(base_path, '\\');
125 if (len > dest_size - 1)
127 memcpy(dest, base_path, len);
129 pstrcat(dest, dest_size, filename);
133 void bdrv_register(BlockDriver *bdrv)
135 if (!bdrv->bdrv_aio_readv) {
136 /* add AIO emulation layer */
137 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
138 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
139 } else if (!bdrv->bdrv_read) {
140 /* add synchronous IO emulation layer */
141 bdrv->bdrv_read = bdrv_read_em;
142 bdrv->bdrv_write = bdrv_write_em;
145 if (!bdrv->bdrv_aio_flush)
146 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
148 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
151 /* create a new block device (by default it is empty) */
152 BlockDriverState *bdrv_new(const char *device_name)
154 BlockDriverState *bs;
156 bs = qemu_mallocz(sizeof(BlockDriverState));
157 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
158 if (device_name[0] != '\0') {
159 QTAILQ_INSERT_TAIL(&bdrv_states, bs, list);
164 BlockDriver *bdrv_find_format(const char *format_name)
167 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
168 if (!strcmp(drv1->format_name, format_name)) {
175 static int bdrv_is_whitelisted(BlockDriver *drv)
177 static const char *whitelist[] = {
178 CONFIG_BDRV_WHITELIST
183 return 1; /* no whitelist, anything goes */
185 for (p = whitelist; *p; p++) {
186 if (!strcmp(drv->format_name, *p)) {
193 BlockDriver *bdrv_find_whitelisted_format(const char *format_name)
195 BlockDriver *drv = bdrv_find_format(format_name);
196 return drv && bdrv_is_whitelisted(drv) ? drv : NULL;
199 int bdrv_create(BlockDriver *drv, const char* filename,
200 QEMUOptionParameter *options)
202 if (!drv->bdrv_create)
205 return drv->bdrv_create(filename, options);
208 int bdrv_create_file(const char* filename, QEMUOptionParameter *options)
212 drv = bdrv_find_protocol(filename);
214 drv = bdrv_find_format("file");
217 return bdrv_create(drv, filename, options);
221 void get_tmp_filename(char *filename, int size)
223 char temp_dir[MAX_PATH];
225 GetTempPath(MAX_PATH, temp_dir);
226 GetTempFileName(temp_dir, "qem", 0, filename);
229 void get_tmp_filename(char *filename, int size)
233 /* XXX: race condition possible */
234 tmpdir = getenv("TMPDIR");
237 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
238 fd = mkstemp(filename);
244 static int is_windows_drive_prefix(const char *filename)
246 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
247 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
251 int is_windows_drive(const char *filename)
253 if (is_windows_drive_prefix(filename) &&
256 if (strstart(filename, "\\\\.\\", NULL) ||
257 strstart(filename, "//./", NULL))
264 * Detect host devices. By convention, /dev/cdrom[N] is always
265 * recognized as a host CDROM.
267 static BlockDriver *find_hdev_driver(const char *filename)
269 int score_max = 0, score;
270 BlockDriver *drv = NULL, *d;
272 QLIST_FOREACH(d, &bdrv_drivers, list) {
273 if (d->bdrv_probe_device) {
274 score = d->bdrv_probe_device(filename);
275 if (score > score_max) {
285 BlockDriver *bdrv_find_protocol(const char *filename)
293 /* TODO Drivers without bdrv_file_open must be specified explicitly */
296 is_drive = is_windows_drive(filename) ||
297 is_windows_drive_prefix(filename);
301 p = strchr(filename, ':');
302 if (!p || is_drive) {
303 drv1 = find_hdev_driver(filename);
305 drv1 = bdrv_find_format("file");
310 if (len > sizeof(protocol) - 1)
311 len = sizeof(protocol) - 1;
312 memcpy(protocol, filename, len);
313 protocol[len] = '\0';
314 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
315 if (drv1->protocol_name &&
316 !strcmp(drv1->protocol_name, protocol)) {
323 static BlockDriver *find_image_format(const char *filename)
325 int ret, score, score_max;
326 BlockDriver *drv1, *drv;
328 BlockDriverState *bs;
330 ret = bdrv_file_open(&bs, filename, 0);
334 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
335 if (bs->sg || !bdrv_is_inserted(bs)) {
337 return bdrv_find_format("raw");
340 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
348 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
349 if (drv1->bdrv_probe) {
350 score = drv1->bdrv_probe(buf, ret, filename);
351 if (score > score_max) {
361 * Set the current 'total_sectors' value
363 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
365 BlockDriver *drv = bs->drv;
367 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
371 /* query actual device if possible, otherwise just trust the hint */
372 if (drv->bdrv_getlength) {
373 int64_t length = drv->bdrv_getlength(bs);
377 hint = length >> BDRV_SECTOR_BITS;
380 bs->total_sectors = hint;
385 * Common part for opening disk images and files
387 static int bdrv_open_common(BlockDriverState *bs, const char *filename,
388 int flags, BlockDriver *drv)
395 bs->total_sectors = 0;
396 bs->is_temporary = 0;
399 bs->open_flags = flags;
400 /* buffer_alignment defaulted to 512, drivers can change this value */
401 bs->buffer_alignment = 512;
403 pstrcpy(bs->filename, sizeof(bs->filename), filename);
405 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv)) {
410 bs->opaque = qemu_mallocz(drv->instance_size);
413 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
414 * write cache to the guest. We do need the fdatasync to flush
415 * out transactions for block allocations, and we maybe have a
416 * volatile write cache in our backing device to deal with.
418 if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))
419 bs->enable_write_cache = 1;
422 * Clear flags that are internal to the block layer before opening the
425 open_flags = flags & ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
428 * Snapshots should be writeable.
430 if (bs->is_temporary) {
431 open_flags |= BDRV_O_RDWR;
434 /* Open the image, either directly or using a protocol */
435 if (drv->bdrv_file_open) {
436 ret = drv->bdrv_file_open(bs, filename, open_flags);
438 ret = bdrv_file_open(&bs->file, filename, open_flags);
440 ret = drv->bdrv_open(bs, open_flags);
448 bs->keep_read_only = bs->read_only = !(open_flags & BDRV_O_RDWR);
450 ret = refresh_total_sectors(bs, bs->total_sectors);
456 if (bs->is_temporary) {
464 bdrv_delete(bs->file);
467 qemu_free(bs->opaque);
474 * Opens a file using a protocol (file, host_device, nbd, ...)
476 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
478 BlockDriverState *bs;
482 drv = bdrv_find_protocol(filename);
488 ret = bdrv_open_common(bs, filename, flags, drv);
499 * Opens a disk image (raw, qcow2, vmdk, ...)
501 int bdrv_open(BlockDriverState *bs, const char *filename, int flags,
506 if (flags & BDRV_O_SNAPSHOT) {
507 BlockDriverState *bs1;
510 BlockDriver *bdrv_qcow2;
511 QEMUOptionParameter *options;
512 char tmp_filename[PATH_MAX];
513 char backing_filename[PATH_MAX];
515 /* if snapshot, we create a temporary backing file and open it
516 instead of opening 'filename' directly */
518 /* if there is a backing file, use it */
520 ret = bdrv_open(bs1, filename, 0, drv);
525 total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;
527 if (bs1->drv && bs1->drv->protocol_name)
532 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
534 /* Real path is meaningless for protocols */
536 snprintf(backing_filename, sizeof(backing_filename),
538 else if (!realpath(filename, backing_filename))
541 bdrv_qcow2 = bdrv_find_format("qcow2");
542 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
544 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);
545 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
547 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
551 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
552 free_option_parameters(options);
557 filename = tmp_filename;
559 bs->is_temporary = 1;
562 /* Find the right image format driver */
564 drv = find_image_format(filename);
569 goto unlink_and_fail;
573 ret = bdrv_open_common(bs, filename, flags, drv);
575 goto unlink_and_fail;
578 /* If there is a backing file, use it */
579 if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {
580 char backing_filename[PATH_MAX];
582 BlockDriver *back_drv = NULL;
584 bs->backing_hd = bdrv_new("");
585 path_combine(backing_filename, sizeof(backing_filename),
586 filename, bs->backing_file);
587 if (bs->backing_format[0] != '\0')
588 back_drv = bdrv_find_format(bs->backing_format);
590 /* backing files always opened read-only */
592 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
594 ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);
599 if (bs->is_temporary) {
600 bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);
602 /* base image inherits from "parent" */
603 bs->backing_hd->keep_read_only = bs->keep_read_only;
607 if (!bdrv_key_required(bs)) {
608 /* call the change callback */
609 bs->media_changed = 1;
611 bs->change_cb(bs->change_opaque);
617 if (bs->is_temporary) {
623 void bdrv_close(BlockDriverState *bs)
626 if (bs->backing_hd) {
627 bdrv_delete(bs->backing_hd);
628 bs->backing_hd = NULL;
630 bs->drv->bdrv_close(bs);
631 qemu_free(bs->opaque);
633 if (bs->is_temporary) {
634 unlink(bs->filename);
640 if (bs->file != NULL) {
641 bdrv_close(bs->file);
644 /* call the change callback */
645 bs->media_changed = 1;
647 bs->change_cb(bs->change_opaque);
651 void bdrv_close_all(void)
653 BlockDriverState *bs;
655 QTAILQ_FOREACH(bs, &bdrv_states, list) {
660 void bdrv_delete(BlockDriverState *bs)
662 /* remove from list, if necessary */
663 if (bs->device_name[0] != '\0') {
664 QTAILQ_REMOVE(&bdrv_states, bs, list);
668 if (bs->file != NULL) {
669 bdrv_delete(bs->file);
676 * Run consistency checks on an image
678 * Returns the number of errors or -errno when an internal error occurs
680 int bdrv_check(BlockDriverState *bs)
682 if (bs->drv->bdrv_check == NULL) {
686 return bs->drv->bdrv_check(bs);
689 /* commit COW file into the raw image */
690 int bdrv_commit(BlockDriverState *bs)
692 BlockDriver *drv = bs->drv;
693 int64_t i, total_sectors;
694 int n, j, ro, open_flags;
695 int ret = 0, rw_ret = 0;
696 unsigned char sector[BDRV_SECTOR_SIZE];
698 BlockDriverState *bs_rw, *bs_ro;
703 if (!bs->backing_hd) {
707 if (bs->backing_hd->keep_read_only) {
711 ro = bs->backing_hd->read_only;
712 strncpy(filename, bs->backing_hd->filename, sizeof(filename));
713 open_flags = bs->backing_hd->open_flags;
717 bdrv_delete(bs->backing_hd);
718 bs->backing_hd = NULL;
719 bs_rw = bdrv_new("");
720 rw_ret = bdrv_open(bs_rw, filename, open_flags | BDRV_O_RDWR, drv);
723 /* try to re-open read-only */
724 bs_ro = bdrv_new("");
725 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR, drv);
728 /* drive not functional anymore */
732 bs->backing_hd = bs_ro;
735 bs->backing_hd = bs_rw;
738 total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
739 for (i = 0; i < total_sectors;) {
740 if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
741 for(j = 0; j < n; j++) {
742 if (bdrv_read(bs, i, sector, 1) != 0) {
747 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
758 if (drv->bdrv_make_empty) {
759 ret = drv->bdrv_make_empty(bs);
764 * Make sure all data we wrote to the backing device is actually
768 bdrv_flush(bs->backing_hd);
774 bdrv_delete(bs->backing_hd);
775 bs->backing_hd = NULL;
776 bs_ro = bdrv_new("");
777 ret = bdrv_open(bs_ro, filename, open_flags & ~BDRV_O_RDWR, drv);
780 /* drive not functional anymore */
784 bs->backing_hd = bs_ro;
785 bs->backing_hd->keep_read_only = 0;
791 void bdrv_commit_all(void)
793 BlockDriverState *bs;
795 QTAILQ_FOREACH(bs, &bdrv_states, list) {
803 * -EINVAL - backing format specified, but no file
804 * -ENOSPC - can't update the backing file because no space is left in the
806 * -ENOTSUP - format driver doesn't support changing the backing file
808 int bdrv_change_backing_file(BlockDriverState *bs,
809 const char *backing_file, const char *backing_fmt)
811 BlockDriver *drv = bs->drv;
813 if (drv->bdrv_change_backing_file != NULL) {
814 return drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
820 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
825 if (!bdrv_is_inserted(bs))
831 len = bdrv_getlength(bs);
836 if ((offset > len) || (len - offset < size))
842 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
845 return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
846 nb_sectors * BDRV_SECTOR_SIZE);
849 /* return < 0 if error. See bdrv_write() for the return codes */
850 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
851 uint8_t *buf, int nb_sectors)
853 BlockDriver *drv = bs->drv;
857 if (bdrv_check_request(bs, sector_num, nb_sectors))
860 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
863 static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,
864 int nb_sectors, int dirty)
867 unsigned long val, idx, bit;
869 start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;
870 end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;
872 for (; start <= end; start++) {
873 idx = start / (sizeof(unsigned long) * 8);
874 bit = start % (sizeof(unsigned long) * 8);
875 val = bs->dirty_bitmap[idx];
877 if (!(val & (1 << bit))) {
882 if (val & (1 << bit)) {
887 bs->dirty_bitmap[idx] = val;
891 /* Return < 0 if error. Important errors are:
892 -EIO generic I/O error (may happen for all errors)
893 -ENOMEDIUM No media inserted.
894 -EINVAL Invalid sector number or nb_sectors
895 -EACCES Trying to write a read-only device
897 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
898 const uint8_t *buf, int nb_sectors)
900 BlockDriver *drv = bs->drv;
905 if (bdrv_check_request(bs, sector_num, nb_sectors))
908 if (bs->dirty_bitmap) {
909 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
912 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
913 bs->wr_highest_sector = sector_num + nb_sectors - 1;
916 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
919 int bdrv_pread(BlockDriverState *bs, int64_t offset,
920 void *buf, int count1)
922 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
923 int len, nb_sectors, count;
928 /* first read to align to sector start */
929 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
932 sector_num = offset >> BDRV_SECTOR_BITS;
934 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
936 memcpy(buf, tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), len);
944 /* read the sectors "in place" */
945 nb_sectors = count >> BDRV_SECTOR_BITS;
946 if (nb_sectors > 0) {
947 if ((ret = bdrv_read(bs, sector_num, buf, nb_sectors)) < 0)
949 sector_num += nb_sectors;
950 len = nb_sectors << BDRV_SECTOR_BITS;
955 /* add data from the last sector */
957 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
959 memcpy(buf, tmp_buf, count);
964 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
965 const void *buf, int count1)
967 uint8_t tmp_buf[BDRV_SECTOR_SIZE];
968 int len, nb_sectors, count;
973 /* first write to align to sector start */
974 len = (BDRV_SECTOR_SIZE - offset) & (BDRV_SECTOR_SIZE - 1);
977 sector_num = offset >> BDRV_SECTOR_BITS;
979 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
981 memcpy(tmp_buf + (offset & (BDRV_SECTOR_SIZE - 1)), buf, len);
982 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
991 /* write the sectors "in place" */
992 nb_sectors = count >> BDRV_SECTOR_BITS;
993 if (nb_sectors > 0) {
994 if ((ret = bdrv_write(bs, sector_num, buf, nb_sectors)) < 0)
996 sector_num += nb_sectors;
997 len = nb_sectors << BDRV_SECTOR_BITS;
1002 /* add data from the last sector */
1004 if ((ret = bdrv_read(bs, sector_num, tmp_buf, 1)) < 0)
1006 memcpy(tmp_buf, buf, count);
1007 if ((ret = bdrv_write(bs, sector_num, tmp_buf, 1)) < 0)
1014 * Writes to the file and ensures that no writes are reordered across this
1015 * request (acts as a barrier)
1017 * Returns 0 on success, -errno in error cases.
1019 int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
1020 const void *buf, int count)
1024 ret = bdrv_pwrite(bs, offset, buf, count);
1029 /* No flush needed for cache=writethrough, it uses O_DSYNC */
1030 if ((bs->open_flags & BDRV_O_CACHE_MASK) != 0) {
1038 * Writes to the file and ensures that no writes are reordered across this
1039 * request (acts as a barrier)
1041 * Returns 0 on success, -errno in error cases.
1043 int bdrv_write_sync(BlockDriverState *bs, int64_t sector_num,
1044 const uint8_t *buf, int nb_sectors)
1046 return bdrv_pwrite_sync(bs, BDRV_SECTOR_SIZE * sector_num,
1047 buf, BDRV_SECTOR_SIZE * nb_sectors);
1051 * Truncate file to 'offset' bytes (needed only for file protocols)
1053 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
1055 BlockDriver *drv = bs->drv;
1059 if (!drv->bdrv_truncate)
1063 ret = drv->bdrv_truncate(bs, offset);
1065 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
1071 * Length of a file in bytes. Return < 0 if error or unknown.
1073 int64_t bdrv_getlength(BlockDriverState *bs)
1075 BlockDriver *drv = bs->drv;
1079 /* Fixed size devices use the total_sectors value for speed instead of
1080 issuing a length query (like lseek) on each call. Also, legacy block
1081 drivers don't provide a bdrv_getlength function and must use
1083 if (!bs->growable || !drv->bdrv_getlength) {
1084 return bs->total_sectors * BDRV_SECTOR_SIZE;
1086 return drv->bdrv_getlength(bs);
1089 /* return 0 as number of sectors if no device present or error */
1090 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
1093 length = bdrv_getlength(bs);
1097 length = length >> BDRV_SECTOR_BITS;
1098 *nb_sectors_ptr = length;
1102 uint8_t boot_ind; /* 0x80 - active */
1103 uint8_t head; /* starting head */
1104 uint8_t sector; /* starting sector */
1105 uint8_t cyl; /* starting cylinder */
1106 uint8_t sys_ind; /* What partition type */
1107 uint8_t end_head; /* end head */
1108 uint8_t end_sector; /* end sector */
1109 uint8_t end_cyl; /* end cylinder */
1110 uint32_t start_sect; /* starting sector counting from 0 */
1111 uint32_t nr_sects; /* nr of sectors in partition */
1112 } __attribute__((packed));
1114 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1115 static int guess_disk_lchs(BlockDriverState *bs,
1116 int *pcylinders, int *pheads, int *psectors)
1118 uint8_t buf[BDRV_SECTOR_SIZE];
1119 int ret, i, heads, sectors, cylinders;
1120 struct partition *p;
1122 uint64_t nb_sectors;
1124 bdrv_get_geometry(bs, &nb_sectors);
1126 ret = bdrv_read(bs, 0, buf, 1);
1129 /* test msdos magic */
1130 if (buf[510] != 0x55 || buf[511] != 0xaa)
1132 for(i = 0; i < 4; i++) {
1133 p = ((struct partition *)(buf + 0x1be)) + i;
1134 nr_sects = le32_to_cpu(p->nr_sects);
1135 if (nr_sects && p->end_head) {
1136 /* We make the assumption that the partition terminates on
1137 a cylinder boundary */
1138 heads = p->end_head + 1;
1139 sectors = p->end_sector & 63;
1142 cylinders = nb_sectors / (heads * sectors);
1143 if (cylinders < 1 || cylinders > 16383)
1146 *psectors = sectors;
1147 *pcylinders = cylinders;
1149 printf("guessed geometry: LCHS=%d %d %d\n",
1150 cylinders, heads, sectors);
1158 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
1160 int translation, lba_detected = 0;
1161 int cylinders, heads, secs;
1162 uint64_t nb_sectors;
1164 /* if a geometry hint is available, use it */
1165 bdrv_get_geometry(bs, &nb_sectors);
1166 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
1167 translation = bdrv_get_translation_hint(bs);
1168 if (cylinders != 0) {
1173 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
1175 /* if heads > 16, it means that a BIOS LBA
1176 translation was active, so the default
1177 hardware geometry is OK */
1179 goto default_geometry;
1184 /* disable any translation to be in sync with
1185 the logical geometry */
1186 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
1187 bdrv_set_translation_hint(bs,
1188 BIOS_ATA_TRANSLATION_NONE);
1193 /* if no geometry, use a standard physical disk geometry */
1194 cylinders = nb_sectors / (16 * 63);
1196 if (cylinders > 16383)
1198 else if (cylinders < 2)
1203 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
1204 if ((*pcyls * *pheads) <= 131072) {
1205 bdrv_set_translation_hint(bs,
1206 BIOS_ATA_TRANSLATION_LARGE);
1208 bdrv_set_translation_hint(bs,
1209 BIOS_ATA_TRANSLATION_LBA);
1213 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
1217 void bdrv_set_geometry_hint(BlockDriverState *bs,
1218 int cyls, int heads, int secs)
1225 void bdrv_set_type_hint(BlockDriverState *bs, int type)
1228 bs->removable = ((type == BDRV_TYPE_CDROM ||
1229 type == BDRV_TYPE_FLOPPY));
1232 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
1234 bs->translation = translation;
1237 void bdrv_get_geometry_hint(BlockDriverState *bs,
1238 int *pcyls, int *pheads, int *psecs)
1241 *pheads = bs->heads;
1245 int bdrv_get_type_hint(BlockDriverState *bs)
1250 int bdrv_get_translation_hint(BlockDriverState *bs)
1252 return bs->translation;
1255 void bdrv_set_on_error(BlockDriverState *bs, BlockErrorAction on_read_error,
1256 BlockErrorAction on_write_error)
1258 bs->on_read_error = on_read_error;
1259 bs->on_write_error = on_write_error;
1262 BlockErrorAction bdrv_get_on_error(BlockDriverState *bs, int is_read)
1264 return is_read ? bs->on_read_error : bs->on_write_error;
1267 int bdrv_is_removable(BlockDriverState *bs)
1269 return bs->removable;
1272 int bdrv_is_read_only(BlockDriverState *bs)
1274 return bs->read_only;
1277 int bdrv_is_sg(BlockDriverState *bs)
1282 int bdrv_enable_write_cache(BlockDriverState *bs)
1284 return bs->enable_write_cache;
1287 /* XXX: no longer used */
1288 void bdrv_set_change_cb(BlockDriverState *bs,
1289 void (*change_cb)(void *opaque), void *opaque)
1291 bs->change_cb = change_cb;
1292 bs->change_opaque = opaque;
1295 int bdrv_is_encrypted(BlockDriverState *bs)
1297 if (bs->backing_hd && bs->backing_hd->encrypted)
1299 return bs->encrypted;
1302 int bdrv_key_required(BlockDriverState *bs)
1304 BlockDriverState *backing_hd = bs->backing_hd;
1306 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
1308 return (bs->encrypted && !bs->valid_key);
1311 int bdrv_set_key(BlockDriverState *bs, const char *key)
1314 if (bs->backing_hd && bs->backing_hd->encrypted) {
1315 ret = bdrv_set_key(bs->backing_hd, key);
1321 if (!bs->encrypted) {
1323 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
1326 ret = bs->drv->bdrv_set_key(bs, key);
1329 } else if (!bs->valid_key) {
1331 /* call the change callback now, we skipped it on open */
1332 bs->media_changed = 1;
1334 bs->change_cb(bs->change_opaque);
1339 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
1344 pstrcpy(buf, buf_size, bs->drv->format_name);
1348 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1353 QLIST_FOREACH(drv, &bdrv_drivers, list) {
1354 it(opaque, drv->format_name);
1358 BlockDriverState *bdrv_find(const char *name)
1360 BlockDriverState *bs;
1362 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1363 if (!strcmp(name, bs->device_name)) {
1370 BlockDriverState *bdrv_next(BlockDriverState *bs)
1373 return QTAILQ_FIRST(&bdrv_states);
1375 return QTAILQ_NEXT(bs, list);
1378 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1380 BlockDriverState *bs;
1382 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1387 const char *bdrv_get_device_name(BlockDriverState *bs)
1389 return bs->device_name;
1392 void bdrv_flush(BlockDriverState *bs)
1394 if (bs->open_flags & BDRV_O_NO_FLUSH) {
1398 if (bs->drv && bs->drv->bdrv_flush)
1399 bs->drv->bdrv_flush(bs);
1402 void bdrv_flush_all(void)
1404 BlockDriverState *bs;
1406 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1407 if (bs->drv && !bdrv_is_read_only(bs) &&
1408 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs))) {
1414 int bdrv_has_zero_init(BlockDriverState *bs)
1418 if (bs->drv->no_zero_init) {
1420 } else if (bs->file) {
1421 return bdrv_has_zero_init(bs->file);
1428 * Returns true iff the specified sector is present in the disk image. Drivers
1429 * not implementing the functionality are assumed to not support backing files,
1430 * hence all their sectors are reported as allocated.
1432 * 'pnum' is set to the number of sectors (including and immediately following
1433 * the specified sector) that are known to be in the same
1434 * allocated/unallocated state.
1436 * 'nb_sectors' is the max value 'pnum' should be set to.
1438 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1442 if (!bs->drv->bdrv_is_allocated) {
1443 if (sector_num >= bs->total_sectors) {
1447 n = bs->total_sectors - sector_num;
1448 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1451 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1454 void bdrv_mon_event(const BlockDriverState *bdrv,
1455 BlockMonEventAction action, int is_read)
1458 const char *action_str;
1461 case BDRV_ACTION_REPORT:
1462 action_str = "report";
1464 case BDRV_ACTION_IGNORE:
1465 action_str = "ignore";
1467 case BDRV_ACTION_STOP:
1468 action_str = "stop";
1474 data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1477 is_read ? "read" : "write");
1478 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR, data);
1480 qobject_decref(data);
1483 static void bdrv_print_dict(QObject *obj, void *opaque)
1486 Monitor *mon = opaque;
1488 bs_dict = qobject_to_qdict(obj);
1490 monitor_printf(mon, "%s: type=%s removable=%d",
1491 qdict_get_str(bs_dict, "device"),
1492 qdict_get_str(bs_dict, "type"),
1493 qdict_get_bool(bs_dict, "removable"));
1495 if (qdict_get_bool(bs_dict, "removable")) {
1496 monitor_printf(mon, " locked=%d", qdict_get_bool(bs_dict, "locked"));
1499 if (qdict_haskey(bs_dict, "inserted")) {
1500 QDict *qdict = qobject_to_qdict(qdict_get(bs_dict, "inserted"));
1502 monitor_printf(mon, " file=");
1503 monitor_print_filename(mon, qdict_get_str(qdict, "file"));
1504 if (qdict_haskey(qdict, "backing_file")) {
1505 monitor_printf(mon, " backing_file=");
1506 monitor_print_filename(mon, qdict_get_str(qdict, "backing_file"));
1508 monitor_printf(mon, " ro=%d drv=%s encrypted=%d",
1509 qdict_get_bool(qdict, "ro"),
1510 qdict_get_str(qdict, "drv"),
1511 qdict_get_bool(qdict, "encrypted"));
1513 monitor_printf(mon, " [not inserted]");
1516 monitor_printf(mon, "\n");
1519 void bdrv_info_print(Monitor *mon, const QObject *data)
1521 qlist_iter(qobject_to_qlist(data), bdrv_print_dict, mon);
1524 void bdrv_info(Monitor *mon, QObject **ret_data)
1527 BlockDriverState *bs;
1529 bs_list = qlist_new();
1531 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1533 const char *type = "unknown";
1539 case BDRV_TYPE_CDROM:
1542 case BDRV_TYPE_FLOPPY:
1547 bs_obj = qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1548 "'removable': %i, 'locked': %i }",
1549 bs->device_name, type, bs->removable,
1554 QDict *bs_dict = qobject_to_qdict(bs_obj);
1556 obj = qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1557 "'encrypted': %i }",
1558 bs->filename, bs->read_only,
1559 bs->drv->format_name,
1560 bdrv_is_encrypted(bs));
1561 if (bs->backing_file[0] != '\0') {
1562 QDict *qdict = qobject_to_qdict(obj);
1563 qdict_put(qdict, "backing_file",
1564 qstring_from_str(bs->backing_file));
1567 qdict_put_obj(bs_dict, "inserted", obj);
1569 qlist_append_obj(bs_list, bs_obj);
1572 *ret_data = QOBJECT(bs_list);
1575 static void bdrv_stats_iter(QObject *data, void *opaque)
1578 Monitor *mon = opaque;
1580 qdict = qobject_to_qdict(data);
1581 monitor_printf(mon, "%s:", qdict_get_str(qdict, "device"));
1583 qdict = qobject_to_qdict(qdict_get(qdict, "stats"));
1584 monitor_printf(mon, " rd_bytes=%" PRId64
1585 " wr_bytes=%" PRId64
1586 " rd_operations=%" PRId64
1587 " wr_operations=%" PRId64
1589 qdict_get_int(qdict, "rd_bytes"),
1590 qdict_get_int(qdict, "wr_bytes"),
1591 qdict_get_int(qdict, "rd_operations"),
1592 qdict_get_int(qdict, "wr_operations"));
1595 void bdrv_stats_print(Monitor *mon, const QObject *data)
1597 qlist_iter(qobject_to_qlist(data), bdrv_stats_iter, mon);
1600 static QObject* bdrv_info_stats_bs(BlockDriverState *bs)
1605 res = qobject_from_jsonf("{ 'stats': {"
1606 "'rd_bytes': %" PRId64 ","
1607 "'wr_bytes': %" PRId64 ","
1608 "'rd_operations': %" PRId64 ","
1609 "'wr_operations': %" PRId64 ","
1610 "'wr_highest_offset': %" PRId64
1612 bs->rd_bytes, bs->wr_bytes,
1613 bs->rd_ops, bs->wr_ops,
1614 bs->wr_highest_sector *
1615 (uint64_t)BDRV_SECTOR_SIZE);
1616 dict = qobject_to_qdict(res);
1618 if (*bs->device_name) {
1619 qdict_put(dict, "device", qstring_from_str(bs->device_name));
1623 QObject *parent = bdrv_info_stats_bs(bs->file);
1624 qdict_put_obj(dict, "parent", parent);
1630 void bdrv_info_stats(Monitor *mon, QObject **ret_data)
1634 BlockDriverState *bs;
1636 devices = qlist_new();
1638 QTAILQ_FOREACH(bs, &bdrv_states, list) {
1639 obj = bdrv_info_stats_bs(bs);
1640 qlist_append_obj(devices, obj);
1643 *ret_data = QOBJECT(devices);
1646 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1648 if (bs->backing_hd && bs->backing_hd->encrypted)
1649 return bs->backing_file;
1650 else if (bs->encrypted)
1651 return bs->filename;
1656 void bdrv_get_backing_filename(BlockDriverState *bs,
1657 char *filename, int filename_size)
1659 if (!bs->backing_file) {
1660 pstrcpy(filename, filename_size, "");
1662 pstrcpy(filename, filename_size, bs->backing_file);
1666 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1667 const uint8_t *buf, int nb_sectors)
1669 BlockDriver *drv = bs->drv;
1672 if (!drv->bdrv_write_compressed)
1674 if (bdrv_check_request(bs, sector_num, nb_sectors))
1677 if (bs->dirty_bitmap) {
1678 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1681 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1684 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1686 BlockDriver *drv = bs->drv;
1689 if (!drv->bdrv_get_info)
1691 memset(bdi, 0, sizeof(*bdi));
1692 return drv->bdrv_get_info(bs, bdi);
1695 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1696 int64_t pos, int size)
1698 BlockDriver *drv = bs->drv;
1701 if (drv->bdrv_save_vmstate)
1702 return drv->bdrv_save_vmstate(bs, buf, pos, size);
1704 return bdrv_save_vmstate(bs->file, buf, pos, size);
1708 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1709 int64_t pos, int size)
1711 BlockDriver *drv = bs->drv;
1714 if (drv->bdrv_load_vmstate)
1715 return drv->bdrv_load_vmstate(bs, buf, pos, size);
1717 return bdrv_load_vmstate(bs->file, buf, pos, size);
1721 void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
1723 BlockDriver *drv = bs->drv;
1725 if (!drv || !drv->bdrv_debug_event) {
1729 return drv->bdrv_debug_event(bs, event);
1733 /**************************************************************/
1734 /* handling of snapshots */
1736 int bdrv_can_snapshot(BlockDriverState *bs)
1738 BlockDriver *drv = bs->drv;
1739 if (!drv || bdrv_is_removable(bs) || bdrv_is_read_only(bs)) {
1743 if (!drv->bdrv_snapshot_create) {
1744 if (bs->file != NULL) {
1745 return bdrv_can_snapshot(bs->file);
1753 int bdrv_snapshot_create(BlockDriverState *bs,
1754 QEMUSnapshotInfo *sn_info)
1756 BlockDriver *drv = bs->drv;
1759 if (drv->bdrv_snapshot_create)
1760 return drv->bdrv_snapshot_create(bs, sn_info);
1762 return bdrv_snapshot_create(bs->file, sn_info);
1766 int bdrv_snapshot_goto(BlockDriverState *bs,
1767 const char *snapshot_id)
1769 BlockDriver *drv = bs->drv;
1774 if (drv->bdrv_snapshot_goto)
1775 return drv->bdrv_snapshot_goto(bs, snapshot_id);
1778 drv->bdrv_close(bs);
1779 ret = bdrv_snapshot_goto(bs->file, snapshot_id);
1780 open_ret = drv->bdrv_open(bs, bs->open_flags);
1782 bdrv_delete(bs->file);
1792 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1794 BlockDriver *drv = bs->drv;
1797 if (drv->bdrv_snapshot_delete)
1798 return drv->bdrv_snapshot_delete(bs, snapshot_id);
1800 return bdrv_snapshot_delete(bs->file, snapshot_id);
1804 int bdrv_snapshot_list(BlockDriverState *bs,
1805 QEMUSnapshotInfo **psn_info)
1807 BlockDriver *drv = bs->drv;
1810 if (drv->bdrv_snapshot_list)
1811 return drv->bdrv_snapshot_list(bs, psn_info);
1813 return bdrv_snapshot_list(bs->file, psn_info);
1817 #define NB_SUFFIXES 4
1819 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1821 static const char suffixes[NB_SUFFIXES] = "KMGT";
1826 snprintf(buf, buf_size, "%" PRId64, size);
1829 for(i = 0; i < NB_SUFFIXES; i++) {
1830 if (size < (10 * base)) {
1831 snprintf(buf, buf_size, "%0.1f%c",
1832 (double)size / base,
1835 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1836 snprintf(buf, buf_size, "%" PRId64 "%c",
1837 ((size + (base >> 1)) / base),
1847 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1849 char buf1[128], date_buf[128], clock_buf[128];
1859 snprintf(buf, buf_size,
1860 "%-10s%-20s%7s%20s%15s",
1861 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1865 ptm = localtime(&ti);
1866 strftime(date_buf, sizeof(date_buf),
1867 "%Y-%m-%d %H:%M:%S", ptm);
1869 localtime_r(&ti, &tm);
1870 strftime(date_buf, sizeof(date_buf),
1871 "%Y-%m-%d %H:%M:%S", &tm);
1873 secs = sn->vm_clock_nsec / 1000000000;
1874 snprintf(clock_buf, sizeof(clock_buf),
1875 "%02d:%02d:%02d.%03d",
1877 (int)((secs / 60) % 60),
1879 (int)((sn->vm_clock_nsec / 1000000) % 1000));
1880 snprintf(buf, buf_size,
1881 "%-10s%-20s%7s%20s%15s",
1882 sn->id_str, sn->name,
1883 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1891 /**************************************************************/
1894 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1895 QEMUIOVector *qiov, int nb_sectors,
1896 BlockDriverCompletionFunc *cb, void *opaque)
1898 BlockDriver *drv = bs->drv;
1899 BlockDriverAIOCB *ret;
1903 if (bdrv_check_request(bs, sector_num, nb_sectors))
1906 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1910 /* Update stats even though technically transfer has not happened. */
1911 bs->rd_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
1918 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1919 QEMUIOVector *qiov, int nb_sectors,
1920 BlockDriverCompletionFunc *cb, void *opaque)
1922 BlockDriver *drv = bs->drv;
1923 BlockDriverAIOCB *ret;
1929 if (bdrv_check_request(bs, sector_num, nb_sectors))
1932 if (bs->dirty_bitmap) {
1933 set_dirty_bitmap(bs, sector_num, nb_sectors, 1);
1936 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
1940 /* Update stats even though technically transfer has not happened. */
1941 bs->wr_bytes += (unsigned) nb_sectors * BDRV_SECTOR_SIZE;
1943 if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
1944 bs->wr_highest_sector = sector_num + nb_sectors - 1;
1952 typedef struct MultiwriteCB {
1957 BlockDriverCompletionFunc *cb;
1959 QEMUIOVector *free_qiov;
1964 static void multiwrite_user_cb(MultiwriteCB *mcb)
1968 for (i = 0; i < mcb->num_callbacks; i++) {
1969 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1970 if (mcb->callbacks[i].free_qiov) {
1971 qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
1973 qemu_free(mcb->callbacks[i].free_qiov);
1974 qemu_vfree(mcb->callbacks[i].free_buf);
1978 static void multiwrite_cb(void *opaque, int ret)
1980 MultiwriteCB *mcb = opaque;
1982 if (ret < 0 && !mcb->error) {
1984 multiwrite_user_cb(mcb);
1987 mcb->num_requests--;
1988 if (mcb->num_requests == 0) {
1989 if (mcb->error == 0) {
1990 multiwrite_user_cb(mcb);
1996 static int multiwrite_req_compare(const void *a, const void *b)
1998 const BlockRequest *req1 = a, *req2 = b;
2001 * Note that we can't simply subtract req2->sector from req1->sector
2002 * here as that could overflow the return value.
2004 if (req1->sector > req2->sector) {
2006 } else if (req1->sector < req2->sector) {
2014 * Takes a bunch of requests and tries to merge them. Returns the number of
2015 * requests that remain after merging.
2017 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
2018 int num_reqs, MultiwriteCB *mcb)
2022 // Sort requests by start sector
2023 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
2025 // Check if adjacent requests touch the same clusters. If so, combine them,
2026 // filling up gaps with zero sectors.
2028 for (i = 1; i < num_reqs; i++) {
2030 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
2032 // This handles the cases that are valid for all block drivers, namely
2033 // exactly sequential writes and overlapping writes.
2034 if (reqs[i].sector <= oldreq_last) {
2038 // The block driver may decide that it makes sense to combine requests
2039 // even if there is a gap of some sectors between them. In this case,
2040 // the gap is filled with zeros (therefore only applicable for yet
2041 // unused space in format like qcow2).
2042 if (!merge && bs->drv->bdrv_merge_requests) {
2043 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
2046 if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
2052 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
2053 qemu_iovec_init(qiov,
2054 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
2056 // Add the first request to the merged one. If the requests are
2057 // overlapping, drop the last sectors of the first request.
2058 size = (reqs[i].sector - reqs[outidx].sector) << 9;
2059 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
2061 // We might need to add some zeros between the two requests
2062 if (reqs[i].sector > oldreq_last) {
2063 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
2064 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
2065 memset(buf, 0, zero_bytes);
2066 qemu_iovec_add(qiov, buf, zero_bytes);
2067 mcb->callbacks[i].free_buf = buf;
2070 // Add the second request
2071 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
2073 reqs[outidx].nb_sectors = qiov->size >> 9;
2074 reqs[outidx].qiov = qiov;
2076 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
2079 reqs[outidx].sector = reqs[i].sector;
2080 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
2081 reqs[outidx].qiov = reqs[i].qiov;
2089 * Submit multiple AIO write requests at once.
2091 * On success, the function returns 0 and all requests in the reqs array have
2092 * been submitted. In error case this function returns -1, and any of the
2093 * requests may or may not be submitted yet. In particular, this means that the
2094 * callback will be called for some of the requests, for others it won't. The
2095 * caller must check the error field of the BlockRequest to wait for the right
2096 * callbacks (if error != 0, no callback will be called).
2098 * The implementation may modify the contents of the reqs array, e.g. to merge
2099 * requests. However, the fields opaque and error are left unmodified as they
2100 * are used to signal failure for a single request to the caller.
2102 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
2104 BlockDriverAIOCB *acb;
2108 if (num_reqs == 0) {
2112 // Create MultiwriteCB structure
2113 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
2114 mcb->num_requests = 0;
2115 mcb->num_callbacks = num_reqs;
2117 for (i = 0; i < num_reqs; i++) {
2118 mcb->callbacks[i].cb = reqs[i].cb;
2119 mcb->callbacks[i].opaque = reqs[i].opaque;
2122 // Check for mergable requests
2123 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
2125 // Run the aio requests
2126 for (i = 0; i < num_reqs; i++) {
2127 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
2128 reqs[i].nb_sectors, multiwrite_cb, mcb);
2131 // We can only fail the whole thing if no request has been
2132 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2133 // complete and report the error in the callback.
2134 if (mcb->num_requests == 0) {
2135 reqs[i].error = -EIO;
2138 mcb->num_requests++;
2139 multiwrite_cb(mcb, -EIO);
2143 mcb->num_requests++;
2154 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
2155 BlockDriverCompletionFunc *cb, void *opaque)
2157 BlockDriver *drv = bs->drv;
2159 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2160 return bdrv_aio_noop_em(bs, cb, opaque);
2165 return drv->bdrv_aio_flush(bs, cb, opaque);
2168 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
2170 acb->pool->cancel(acb);
2174 /**************************************************************/
2175 /* async block device emulation */
2177 typedef struct BlockDriverAIOCBSync {
2178 BlockDriverAIOCB common;
2181 /* vector translation state */
2185 } BlockDriverAIOCBSync;
2187 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
2189 BlockDriverAIOCBSync *acb =
2190 container_of(blockacb, BlockDriverAIOCBSync, common);
2191 qemu_bh_delete(acb->bh);
2193 qemu_aio_release(acb);
2196 static AIOPool bdrv_em_aio_pool = {
2197 .aiocb_size = sizeof(BlockDriverAIOCBSync),
2198 .cancel = bdrv_aio_cancel_em,
2201 static void bdrv_aio_bh_cb(void *opaque)
2203 BlockDriverAIOCBSync *acb = opaque;
2206 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
2207 qemu_vfree(acb->bounce);
2208 acb->common.cb(acb->common.opaque, acb->ret);
2209 qemu_bh_delete(acb->bh);
2211 qemu_aio_release(acb);
2214 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
2218 BlockDriverCompletionFunc *cb,
2223 BlockDriverAIOCBSync *acb;
2225 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2226 acb->is_write = is_write;
2228 acb->bounce = qemu_blockalign(bs, qiov->size);
2231 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2234 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
2235 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
2237 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
2240 qemu_bh_schedule(acb->bh);
2242 return &acb->common;
2245 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
2246 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2247 BlockDriverCompletionFunc *cb, void *opaque)
2249 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
2252 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
2253 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
2254 BlockDriverCompletionFunc *cb, void *opaque)
2256 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
2259 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
2260 BlockDriverCompletionFunc *cb, void *opaque)
2262 BlockDriverAIOCBSync *acb;
2264 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2265 acb->is_write = 1; /* don't bounce in the completion hadler */
2271 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2274 qemu_bh_schedule(acb->bh);
2275 return &acb->common;
2278 static BlockDriverAIOCB *bdrv_aio_noop_em(BlockDriverState *bs,
2279 BlockDriverCompletionFunc *cb, void *opaque)
2281 BlockDriverAIOCBSync *acb;
2283 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
2284 acb->is_write = 1; /* don't bounce in the completion handler */
2290 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
2293 qemu_bh_schedule(acb->bh);
2294 return &acb->common;
2297 /**************************************************************/
2298 /* sync block device emulation */
2300 static void bdrv_rw_em_cb(void *opaque, int ret)
2302 *(int *)opaque = ret;
2305 #define NOT_DONE 0x7fffffff
2307 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
2308 uint8_t *buf, int nb_sectors)
2311 BlockDriverAIOCB *acb;
2315 async_context_push();
2317 async_ret = NOT_DONE;
2318 iov.iov_base = (void *)buf;
2319 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2320 qemu_iovec_init_external(&qiov, &iov, 1);
2321 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
2322 bdrv_rw_em_cb, &async_ret);
2328 while (async_ret == NOT_DONE) {
2334 async_context_pop();
2338 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
2339 const uint8_t *buf, int nb_sectors)
2342 BlockDriverAIOCB *acb;
2346 async_context_push();
2348 async_ret = NOT_DONE;
2349 iov.iov_base = (void *)buf;
2350 iov.iov_len = nb_sectors * BDRV_SECTOR_SIZE;
2351 qemu_iovec_init_external(&qiov, &iov, 1);
2352 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
2353 bdrv_rw_em_cb, &async_ret);
2358 while (async_ret == NOT_DONE) {
2363 async_context_pop();
2367 void bdrv_init(void)
2369 module_call_init(MODULE_INIT_BLOCK);
2372 void bdrv_init_with_whitelist(void)
2374 use_bdrv_whitelist = 1;
2378 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
2379 BlockDriverCompletionFunc *cb, void *opaque)
2381 BlockDriverAIOCB *acb;
2383 if (pool->free_aiocb) {
2384 acb = pool->free_aiocb;
2385 pool->free_aiocb = acb->next;
2387 acb = qemu_mallocz(pool->aiocb_size);
2392 acb->opaque = opaque;
2396 void qemu_aio_release(void *p)
2398 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
2399 AIOPool *pool = acb->pool;
2400 acb->next = pool->free_aiocb;
2401 pool->free_aiocb = acb;
2404 /**************************************************************/
2405 /* removable device support */
2408 * Return TRUE if the media is present
2410 int bdrv_is_inserted(BlockDriverState *bs)
2412 BlockDriver *drv = bs->drv;
2416 if (!drv->bdrv_is_inserted)
2418 ret = drv->bdrv_is_inserted(bs);
2423 * Return TRUE if the media changed since the last call to this
2424 * function. It is currently only used for floppy disks
2426 int bdrv_media_changed(BlockDriverState *bs)
2428 BlockDriver *drv = bs->drv;
2431 if (!drv || !drv->bdrv_media_changed)
2434 ret = drv->bdrv_media_changed(bs);
2435 if (ret == -ENOTSUP)
2436 ret = bs->media_changed;
2437 bs->media_changed = 0;
2442 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2444 int bdrv_eject(BlockDriverState *bs, int eject_flag)
2446 BlockDriver *drv = bs->drv;
2453 if (!drv || !drv->bdrv_eject) {
2456 ret = drv->bdrv_eject(bs, eject_flag);
2458 if (ret == -ENOTSUP) {
2467 int bdrv_is_locked(BlockDriverState *bs)
2473 * Lock or unlock the media (if it is locked, the user won't be able
2474 * to eject it manually).
2476 void bdrv_set_locked(BlockDriverState *bs, int locked)
2478 BlockDriver *drv = bs->drv;
2480 bs->locked = locked;
2481 if (drv && drv->bdrv_set_locked) {
2482 drv->bdrv_set_locked(bs, locked);
2486 /* needed for generic scsi interface */
2488 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
2490 BlockDriver *drv = bs->drv;
2492 if (drv && drv->bdrv_ioctl)
2493 return drv->bdrv_ioctl(bs, req, buf);
2497 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
2498 unsigned long int req, void *buf,
2499 BlockDriverCompletionFunc *cb, void *opaque)
2501 BlockDriver *drv = bs->drv;
2503 if (drv && drv->bdrv_aio_ioctl)
2504 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
2510 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2512 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);
2515 void bdrv_set_dirty_tracking(BlockDriverState *bs, int enable)
2517 int64_t bitmap_size;
2519 bs->dirty_count = 0;
2521 if (!bs->dirty_bitmap) {
2522 bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS) +
2523 BDRV_SECTORS_PER_DIRTY_CHUNK * 8 - 1;
2524 bitmap_size /= BDRV_SECTORS_PER_DIRTY_CHUNK * 8;
2526 bs->dirty_bitmap = qemu_mallocz(bitmap_size);
2529 if (bs->dirty_bitmap) {
2530 qemu_free(bs->dirty_bitmap);
2531 bs->dirty_bitmap = NULL;
2536 int bdrv_get_dirty(BlockDriverState *bs, int64_t sector)
2538 int64_t chunk = sector / (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK;
2540 if (bs->dirty_bitmap &&
2541 (sector << BDRV_SECTOR_BITS) < bdrv_getlength(bs)) {
2542 return bs->dirty_bitmap[chunk / (sizeof(unsigned long) * 8)] &
2543 (1 << (chunk % (sizeof(unsigned long) * 8)));
2549 void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
2552 set_dirty_bitmap(bs, cur_sector, nr_sectors, 0);
2555 int64_t bdrv_get_dirty_count(BlockDriverState *bs)
2557 return bs->dirty_count;