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"
26 /* include native header before sys-queue.h */
27 #include <sys/queue.h>
30 #include "qemu-common.h"
32 #include "block_int.h"
36 #include <sys/types.h>
38 #include <sys/ioctl.h>
49 #define SECTOR_SIZE (1 << SECTOR_BITS)
51 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
52 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
53 BlockDriverCompletionFunc *cb, void *opaque);
54 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
55 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
56 BlockDriverCompletionFunc *cb, void *opaque);
57 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
58 uint8_t *buf, int nb_sectors);
59 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
60 const uint8_t *buf, int nb_sectors);
62 BlockDriverState *bdrv_first;
64 static BlockDriver *first_drv;
66 int path_is_absolute(const char *path)
70 /* specific case for names like: "\\.\d:" */
71 if (*path == '/' || *path == '\\')
74 p = strchr(path, ':');
80 return (*p == '/' || *p == '\\');
86 /* if filename is absolute, just copy it to dest. Otherwise, build a
87 path to it by considering it is relative to base_path. URL are
89 void path_combine(char *dest, int dest_size,
90 const char *base_path,
98 if (path_is_absolute(filename)) {
99 pstrcpy(dest, dest_size, filename);
101 p = strchr(base_path, ':');
106 p1 = strrchr(base_path, '/');
110 p2 = strrchr(base_path, '\\');
122 if (len > dest_size - 1)
124 memcpy(dest, base_path, len);
126 pstrcat(dest, dest_size, filename);
130 void bdrv_register(BlockDriver *bdrv)
132 if (!bdrv->bdrv_aio_readv) {
133 /* add AIO emulation layer */
134 bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
135 bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
136 } else if (!bdrv->bdrv_read) {
137 /* add synchronous IO emulation layer */
138 bdrv->bdrv_read = bdrv_read_em;
139 bdrv->bdrv_write = bdrv_write_em;
141 bdrv->next = first_drv;
145 /* create a new block device (by default it is empty) */
146 BlockDriverState *bdrv_new(const char *device_name)
148 BlockDriverState **pbs, *bs;
150 bs = qemu_mallocz(sizeof(BlockDriverState));
151 pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
152 if (device_name[0] != '\0') {
153 /* insert at the end */
162 BlockDriver *bdrv_find_format(const char *format_name)
165 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
166 if (!strcmp(drv1->format_name, format_name))
172 int bdrv_create(BlockDriver *drv, const char* filename,
173 QEMUOptionParameter *options)
175 if (!drv->bdrv_create)
178 return drv->bdrv_create(filename, options);
182 void get_tmp_filename(char *filename, int size)
184 char temp_dir[MAX_PATH];
186 GetTempPath(MAX_PATH, temp_dir);
187 GetTempFileName(temp_dir, "qem", 0, filename);
190 void get_tmp_filename(char *filename, int size)
194 /* XXX: race condition possible */
195 tmpdir = getenv("TMPDIR");
198 snprintf(filename, size, "%s/vl.XXXXXX", tmpdir);
199 fd = mkstemp(filename);
205 static int is_windows_drive_prefix(const char *filename)
207 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
208 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
212 static int is_windows_drive(const char *filename)
214 if (is_windows_drive_prefix(filename) &&
217 if (strstart(filename, "\\\\.\\", NULL) ||
218 strstart(filename, "//./", NULL))
224 static BlockDriver *find_protocol(const char *filename)
232 if (is_windows_drive(filename) ||
233 is_windows_drive_prefix(filename))
234 return bdrv_find_format("raw");
236 p = strchr(filename, ':');
238 return bdrv_find_format("raw");
240 if (len > sizeof(protocol) - 1)
241 len = sizeof(protocol) - 1;
242 memcpy(protocol, filename, len);
243 protocol[len] = '\0';
244 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
245 if (drv1->protocol_name &&
246 !strcmp(drv1->protocol_name, protocol))
253 * Detect host devices. By convention, /dev/cdrom[N] is always
254 * recognized as a host CDROM.
257 static BlockDriver *find_hdev_driver(const char *filename)
259 if (strstart(filename, "/dev/cdrom", NULL))
260 return bdrv_find_format("host_device");
261 if (is_windows_drive(filename))
262 return bdrv_find_format("host_device");
266 static BlockDriver *find_hdev_driver(const char *filename)
271 if (strstart(filename, "/dev/fd", NULL))
272 return bdrv_find_format("host_floppy");
273 if (strstart(filename, "/dev/cd", NULL))
274 return bdrv_find_format("host_cdrom");
275 #elif defined(__FreeBSD__)
276 if (strstart(filename, "/dev/cd", NULL) ||
277 strstart(filename, "/dev/acd", NULL)) {
278 return bdrv_find_format("host_cdrom");
281 if (strstart(filename, "/dev/cdrom", NULL))
282 return bdrv_find_format("host_device");
285 if (stat(filename, &st) >= 0 &&
286 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
287 return bdrv_find_format("host_device");
294 static BlockDriver *find_image_format(const char *filename)
296 int ret, score, score_max;
297 BlockDriver *drv1, *drv;
299 BlockDriverState *bs;
301 drv = find_protocol(filename);
302 /* no need to test disk image formats for vvfat */
303 if (drv && strcmp(drv->format_name, "vvfat") == 0)
306 ret = bdrv_file_open(&bs, filename, BDRV_O_RDONLY);
309 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
316 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
317 if (drv1->bdrv_probe) {
318 score = drv1->bdrv_probe(buf, ret, filename);
319 if (score > score_max) {
328 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
330 BlockDriverState *bs;
334 ret = bdrv_open2(bs, filename, flags | BDRV_O_FILE, NULL);
344 int bdrv_open(BlockDriverState *bs, const char *filename, int flags)
346 return bdrv_open2(bs, filename, flags, NULL);
349 int bdrv_open2(BlockDriverState *bs, const char *filename, int flags,
353 char tmp_filename[PATH_MAX];
354 char backing_filename[PATH_MAX];
357 bs->is_temporary = 0;
360 /* buffer_alignment defaulted to 512, drivers can change this value */
361 bs->buffer_alignment = 512;
363 if (flags & BDRV_O_SNAPSHOT) {
364 BlockDriverState *bs1;
367 BlockDriver *bdrv_qcow2;
368 QEMUOptionParameter *options;
370 /* if snapshot, we create a temporary backing file and open it
371 instead of opening 'filename' directly */
373 /* if there is a backing file, use it */
375 ret = bdrv_open2(bs1, filename, 0, drv);
380 total_size = bdrv_getlength(bs1) >> SECTOR_BITS;
382 if (bs1->drv && bs1->drv->protocol_name)
387 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
389 /* Real path is meaningless for protocols */
391 snprintf(backing_filename, sizeof(backing_filename),
394 realpath(filename, backing_filename);
396 bdrv_qcow2 = bdrv_find_format("qcow2");
397 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
399 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size * 512);
400 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
402 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
406 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
411 filename = tmp_filename;
413 bs->is_temporary = 1;
416 pstrcpy(bs->filename, sizeof(bs->filename), filename);
417 if (flags & BDRV_O_FILE) {
418 drv = find_protocol(filename);
420 drv = find_hdev_driver(filename);
422 drv = find_image_format(filename);
427 goto unlink_and_fail;
430 bs->opaque = qemu_mallocz(drv->instance_size);
431 /* Note: for compatibility, we open disk image files as RDWR, and
432 RDONLY as fallback */
433 if (!(flags & BDRV_O_FILE))
434 open_flags = BDRV_O_RDWR | (flags & BDRV_O_CACHE_MASK);
436 open_flags = flags & ~(BDRV_O_FILE | BDRV_O_SNAPSHOT);
437 ret = drv->bdrv_open(bs, filename, open_flags);
438 if ((ret == -EACCES || ret == -EPERM) && !(flags & BDRV_O_FILE)) {
439 ret = drv->bdrv_open(bs, filename, open_flags & ~BDRV_O_RDWR);
443 qemu_free(bs->opaque);
447 if (bs->is_temporary)
451 if (drv->bdrv_getlength) {
452 bs->total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
455 if (bs->is_temporary) {
459 if (bs->backing_file[0] != '\0') {
460 /* if there is a backing file, use it */
461 BlockDriver *back_drv = NULL;
462 bs->backing_hd = bdrv_new("");
463 path_combine(backing_filename, sizeof(backing_filename),
464 filename, bs->backing_file);
465 if (bs->backing_format[0] != '\0')
466 back_drv = bdrv_find_format(bs->backing_format);
467 ret = bdrv_open2(bs->backing_hd, backing_filename, open_flags,
475 if (!bdrv_key_required(bs)) {
476 /* call the change callback */
477 bs->media_changed = 1;
479 bs->change_cb(bs->change_opaque);
484 void bdrv_close(BlockDriverState *bs)
488 bdrv_delete(bs->backing_hd);
489 bs->drv->bdrv_close(bs);
490 qemu_free(bs->opaque);
492 if (bs->is_temporary) {
493 unlink(bs->filename);
499 /* call the change callback */
500 bs->media_changed = 1;
502 bs->change_cb(bs->change_opaque);
506 void bdrv_delete(BlockDriverState *bs)
508 BlockDriverState **pbs;
511 while (*pbs != bs && *pbs != NULL)
521 * Run consistency checks on an image
523 * Returns the number of errors or -errno when an internal error occurs
525 int bdrv_check(BlockDriverState *bs)
527 if (bs->drv->bdrv_check == NULL) {
531 return bs->drv->bdrv_check(bs);
534 /* commit COW file into the raw image */
535 int bdrv_commit(BlockDriverState *bs)
537 BlockDriver *drv = bs->drv;
538 int64_t i, total_sectors;
540 unsigned char sector[512];
549 if (!bs->backing_hd) {
553 total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
554 for (i = 0; i < total_sectors;) {
555 if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
556 for(j = 0; j < n; j++) {
557 if (bdrv_read(bs, i, sector, 1) != 0) {
561 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
571 if (drv->bdrv_make_empty)
572 return drv->bdrv_make_empty(bs);
577 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
582 if (!bdrv_is_inserted(bs))
588 len = bdrv_getlength(bs);
593 if ((offset > len) || (len - offset < size))
599 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
602 return bdrv_check_byte_request(bs, sector_num * 512, nb_sectors * 512);
605 /* return < 0 if error. See bdrv_write() for the return codes */
606 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
607 uint8_t *buf, int nb_sectors)
609 BlockDriver *drv = bs->drv;
613 if (bdrv_check_request(bs, sector_num, nb_sectors))
616 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
619 /* Return < 0 if error. Important errors are:
620 -EIO generic I/O error (may happen for all errors)
621 -ENOMEDIUM No media inserted.
622 -EINVAL Invalid sector number or nb_sectors
623 -EACCES Trying to write a read-only device
625 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
626 const uint8_t *buf, int nb_sectors)
628 BlockDriver *drv = bs->drv;
633 if (bdrv_check_request(bs, sector_num, nb_sectors))
636 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
639 int bdrv_pread(BlockDriverState *bs, int64_t offset,
640 void *buf, int count1)
642 uint8_t tmp_buf[SECTOR_SIZE];
643 int len, nb_sectors, count;
647 /* first read to align to sector start */
648 len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
651 sector_num = offset >> SECTOR_BITS;
653 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
655 memcpy(buf, tmp_buf + (offset & (SECTOR_SIZE - 1)), len);
663 /* read the sectors "in place" */
664 nb_sectors = count >> SECTOR_BITS;
665 if (nb_sectors > 0) {
666 if (bdrv_read(bs, sector_num, buf, nb_sectors) < 0)
668 sector_num += nb_sectors;
669 len = nb_sectors << SECTOR_BITS;
674 /* add data from the last sector */
676 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
678 memcpy(buf, tmp_buf, count);
683 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
684 const void *buf, int count1)
686 uint8_t tmp_buf[SECTOR_SIZE];
687 int len, nb_sectors, count;
691 /* first write to align to sector start */
692 len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
695 sector_num = offset >> SECTOR_BITS;
697 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
699 memcpy(tmp_buf + (offset & (SECTOR_SIZE - 1)), buf, len);
700 if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
709 /* write the sectors "in place" */
710 nb_sectors = count >> SECTOR_BITS;
711 if (nb_sectors > 0) {
712 if (bdrv_write(bs, sector_num, buf, nb_sectors) < 0)
714 sector_num += nb_sectors;
715 len = nb_sectors << SECTOR_BITS;
720 /* add data from the last sector */
722 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
724 memcpy(tmp_buf, buf, count);
725 if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
732 * Truncate file to 'offset' bytes (needed only for file protocols)
734 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
736 BlockDriver *drv = bs->drv;
739 if (!drv->bdrv_truncate)
741 return drv->bdrv_truncate(bs, offset);
745 * Length of a file in bytes. Return < 0 if error or unknown.
747 int64_t bdrv_getlength(BlockDriverState *bs)
749 BlockDriver *drv = bs->drv;
752 if (!drv->bdrv_getlength) {
754 return bs->total_sectors * SECTOR_SIZE;
756 return drv->bdrv_getlength(bs);
759 /* return 0 as number of sectors if no device present or error */
760 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
763 length = bdrv_getlength(bs);
767 length = length >> SECTOR_BITS;
768 *nb_sectors_ptr = length;
772 uint8_t boot_ind; /* 0x80 - active */
773 uint8_t head; /* starting head */
774 uint8_t sector; /* starting sector */
775 uint8_t cyl; /* starting cylinder */
776 uint8_t sys_ind; /* What partition type */
777 uint8_t end_head; /* end head */
778 uint8_t end_sector; /* end sector */
779 uint8_t end_cyl; /* end cylinder */
780 uint32_t start_sect; /* starting sector counting from 0 */
781 uint32_t nr_sects; /* nr of sectors in partition */
782 } __attribute__((packed));
784 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
785 static int guess_disk_lchs(BlockDriverState *bs,
786 int *pcylinders, int *pheads, int *psectors)
789 int ret, i, heads, sectors, cylinders;
794 bdrv_get_geometry(bs, &nb_sectors);
796 ret = bdrv_read(bs, 0, buf, 1);
799 /* test msdos magic */
800 if (buf[510] != 0x55 || buf[511] != 0xaa)
802 for(i = 0; i < 4; i++) {
803 p = ((struct partition *)(buf + 0x1be)) + i;
804 nr_sects = le32_to_cpu(p->nr_sects);
805 if (nr_sects && p->end_head) {
806 /* We make the assumption that the partition terminates on
807 a cylinder boundary */
808 heads = p->end_head + 1;
809 sectors = p->end_sector & 63;
812 cylinders = nb_sectors / (heads * sectors);
813 if (cylinders < 1 || cylinders > 16383)
817 *pcylinders = cylinders;
819 printf("guessed geometry: LCHS=%d %d %d\n",
820 cylinders, heads, sectors);
828 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
830 int translation, lba_detected = 0;
831 int cylinders, heads, secs;
834 /* if a geometry hint is available, use it */
835 bdrv_get_geometry(bs, &nb_sectors);
836 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
837 translation = bdrv_get_translation_hint(bs);
838 if (cylinders != 0) {
843 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
845 /* if heads > 16, it means that a BIOS LBA
846 translation was active, so the default
847 hardware geometry is OK */
849 goto default_geometry;
854 /* disable any translation to be in sync with
855 the logical geometry */
856 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
857 bdrv_set_translation_hint(bs,
858 BIOS_ATA_TRANSLATION_NONE);
863 /* if no geometry, use a standard physical disk geometry */
864 cylinders = nb_sectors / (16 * 63);
866 if (cylinders > 16383)
868 else if (cylinders < 2)
873 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
874 if ((*pcyls * *pheads) <= 131072) {
875 bdrv_set_translation_hint(bs,
876 BIOS_ATA_TRANSLATION_LARGE);
878 bdrv_set_translation_hint(bs,
879 BIOS_ATA_TRANSLATION_LBA);
883 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
887 void bdrv_set_geometry_hint(BlockDriverState *bs,
888 int cyls, int heads, int secs)
895 void bdrv_set_type_hint(BlockDriverState *bs, int type)
898 bs->removable = ((type == BDRV_TYPE_CDROM ||
899 type == BDRV_TYPE_FLOPPY));
902 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
904 bs->translation = translation;
907 void bdrv_get_geometry_hint(BlockDriverState *bs,
908 int *pcyls, int *pheads, int *psecs)
915 int bdrv_get_type_hint(BlockDriverState *bs)
920 int bdrv_get_translation_hint(BlockDriverState *bs)
922 return bs->translation;
925 int bdrv_is_removable(BlockDriverState *bs)
927 return bs->removable;
930 int bdrv_is_read_only(BlockDriverState *bs)
932 return bs->read_only;
935 int bdrv_is_sg(BlockDriverState *bs)
940 /* XXX: no longer used */
941 void bdrv_set_change_cb(BlockDriverState *bs,
942 void (*change_cb)(void *opaque), void *opaque)
944 bs->change_cb = change_cb;
945 bs->change_opaque = opaque;
948 int bdrv_is_encrypted(BlockDriverState *bs)
950 if (bs->backing_hd && bs->backing_hd->encrypted)
952 return bs->encrypted;
955 int bdrv_key_required(BlockDriverState *bs)
957 BlockDriverState *backing_hd = bs->backing_hd;
959 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
961 return (bs->encrypted && !bs->valid_key);
964 int bdrv_set_key(BlockDriverState *bs, const char *key)
967 if (bs->backing_hd && bs->backing_hd->encrypted) {
968 ret = bdrv_set_key(bs->backing_hd, key);
974 if (!bs->encrypted || !bs->drv || !bs->drv->bdrv_set_key)
976 ret = bs->drv->bdrv_set_key(bs, key);
979 } else if (!bs->valid_key) {
981 /* call the change callback now, we skipped it on open */
982 bs->media_changed = 1;
984 bs->change_cb(bs->change_opaque);
989 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
994 pstrcpy(buf, buf_size, bs->drv->format_name);
998 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
1003 for (drv = first_drv; drv != NULL; drv = drv->next) {
1004 it(opaque, drv->format_name);
1008 BlockDriverState *bdrv_find(const char *name)
1010 BlockDriverState *bs;
1012 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1013 if (!strcmp(name, bs->device_name))
1019 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1021 BlockDriverState *bs;
1023 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1028 const char *bdrv_get_device_name(BlockDriverState *bs)
1030 return bs->device_name;
1033 void bdrv_flush(BlockDriverState *bs)
1037 if (bs->drv->bdrv_flush)
1038 bs->drv->bdrv_flush(bs);
1040 bdrv_flush(bs->backing_hd);
1043 void bdrv_flush_all(void)
1045 BlockDriverState *bs;
1047 for (bs = bdrv_first; bs != NULL; bs = bs->next)
1048 if (bs->drv && !bdrv_is_read_only(bs) &&
1049 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs)))
1054 * Returns true iff the specified sector is present in the disk image. Drivers
1055 * not implementing the functionality are assumed to not support backing files,
1056 * hence all their sectors are reported as allocated.
1058 * 'pnum' is set to the number of sectors (including and immediately following
1059 * the specified sector) that are known to be in the same
1060 * allocated/unallocated state.
1062 * 'nb_sectors' is the max value 'pnum' should be set to.
1064 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1068 if (!bs->drv->bdrv_is_allocated) {
1069 if (sector_num >= bs->total_sectors) {
1073 n = bs->total_sectors - sector_num;
1074 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1077 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1080 void bdrv_info(Monitor *mon)
1082 BlockDriverState *bs;
1084 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1085 monitor_printf(mon, "%s:", bs->device_name);
1086 monitor_printf(mon, " type=");
1089 monitor_printf(mon, "hd");
1091 case BDRV_TYPE_CDROM:
1092 monitor_printf(mon, "cdrom");
1094 case BDRV_TYPE_FLOPPY:
1095 monitor_printf(mon, "floppy");
1098 monitor_printf(mon, " removable=%d", bs->removable);
1099 if (bs->removable) {
1100 monitor_printf(mon, " locked=%d", bs->locked);
1103 monitor_printf(mon, " file=");
1104 monitor_print_filename(mon, bs->filename);
1105 if (bs->backing_file[0] != '\0') {
1106 monitor_printf(mon, " backing_file=");
1107 monitor_print_filename(mon, bs->backing_file);
1109 monitor_printf(mon, " ro=%d", bs->read_only);
1110 monitor_printf(mon, " drv=%s", bs->drv->format_name);
1111 monitor_printf(mon, " encrypted=%d", bdrv_is_encrypted(bs));
1113 monitor_printf(mon, " [not inserted]");
1115 monitor_printf(mon, "\n");
1119 /* The "info blockstats" command. */
1120 void bdrv_info_stats(Monitor *mon)
1122 BlockDriverState *bs;
1124 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1125 monitor_printf(mon, "%s:"
1126 " rd_bytes=%" PRIu64
1127 " wr_bytes=%" PRIu64
1128 " rd_operations=%" PRIu64
1129 " wr_operations=%" PRIu64
1132 bs->rd_bytes, bs->wr_bytes,
1133 bs->rd_ops, bs->wr_ops);
1137 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1139 if (bs->backing_hd && bs->backing_hd->encrypted)
1140 return bs->backing_file;
1141 else if (bs->encrypted)
1142 return bs->filename;
1147 void bdrv_get_backing_filename(BlockDriverState *bs,
1148 char *filename, int filename_size)
1150 if (!bs->backing_hd) {
1151 pstrcpy(filename, filename_size, "");
1153 pstrcpy(filename, filename_size, bs->backing_file);
1157 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1158 const uint8_t *buf, int nb_sectors)
1160 BlockDriver *drv = bs->drv;
1163 if (!drv->bdrv_write_compressed)
1165 if (bdrv_check_request(bs, sector_num, nb_sectors))
1167 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1170 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1172 BlockDriver *drv = bs->drv;
1175 if (!drv->bdrv_get_info)
1177 memset(bdi, 0, sizeof(*bdi));
1178 return drv->bdrv_get_info(bs, bdi);
1181 int bdrv_put_buffer(BlockDriverState *bs, const uint8_t *buf, int64_t pos, int size)
1183 BlockDriver *drv = bs->drv;
1186 if (!drv->bdrv_put_buffer)
1188 return drv->bdrv_put_buffer(bs, buf, pos, size);
1191 int bdrv_get_buffer(BlockDriverState *bs, uint8_t *buf, int64_t pos, int size)
1193 BlockDriver *drv = bs->drv;
1196 if (!drv->bdrv_get_buffer)
1198 return drv->bdrv_get_buffer(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;
1374 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
1376 acb->pool->cancel(acb);
1380 /**************************************************************/
1381 /* async block device emulation */
1383 typedef struct BlockDriverAIOCBSync {
1384 BlockDriverAIOCB common;
1387 /* vector translation state */
1391 } BlockDriverAIOCBSync;
1393 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
1395 BlockDriverAIOCBSync *acb = (BlockDriverAIOCBSync *)blockacb;
1396 qemu_bh_cancel(acb->bh);
1397 qemu_aio_release(acb);
1400 static AIOPool bdrv_em_aio_pool = {
1401 .aiocb_size = sizeof(BlockDriverAIOCBSync),
1402 .cancel = bdrv_aio_cancel_em,
1405 static void bdrv_aio_bh_cb(void *opaque)
1407 BlockDriverAIOCBSync *acb = opaque;
1410 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
1411 qemu_vfree(acb->bounce);
1412 acb->common.cb(acb->common.opaque, acb->ret);
1414 qemu_aio_release(acb);
1417 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
1421 BlockDriverCompletionFunc *cb,
1426 BlockDriverAIOCBSync *acb;
1428 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
1429 acb->is_write = is_write;
1431 acb->bounce = qemu_blockalign(bs, qiov->size);
1434 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
1437 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
1438 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
1440 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
1443 qemu_bh_schedule(acb->bh);
1445 return &acb->common;
1448 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
1449 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1450 BlockDriverCompletionFunc *cb, void *opaque)
1452 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1455 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
1456 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1457 BlockDriverCompletionFunc *cb, void *opaque)
1459 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
1462 /**************************************************************/
1463 /* sync block device emulation */
1465 static void bdrv_rw_em_cb(void *opaque, int ret)
1467 *(int *)opaque = ret;
1470 #define NOT_DONE 0x7fffffff
1472 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
1473 uint8_t *buf, int nb_sectors)
1476 BlockDriverAIOCB *acb;
1480 async_ret = NOT_DONE;
1481 iov.iov_base = (void *)buf;
1482 iov.iov_len = nb_sectors * 512;
1483 qemu_iovec_init_external(&qiov, &iov, 1);
1484 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
1485 bdrv_rw_em_cb, &async_ret);
1489 while (async_ret == NOT_DONE) {
1496 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
1497 const uint8_t *buf, int nb_sectors)
1500 BlockDriverAIOCB *acb;
1504 async_ret = NOT_DONE;
1505 iov.iov_base = (void *)buf;
1506 iov.iov_len = nb_sectors * 512;
1507 qemu_iovec_init_external(&qiov, &iov, 1);
1508 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
1509 bdrv_rw_em_cb, &async_ret);
1512 while (async_ret == NOT_DONE) {
1518 void bdrv_init(void)
1520 module_call_init(MODULE_INIT_BLOCK);
1523 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
1524 BlockDriverCompletionFunc *cb, void *opaque)
1526 BlockDriverAIOCB *acb;
1528 if (pool->free_aiocb) {
1529 acb = pool->free_aiocb;
1530 pool->free_aiocb = acb->next;
1532 acb = qemu_mallocz(pool->aiocb_size);
1537 acb->opaque = opaque;
1541 void qemu_aio_release(void *p)
1543 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
1544 AIOPool *pool = acb->pool;
1545 acb->next = pool->free_aiocb;
1546 pool->free_aiocb = acb;
1549 /**************************************************************/
1550 /* removable device support */
1553 * Return TRUE if the media is present
1555 int bdrv_is_inserted(BlockDriverState *bs)
1557 BlockDriver *drv = bs->drv;
1561 if (!drv->bdrv_is_inserted)
1563 ret = drv->bdrv_is_inserted(bs);
1568 * Return TRUE if the media changed since the last call to this
1569 * function. It is currently only used for floppy disks
1571 int bdrv_media_changed(BlockDriverState *bs)
1573 BlockDriver *drv = bs->drv;
1576 if (!drv || !drv->bdrv_media_changed)
1579 ret = drv->bdrv_media_changed(bs);
1580 if (ret == -ENOTSUP)
1581 ret = bs->media_changed;
1582 bs->media_changed = 0;
1587 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
1589 void bdrv_eject(BlockDriverState *bs, int eject_flag)
1591 BlockDriver *drv = bs->drv;
1594 if (!drv || !drv->bdrv_eject) {
1597 ret = drv->bdrv_eject(bs, eject_flag);
1599 if (ret == -ENOTSUP) {
1605 int bdrv_is_locked(BlockDriverState *bs)
1611 * Lock or unlock the media (if it is locked, the user won't be able
1612 * to eject it manually).
1614 void bdrv_set_locked(BlockDriverState *bs, int locked)
1616 BlockDriver *drv = bs->drv;
1618 bs->locked = locked;
1619 if (drv && drv->bdrv_set_locked) {
1620 drv->bdrv_set_locked(bs, locked);
1624 /* needed for generic scsi interface */
1626 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1628 BlockDriver *drv = bs->drv;
1630 if (drv && drv->bdrv_ioctl)
1631 return drv->bdrv_ioctl(bs, req, buf);
1635 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
1636 unsigned long int req, void *buf,
1637 BlockDriverCompletionFunc *cb, void *opaque)
1639 BlockDriver *drv = bs->drv;
1641 if (drv && drv->bdrv_aio_ioctl)
1642 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
1646 void *qemu_blockalign(BlockDriverState *bs, size_t size)
1648 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);