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"
31 #include <sys/types.h>
33 #include <sys/ioctl.h>
34 #include <sys/queue.h>
45 #define SECTOR_SIZE (1 << SECTOR_BITS)
47 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
48 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
49 BlockDriverCompletionFunc *cb, void *opaque);
50 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
51 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
52 BlockDriverCompletionFunc *cb, void *opaque);
53 static BlockDriverAIOCB *bdrv_aio_flush_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 BlockDriverState *bdrv_first;
62 static BlockDriver *first_drv;
64 int path_is_absolute(const char *path)
68 /* specific case for names like: "\\.\d:" */
69 if (*path == '/' || *path == '\\')
72 p = strchr(path, ':');
78 return (*p == '/' || *p == '\\');
84 /* if filename is absolute, just copy it to dest. Otherwise, build a
85 path to it by considering it is relative to base_path. URL are
87 void path_combine(char *dest, int dest_size,
88 const char *base_path,
96 if (path_is_absolute(filename)) {
97 pstrcpy(dest, dest_size, filename);
99 p = strchr(base_path, ':');
104 p1 = strrchr(base_path, '/');
108 p2 = strrchr(base_path, '\\');
120 if (len > dest_size - 1)
122 memcpy(dest, base_path, len);
124 pstrcat(dest, dest_size, filename);
128 void bdrv_register(BlockDriver *bdrv)
130 if (!bdrv->bdrv_aio_readv) {
131 /* add AIO emulation layer */
132 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
133 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
134 } else if (!bdrv->bdrv_read) {
135 /* add synchronous IO emulation layer */
136 bdrv->bdrv_read = bdrv_read_em;
137 bdrv->bdrv_write = bdrv_write_em;
140 if (!bdrv->bdrv_aio_flush)
141 bdrv->bdrv_aio_flush = bdrv_aio_flush_em;
143 bdrv->next = first_drv;
147 /* create a new block device (by default it is empty) */
148 BlockDriverState *bdrv_new(const char *device_name)
150 BlockDriverState **pbs, *bs;
152 bs = qemu_mallocz(sizeof(BlockDriverState));
153 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
154 if (device_name[0] != '\0') {
155 /* insert at the end */
164 BlockDriver *bdrv_find_format(const char *format_name)
167 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
168 if (!strcmp(drv1->format_name, format_name))
174 int bdrv_create(BlockDriver *drv, const char* filename,
175 QEMUOptionParameter *options)
177 if (!drv->bdrv_create)
180 return drv->bdrv_create(filename, options);
184 void get_tmp_filename(char *filename, int size)
186 char temp_dir[MAX_PATH];
188 GetTempPath(MAX_PATH, temp_dir);
189 GetTempFileName(temp_dir, "qem", 0, filename);
192 void get_tmp_filename(char *filename, int size)
196 /* XXX: race condition possible */
197 tmpdir = getenv("TMPDIR");
200 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
201 fd = mkstemp(filename);
207 static int is_windows_drive_prefix(const char *filename)
209 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
210 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
214 int is_windows_drive(const char *filename)
216 if (is_windows_drive_prefix(filename) &&
219 if (strstart(filename, "\\\\.\\", NULL) ||
220 strstart(filename, "//./", NULL))
226 static BlockDriver *find_protocol(const char *filename)
234 if (is_windows_drive(filename) ||
235 is_windows_drive_prefix(filename))
236 return bdrv_find_format("raw");
238 p = strchr(filename, ':');
240 return bdrv_find_format("raw");
242 if (len > sizeof(protocol) - 1)
243 len = sizeof(protocol) - 1;
244 memcpy(protocol, filename, len);
245 protocol[len] = '\0';
246 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
247 if (drv1->protocol_name &&
248 !strcmp(drv1->protocol_name, protocol))
255 * Detect host devices. By convention, /dev/cdrom[N] is always
256 * recognized as a host CDROM.
258 static BlockDriver *find_hdev_driver(const char *filename)
260 int score_max = 0, score;
261 BlockDriver *drv = NULL, *d;
263 for (d = first_drv; d; d = d->next) {
264 if (d->bdrv_probe_device) {
265 score = d->bdrv_probe_device(filename);
266 if (score > score_max) {
276 static BlockDriver *find_image_format(const char *filename)
278 int ret, score, score_max;
279 BlockDriver *drv1, *drv;
281 BlockDriverState *bs;
283 drv = find_protocol(filename);
284 /* no need to test disk image formats for vvfat */
285 if (drv && strcmp(drv->format_name, "vvfat") == 0)
288 ret = bdrv_file_open(&bs, filename, BDRV_O_RDONLY);
291 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
298 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
299 if (drv1->bdrv_probe) {
300 score = drv1->bdrv_probe(buf, ret, filename);
301 if (score > score_max) {
310 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
312 BlockDriverState *bs;
316 ret = bdrv_open2(bs, filename, flags | BDRV_O_FILE, NULL);
326 int bdrv_open(BlockDriverState *bs, const char *filename, int flags)
328 return bdrv_open2(bs, filename, flags, NULL);
331 int bdrv_open2(BlockDriverState *bs, const char *filename, int flags,
335 char tmp_filename[PATH_MAX];
336 char backing_filename[PATH_MAX];
339 bs->is_temporary = 0;
342 /* buffer_alignment defaulted to 512, drivers can change this value */
343 bs->buffer_alignment = 512;
345 if (flags & BDRV_O_SNAPSHOT) {
346 BlockDriverState *bs1;
349 BlockDriver *bdrv_qcow2;
350 QEMUOptionParameter *options;
352 /* if snapshot, we create a temporary backing file and open it
353 instead of opening 'filename' directly */
355 /* if there is a backing file, use it */
357 ret = bdrv_open2(bs1, filename, 0, drv);
362 total_size = bdrv_getlength(bs1) >> SECTOR_BITS;
364 if (bs1->drv && bs1->drv->protocol_name)
369 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
371 /* Real path is meaningless for protocols */
373 snprintf(backing_filename, sizeof(backing_filename),
376 realpath(filename, backing_filename);
378 bdrv_qcow2 = bdrv_find_format("qcow2");
379 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
381 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size * 512);
382 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
384 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
388 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
393 filename = tmp_filename;
395 bs->is_temporary = 1;
398 pstrcpy(bs->filename, sizeof(bs->filename), filename);
399 if (flags & BDRV_O_FILE) {
400 drv = find_protocol(filename);
402 drv = find_hdev_driver(filename);
404 drv = find_image_format(filename);
409 goto unlink_and_fail;
412 bs->opaque = qemu_mallocz(drv->instance_size);
415 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
416 * write cache to the guest. We do need the fdatasync to flush
417 * out transactions for block allocations, and we maybe have a
418 * volatile write cache in our backing device to deal with.
420 if (flags & (BDRV_O_CACHE_WB|BDRV_O_NOCACHE))
421 bs->enable_write_cache = 1;
423 /* Note: for compatibility, we open disk image files as RDWR, and
424 RDONLY as fallback */
425 if (!(flags & BDRV_O_FILE))
426 open_flags = BDRV_O_RDWR |
427 (flags & (BDRV_O_CACHE_MASK|BDRV_O_NATIVE_AIO));
429 open_flags = flags & ~(BDRV_O_FILE | BDRV_O_SNAPSHOT);
430 ret = drv->bdrv_open(bs, filename, open_flags);
431 if ((ret == -EACCES || ret == -EPERM) && !(flags & BDRV_O_FILE)) {
432 ret = drv->bdrv_open(bs, filename, open_flags & ~BDRV_O_RDWR);
436 qemu_free(bs->opaque);
440 if (bs->is_temporary)
444 if (drv->bdrv_getlength) {
445 bs->total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
448 if (bs->is_temporary) {
452 if (bs->backing_file[0] != '\0') {
453 /* if there is a backing file, use it */
454 BlockDriver *back_drv = NULL;
455 bs->backing_hd = bdrv_new("");
456 path_combine(backing_filename, sizeof(backing_filename),
457 filename, bs->backing_file);
458 if (bs->backing_format[0] != '\0')
459 back_drv = bdrv_find_format(bs->backing_format);
460 ret = bdrv_open2(bs->backing_hd, backing_filename, open_flags,
468 if (!bdrv_key_required(bs)) {
469 /* call the change callback */
470 bs->media_changed = 1;
472 bs->change_cb(bs->change_opaque);
477 void bdrv_close(BlockDriverState *bs)
481 bdrv_delete(bs->backing_hd);
482 bs->drv->bdrv_close(bs);
483 qemu_free(bs->opaque);
485 if (bs->is_temporary) {
486 unlink(bs->filename);
492 /* call the change callback */
493 bs->media_changed = 1;
495 bs->change_cb(bs->change_opaque);
499 void bdrv_delete(BlockDriverState *bs)
501 BlockDriverState **pbs;
504 while (*pbs != bs && *pbs != NULL)
514 * Run consistency checks on an image
516 * Returns the number of errors or -errno when an internal error occurs
518 int bdrv_check(BlockDriverState *bs)
520 if (bs->drv->bdrv_check == NULL) {
524 return bs->drv->bdrv_check(bs);
527 /* commit COW file into the raw image */
528 int bdrv_commit(BlockDriverState *bs)
530 BlockDriver *drv = bs->drv;
531 int64_t i, total_sectors;
533 unsigned char sector[512];
542 if (!bs->backing_hd) {
546 total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
547 for (i = 0; i < total_sectors;) {
548 if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
549 for(j = 0; j < n; j++) {
550 if (bdrv_read(bs, i, sector, 1) != 0) {
554 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
564 if (drv->bdrv_make_empty)
565 return drv->bdrv_make_empty(bs);
570 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
575 if (!bdrv_is_inserted(bs))
581 len = bdrv_getlength(bs);
586 if ((offset > len) || (len - offset < size))
592 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
595 return bdrv_check_byte_request(bs, sector_num * 512, nb_sectors * 512);
598 /* return < 0 if error. See bdrv_write() for the return codes */
599 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
600 uint8_t *buf, int nb_sectors)
602 BlockDriver *drv = bs->drv;
606 if (bdrv_check_request(bs, sector_num, nb_sectors))
609 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
612 /* Return < 0 if error. Important errors are:
613 -EIO generic I/O error (may happen for all errors)
614 -ENOMEDIUM No media inserted.
615 -EINVAL Invalid sector number or nb_sectors
616 -EACCES Trying to write a read-only device
618 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
619 const uint8_t *buf, int nb_sectors)
621 BlockDriver *drv = bs->drv;
626 if (bdrv_check_request(bs, sector_num, nb_sectors))
629 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
632 int bdrv_pread(BlockDriverState *bs, int64_t offset,
633 void *buf, int count1)
635 uint8_t tmp_buf[SECTOR_SIZE];
636 int len, nb_sectors, count;
640 /* first read to align to sector start */
641 len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
644 sector_num = offset >> SECTOR_BITS;
646 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
648 memcpy(buf, tmp_buf + (offset & (SECTOR_SIZE - 1)), len);
656 /* read the sectors "in place" */
657 nb_sectors = count >> SECTOR_BITS;
658 if (nb_sectors > 0) {
659 if (bdrv_read(bs, sector_num, buf, nb_sectors) < 0)
661 sector_num += nb_sectors;
662 len = nb_sectors << SECTOR_BITS;
667 /* add data from the last sector */
669 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
671 memcpy(buf, tmp_buf, count);
676 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
677 const void *buf, int count1)
679 uint8_t tmp_buf[SECTOR_SIZE];
680 int len, nb_sectors, count;
684 /* first write to align to sector start */
685 len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
688 sector_num = offset >> SECTOR_BITS;
690 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
692 memcpy(tmp_buf + (offset & (SECTOR_SIZE - 1)), buf, len);
693 if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
702 /* write the sectors "in place" */
703 nb_sectors = count >> SECTOR_BITS;
704 if (nb_sectors > 0) {
705 if (bdrv_write(bs, sector_num, buf, nb_sectors) < 0)
707 sector_num += nb_sectors;
708 len = nb_sectors << SECTOR_BITS;
713 /* add data from the last sector */
715 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
717 memcpy(tmp_buf, buf, count);
718 if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
725 * Truncate file to 'offset' bytes (needed only for file protocols)
727 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
729 BlockDriver *drv = bs->drv;
732 if (!drv->bdrv_truncate)
734 return drv->bdrv_truncate(bs, offset);
738 * Length of a file in bytes. Return < 0 if error or unknown.
740 int64_t bdrv_getlength(BlockDriverState *bs)
742 BlockDriver *drv = bs->drv;
745 if (!drv->bdrv_getlength) {
747 return bs->total_sectors * SECTOR_SIZE;
749 return drv->bdrv_getlength(bs);
752 /* return 0 as number of sectors if no device present or error */
753 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
756 length = bdrv_getlength(bs);
760 length = length >> SECTOR_BITS;
761 *nb_sectors_ptr = length;
765 uint8_t boot_ind; /* 0x80 - active */
766 uint8_t head; /* starting head */
767 uint8_t sector; /* starting sector */
768 uint8_t cyl; /* starting cylinder */
769 uint8_t sys_ind; /* What partition type */
770 uint8_t end_head; /* end head */
771 uint8_t end_sector; /* end sector */
772 uint8_t end_cyl; /* end cylinder */
773 uint32_t start_sect; /* starting sector counting from 0 */
774 uint32_t nr_sects; /* nr of sectors in partition */
775 } __attribute__((packed));
777 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
778 static int guess_disk_lchs(BlockDriverState *bs,
779 int *pcylinders, int *pheads, int *psectors)
782 int ret, i, heads, sectors, cylinders;
787 bdrv_get_geometry(bs, &nb_sectors);
789 ret = bdrv_read(bs, 0, buf, 1);
792 /* test msdos magic */
793 if (buf[510] != 0x55 || buf[511] != 0xaa)
795 for(i = 0; i < 4; i++) {
796 p = ((struct partition *)(buf + 0x1be)) + i;
797 nr_sects = le32_to_cpu(p->nr_sects);
798 if (nr_sects && p->end_head) {
799 /* We make the assumption that the partition terminates on
800 a cylinder boundary */
801 heads = p->end_head + 1;
802 sectors = p->end_sector & 63;
805 cylinders = nb_sectors / (heads * sectors);
806 if (cylinders < 1 || cylinders > 16383)
810 *pcylinders = cylinders;
812 printf("guessed geometry: LCHS=%d %d %d\n",
813 cylinders, heads, sectors);
821 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
823 int translation, lba_detected = 0;
824 int cylinders, heads, secs;
827 /* if a geometry hint is available, use it */
828 bdrv_get_geometry(bs, &nb_sectors);
829 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
830 translation = bdrv_get_translation_hint(bs);
831 if (cylinders != 0) {
836 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
838 /* if heads > 16, it means that a BIOS LBA
839 translation was active, so the default
840 hardware geometry is OK */
842 goto default_geometry;
847 /* disable any translation to be in sync with
848 the logical geometry */
849 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
850 bdrv_set_translation_hint(bs,
851 BIOS_ATA_TRANSLATION_NONE);
856 /* if no geometry, use a standard physical disk geometry */
857 cylinders = nb_sectors / (16 * 63);
859 if (cylinders > 16383)
861 else if (cylinders < 2)
866 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
867 if ((*pcyls * *pheads) <= 131072) {
868 bdrv_set_translation_hint(bs,
869 BIOS_ATA_TRANSLATION_LARGE);
871 bdrv_set_translation_hint(bs,
872 BIOS_ATA_TRANSLATION_LBA);
876 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
880 void bdrv_set_geometry_hint(BlockDriverState *bs,
881 int cyls, int heads, int secs)
888 void bdrv_set_type_hint(BlockDriverState *bs, int type)
891 bs->removable = ((type == BDRV_TYPE_CDROM ||
892 type == BDRV_TYPE_FLOPPY));
895 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
897 bs->translation = translation;
900 void bdrv_get_geometry_hint(BlockDriverState *bs,
901 int *pcyls, int *pheads, int *psecs)
908 int bdrv_get_type_hint(BlockDriverState *bs)
913 int bdrv_get_translation_hint(BlockDriverState *bs)
915 return bs->translation;
918 int bdrv_is_removable(BlockDriverState *bs)
920 return bs->removable;
923 int bdrv_is_read_only(BlockDriverState *bs)
925 return bs->read_only;
928 int bdrv_is_sg(BlockDriverState *bs)
933 int bdrv_enable_write_cache(BlockDriverState *bs)
935 return bs->enable_write_cache;
938 /* XXX: no longer used */
939 void bdrv_set_change_cb(BlockDriverState *bs,
940 void (*change_cb)(void *opaque), void *opaque)
942 bs->change_cb = change_cb;
943 bs->change_opaque = opaque;
946 int bdrv_is_encrypted(BlockDriverState *bs)
948 if (bs->backing_hd && bs->backing_hd->encrypted)
950 return bs->encrypted;
953 int bdrv_key_required(BlockDriverState *bs)
955 BlockDriverState *backing_hd = bs->backing_hd;
957 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
959 return (bs->encrypted && !bs->valid_key);
962 int bdrv_set_key(BlockDriverState *bs, const char *key)
965 if (bs->backing_hd && bs->backing_hd->encrypted) {
966 ret = bdrv_set_key(bs->backing_hd, key);
972 if (!bs->encrypted || !bs->drv || !bs->drv->bdrv_set_key)
974 ret = bs->drv->bdrv_set_key(bs, key);
977 } else if (!bs->valid_key) {
979 /* call the change callback now, we skipped it on open */
980 bs->media_changed = 1;
982 bs->change_cb(bs->change_opaque);
987 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
992 pstrcpy(buf, buf_size, bs->drv->format_name);
996 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1001 for (drv = first_drv; drv != NULL; drv = drv->next) {
1002 it(opaque, drv->format_name);
1006 BlockDriverState *bdrv_find(const char *name)
1008 BlockDriverState *bs;
1010 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1011 if (!strcmp(name, bs->device_name))
1017 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1019 BlockDriverState *bs;
1021 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1026 const char *bdrv_get_device_name(BlockDriverState *bs)
1028 return bs->device_name;
1031 void bdrv_flush(BlockDriverState *bs)
1035 if (bs->drv->bdrv_flush)
1036 bs->drv->bdrv_flush(bs);
1038 bdrv_flush(bs->backing_hd);
1041 void bdrv_flush_all(void)
1043 BlockDriverState *bs;
1045 for (bs = bdrv_first; bs != NULL; bs = bs->next)
1046 if (bs->drv && !bdrv_is_read_only(bs) &&
1047 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs)))
1052 * Returns true iff the specified sector is present in the disk image. Drivers
1053 * not implementing the functionality are assumed to not support backing files,
1054 * hence all their sectors are reported as allocated.
1056 * 'pnum' is set to the number of sectors (including and immediately following
1057 * the specified sector) that are known to be in the same
1058 * allocated/unallocated state.
1060 * 'nb_sectors' is the max value 'pnum' should be set to.
1062 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1066 if (!bs->drv->bdrv_is_allocated) {
1067 if (sector_num >= bs->total_sectors) {
1071 n = bs->total_sectors - sector_num;
1072 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1075 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1078 void bdrv_info(Monitor *mon)
1080 BlockDriverState *bs;
1082 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1083 monitor_printf(mon, "%s:", bs->device_name);
1084 monitor_printf(mon, " type=");
1087 monitor_printf(mon, "hd");
1089 case BDRV_TYPE_CDROM:
1090 monitor_printf(mon, "cdrom");
1092 case BDRV_TYPE_FLOPPY:
1093 monitor_printf(mon, "floppy");
1096 monitor_printf(mon, " removable=%d", bs->removable);
1097 if (bs->removable) {
1098 monitor_printf(mon, " locked=%d", bs->locked);
1101 monitor_printf(mon, " file=");
1102 monitor_print_filename(mon, bs->filename);
1103 if (bs->backing_file[0] != '\0') {
1104 monitor_printf(mon, " backing_file=");
1105 monitor_print_filename(mon, bs->backing_file);
1107 monitor_printf(mon, " ro=%d", bs->read_only);
1108 monitor_printf(mon, " drv=%s", bs->drv->format_name);
1109 monitor_printf(mon, " encrypted=%d", bdrv_is_encrypted(bs));
1111 monitor_printf(mon, " [not inserted]");
1113 monitor_printf(mon, "\n");
1117 /* The "info blockstats" command. */
1118 void bdrv_info_stats(Monitor *mon)
1120 BlockDriverState *bs;
1122 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1123 monitor_printf(mon, "%s:"
1124 " rd_bytes=%" PRIu64
1125 " wr_bytes=%" PRIu64
1126 " rd_operations=%" PRIu64
1127 " wr_operations=%" PRIu64
1130 bs->rd_bytes, bs->wr_bytes,
1131 bs->rd_ops, bs->wr_ops);
1135 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1137 if (bs->backing_hd && bs->backing_hd->encrypted)
1138 return bs->backing_file;
1139 else if (bs->encrypted)
1140 return bs->filename;
1145 void bdrv_get_backing_filename(BlockDriverState *bs,
1146 char *filename, int filename_size)
1148 if (!bs->backing_hd) {
1149 pstrcpy(filename, filename_size, "");
1151 pstrcpy(filename, filename_size, bs->backing_file);
1155 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1156 const uint8_t *buf, int nb_sectors)
1158 BlockDriver *drv = bs->drv;
1161 if (!drv->bdrv_write_compressed)
1163 if (bdrv_check_request(bs, sector_num, nb_sectors))
1165 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1168 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1170 BlockDriver *drv = bs->drv;
1173 if (!drv->bdrv_get_info)
1175 memset(bdi, 0, sizeof(*bdi));
1176 return drv->bdrv_get_info(bs, bdi);
1179 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1180 int64_t pos, int size)
1182 BlockDriver *drv = bs->drv;
1185 if (!drv->bdrv_save_vmstate)
1187 return drv->bdrv_save_vmstate(bs, buf, pos, size);
1190 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1191 int64_t pos, int size)
1193 BlockDriver *drv = bs->drv;
1196 if (!drv->bdrv_load_vmstate)
1198 return drv->bdrv_load_vmstate(bs, buf, pos, size);
1201 /**************************************************************/
1202 /* handling of snapshots */
1204 int bdrv_snapshot_create(BlockDriverState *bs,
1205 QEMUSnapshotInfo *sn_info)
1207 BlockDriver *drv = bs->drv;
1210 if (!drv->bdrv_snapshot_create)
1212 return drv->bdrv_snapshot_create(bs, sn_info);
1215 int bdrv_snapshot_goto(BlockDriverState *bs,
1216 const char *snapshot_id)
1218 BlockDriver *drv = bs->drv;
1221 if (!drv->bdrv_snapshot_goto)
1223 return drv->bdrv_snapshot_goto(bs, snapshot_id);
1226 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1228 BlockDriver *drv = bs->drv;
1231 if (!drv->bdrv_snapshot_delete)
1233 return drv->bdrv_snapshot_delete(bs, snapshot_id);
1236 int bdrv_snapshot_list(BlockDriverState *bs,
1237 QEMUSnapshotInfo **psn_info)
1239 BlockDriver *drv = bs->drv;
1242 if (!drv->bdrv_snapshot_list)
1244 return drv->bdrv_snapshot_list(bs, psn_info);
1247 #define NB_SUFFIXES 4
1249 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1251 static const char suffixes[NB_SUFFIXES] = "KMGT";
1256 snprintf(buf, buf_size, "%" PRId64, size);
1259 for(i = 0; i < NB_SUFFIXES; i++) {
1260 if (size < (10 * base)) {
1261 snprintf(buf, buf_size, "%0.1f%c",
1262 (double)size / base,
1265 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1266 snprintf(buf, buf_size, "%" PRId64 "%c",
1267 ((size + (base >> 1)) / base),
1277 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1279 char buf1[128], date_buf[128], clock_buf[128];
1289 snprintf(buf, buf_size,
1290 "%-10s%-20s%7s%20s%15s",
1291 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1295 ptm = localtime(&ti);
1296 strftime(date_buf, sizeof(date_buf),
1297 "%Y-%m-%d %H:%M:%S", ptm);
1299 localtime_r(&ti, &tm);
1300 strftime(date_buf, sizeof(date_buf),
1301 "%Y-%m-%d %H:%M:%S", &tm);
1303 secs = sn->vm_clock_nsec / 1000000000;
1304 snprintf(clock_buf, sizeof(clock_buf),
1305 "%02d:%02d:%02d.%03d",
1307 (int)((secs / 60) % 60),
1309 (int)((sn->vm_clock_nsec / 1000000) % 1000));
1310 snprintf(buf, buf_size,
1311 "%-10s%-20s%7s%20s%15s",
1312 sn->id_str, sn->name,
1313 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1321 /**************************************************************/
1324 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1325 QEMUIOVector *qiov, int nb_sectors,
1326 BlockDriverCompletionFunc *cb, void *opaque)
1328 BlockDriver *drv = bs->drv;
1329 BlockDriverAIOCB *ret;
1333 if (bdrv_check_request(bs, sector_num, nb_sectors))
1336 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1340 /* Update stats even though technically transfer has not happened. */
1341 bs->rd_bytes += (unsigned) nb_sectors * SECTOR_SIZE;
1348 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1349 QEMUIOVector *qiov, int nb_sectors,
1350 BlockDriverCompletionFunc *cb, void *opaque)
1352 BlockDriver *drv = bs->drv;
1353 BlockDriverAIOCB *ret;
1359 if (bdrv_check_request(bs, sector_num, nb_sectors))
1362 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
1366 /* Update stats even though technically transfer has not happened. */
1367 bs->wr_bytes += (unsigned) nb_sectors * SECTOR_SIZE;
1375 typedef struct MultiwriteCB {
1380 BlockDriverCompletionFunc *cb;
1382 QEMUIOVector *free_qiov;
1387 static void multiwrite_user_cb(MultiwriteCB *mcb)
1391 for (i = 0; i < mcb->num_callbacks; i++) {
1392 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1393 qemu_free(mcb->callbacks[i].free_qiov);
1394 qemu_free(mcb->callbacks[i].free_buf);
1398 static void multiwrite_cb(void *opaque, int ret)
1400 MultiwriteCB *mcb = opaque;
1404 multiwrite_user_cb(mcb);
1407 mcb->num_requests--;
1408 if (mcb->num_requests == 0) {
1409 if (mcb->error == 0) {
1410 multiwrite_user_cb(mcb);
1416 static int multiwrite_req_compare(const void *a, const void *b)
1418 return (((BlockRequest*) a)->sector - ((BlockRequest*) b)->sector);
1422 * Takes a bunch of requests and tries to merge them. Returns the number of
1423 * requests that remain after merging.
1425 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
1426 int num_reqs, MultiwriteCB *mcb)
1430 // Sort requests by start sector
1431 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
1433 // Check if adjacent requests touch the same clusters. If so, combine them,
1434 // filling up gaps with zero sectors.
1436 for (i = 1; i < num_reqs; i++) {
1438 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
1440 // This handles the cases that are valid for all block drivers, namely
1441 // exactly sequential writes and overlapping writes.
1442 if (reqs[i].sector <= oldreq_last) {
1446 // The block driver may decide that it makes sense to combine requests
1447 // even if there is a gap of some sectors between them. In this case,
1448 // the gap is filled with zeros (therefore only applicable for yet
1449 // unused space in format like qcow2).
1450 if (!merge && bs->drv->bdrv_merge_requests) {
1451 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
1456 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
1457 qemu_iovec_init(qiov,
1458 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
1460 // Add the first request to the merged one. If the requests are
1461 // overlapping, drop the last sectors of the first request.
1462 size = (reqs[i].sector - reqs[outidx].sector) << 9;
1463 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
1465 // We might need to add some zeros between the two requests
1466 if (reqs[i].sector > oldreq_last) {
1467 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
1468 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
1469 memset(buf, 0, zero_bytes);
1470 qemu_iovec_add(qiov, buf, zero_bytes);
1471 mcb->callbacks[i].free_buf = buf;
1474 // Add the second request
1475 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
1477 reqs[outidx].nb_sectors += reqs[i].nb_sectors;
1478 reqs[outidx].qiov = qiov;
1480 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
1483 reqs[outidx].sector = reqs[i].sector;
1484 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
1485 reqs[outidx].qiov = reqs[i].qiov;
1493 * Submit multiple AIO write requests at once.
1495 * On success, the function returns 0 and all requests in the reqs array have
1496 * been submitted. In error case this function returns -1, and any of the
1497 * requests may or may not be submitted yet. In particular, this means that the
1498 * callback will be called for some of the requests, for others it won't. The
1499 * caller must check the error field of the BlockRequest to wait for the right
1500 * callbacks (if error != 0, no callback will be called).
1502 * The implementation may modify the contents of the reqs array, e.g. to merge
1503 * requests. However, the fields opaque and error are left unmodified as they
1504 * are used to signal failure for a single request to the caller.
1506 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
1508 BlockDriverAIOCB *acb;
1512 if (num_reqs == 0) {
1516 // Create MultiwriteCB structure
1517 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
1518 mcb->num_requests = 0;
1519 mcb->num_callbacks = num_reqs;
1521 for (i = 0; i < num_reqs; i++) {
1522 mcb->callbacks[i].cb = reqs[i].cb;
1523 mcb->callbacks[i].opaque = reqs[i].opaque;
1526 // Check for mergable requests
1527 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
1529 // Run the aio requests
1530 for (i = 0; i < num_reqs; i++) {
1531 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
1532 reqs[i].nb_sectors, multiwrite_cb, mcb);
1535 // We can only fail the whole thing if no request has been
1536 // submitted yet. Otherwise we'll wait for the submitted AIOs to
1537 // complete and report the error in the callback.
1538 if (mcb->num_requests == 0) {
1539 reqs[i].error = EIO;
1546 mcb->num_requests++;
1557 BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
1558 BlockDriverCompletionFunc *cb, void *opaque)
1560 BlockDriver *drv = bs->drv;
1566 * Note that unlike bdrv_flush the driver is reponsible for flushing a
1567 * backing image if it exists.
1569 return drv->bdrv_aio_flush(bs, cb, opaque);
1572 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
1574 acb->pool->cancel(acb);
1578 /**************************************************************/
1579 /* async block device emulation */
1581 typedef struct BlockDriverAIOCBSync {
1582 BlockDriverAIOCB common;
1585 /* vector translation state */
1589 } BlockDriverAIOCBSync;
1591 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
1593 BlockDriverAIOCBSync *acb = (BlockDriverAIOCBSync *)blockacb;
1594 qemu_bh_delete(acb->bh);
1596 qemu_aio_release(acb);
1599 static AIOPool bdrv_em_aio_pool = {
1600 .aiocb_size = sizeof(BlockDriverAIOCBSync),
1601 .cancel = bdrv_aio_cancel_em,
1604 static void bdrv_aio_bh_cb(void *opaque)
1606 BlockDriverAIOCBSync *acb = opaque;
1609 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
1610 qemu_vfree(acb->bounce);
1611 acb->common.cb(acb->common.opaque, acb->ret);
1612 qemu_bh_delete(acb->bh);
1614 qemu_aio_release(acb);
1617 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
1621 BlockDriverCompletionFunc *cb,
1626 BlockDriverAIOCBSync *acb;
1628 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
1629 acb->is_write = is_write;
1631 acb->bounce = qemu_blockalign(bs, qiov->size);
1634 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
1637 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
1638 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
1640 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
1643 qemu_bh_schedule(acb->bh);
1645 return &acb->common;
1648 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
1649 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1650 BlockDriverCompletionFunc *cb, void *opaque)
1652 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1655 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
1656 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1657 BlockDriverCompletionFunc *cb, void *opaque)
1659 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
1662 static BlockDriverAIOCB *bdrv_aio_flush_em(BlockDriverState *bs,
1663 BlockDriverCompletionFunc *cb, void *opaque)
1665 BlockDriverAIOCBSync *acb;
1667 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
1668 acb->is_write = 1; /* don't bounce in the completion hadler */
1674 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
1677 qemu_bh_schedule(acb->bh);
1678 return &acb->common;
1681 /**************************************************************/
1682 /* sync block device emulation */
1684 static void bdrv_rw_em_cb(void *opaque, int ret)
1686 *(int *)opaque = ret;
1689 #define NOT_DONE 0x7fffffff
1691 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
1692 uint8_t *buf, int nb_sectors)
1695 BlockDriverAIOCB *acb;
1699 async_context_push();
1701 async_ret = NOT_DONE;
1702 iov.iov_base = (void *)buf;
1703 iov.iov_len = nb_sectors * 512;
1704 qemu_iovec_init_external(&qiov, &iov, 1);
1705 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
1706 bdrv_rw_em_cb, &async_ret);
1712 while (async_ret == NOT_DONE) {
1718 async_context_pop();
1722 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
1723 const uint8_t *buf, int nb_sectors)
1726 BlockDriverAIOCB *acb;
1730 async_context_push();
1732 async_ret = NOT_DONE;
1733 iov.iov_base = (void *)buf;
1734 iov.iov_len = nb_sectors * 512;
1735 qemu_iovec_init_external(&qiov, &iov, 1);
1736 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
1737 bdrv_rw_em_cb, &async_ret);
1742 while (async_ret == NOT_DONE) {
1747 async_context_pop();
1751 void bdrv_init(void)
1753 module_call_init(MODULE_INIT_BLOCK);
1756 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
1757 BlockDriverCompletionFunc *cb, void *opaque)
1759 BlockDriverAIOCB *acb;
1761 if (pool->free_aiocb) {
1762 acb = pool->free_aiocb;
1763 pool->free_aiocb = acb->next;
1765 acb = qemu_mallocz(pool->aiocb_size);
1770 acb->opaque = opaque;
1774 void qemu_aio_release(void *p)
1776 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
1777 AIOPool *pool = acb->pool;
1778 acb->next = pool->free_aiocb;
1779 pool->free_aiocb = acb;
1782 /**************************************************************/
1783 /* removable device support */
1786 * Return TRUE if the media is present
1788 int bdrv_is_inserted(BlockDriverState *bs)
1790 BlockDriver *drv = bs->drv;
1794 if (!drv->bdrv_is_inserted)
1796 ret = drv->bdrv_is_inserted(bs);
1801 * Return TRUE if the media changed since the last call to this
1802 * function. It is currently only used for floppy disks
1804 int bdrv_media_changed(BlockDriverState *bs)
1806 BlockDriver *drv = bs->drv;
1809 if (!drv || !drv->bdrv_media_changed)
1812 ret = drv->bdrv_media_changed(bs);
1813 if (ret == -ENOTSUP)
1814 ret = bs->media_changed;
1815 bs->media_changed = 0;
1820 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
1822 int bdrv_eject(BlockDriverState *bs, int eject_flag)
1824 BlockDriver *drv = bs->drv;
1831 if (!drv || !drv->bdrv_eject) {
1834 ret = drv->bdrv_eject(bs, eject_flag);
1836 if (ret == -ENOTSUP) {
1845 int bdrv_is_locked(BlockDriverState *bs)
1851 * Lock or unlock the media (if it is locked, the user won't be able
1852 * to eject it manually).
1854 void bdrv_set_locked(BlockDriverState *bs, int locked)
1856 BlockDriver *drv = bs->drv;
1858 bs->locked = locked;
1859 if (drv && drv->bdrv_set_locked) {
1860 drv->bdrv_set_locked(bs, locked);
1864 /* needed for generic scsi interface */
1866 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1868 BlockDriver *drv = bs->drv;
1870 if (drv && drv->bdrv_ioctl)
1871 return drv->bdrv_ioctl(bs, req, buf);
1875 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
1876 unsigned long int req, void *buf,
1877 BlockDriverCompletionFunc *cb, void *opaque)
1879 BlockDriver *drv = bs->drv;
1881 if (drv && drv->bdrv_aio_ioctl)
1882 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
1886 void *qemu_blockalign(BlockDriverState *bs, size_t size)
1888 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);