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 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.
256 static BlockDriver *find_hdev_driver(const char *filename)
258 int score_max = 0, score;
259 BlockDriver *drv = NULL, *d;
261 for (d = first_drv; d; d = d->next) {
262 if (d->bdrv_probe_device) {
263 score = d->bdrv_probe_device(filename);
264 if (score > score_max) {
274 static BlockDriver *find_image_format(const char *filename)
276 int ret, score, score_max;
277 BlockDriver *drv1, *drv;
279 BlockDriverState *bs;
281 drv = find_protocol(filename);
282 /* no need to test disk image formats for vvfat */
283 if (drv && strcmp(drv->format_name, "vvfat") == 0)
286 ret = bdrv_file_open(&bs, filename, BDRV_O_RDONLY);
289 ret = bdrv_pread(bs, 0, buf, sizeof(buf));
296 for(drv1 = first_drv; drv1 != NULL; drv1 = drv1->next) {
297 if (drv1->bdrv_probe) {
298 score = drv1->bdrv_probe(buf, ret, filename);
299 if (score > score_max) {
308 int bdrv_file_open(BlockDriverState **pbs, const char *filename, int flags)
310 BlockDriverState *bs;
314 ret = bdrv_open2(bs, filename, flags | BDRV_O_FILE, NULL);
324 int bdrv_open(BlockDriverState *bs, const char *filename, int flags)
326 return bdrv_open2(bs, filename, flags, NULL);
329 int bdrv_open2(BlockDriverState *bs, const char *filename, int flags,
333 char tmp_filename[PATH_MAX];
334 char backing_filename[PATH_MAX];
337 bs->is_temporary = 0;
340 /* buffer_alignment defaulted to 512, drivers can change this value */
341 bs->buffer_alignment = 512;
343 if (flags & BDRV_O_SNAPSHOT) {
344 BlockDriverState *bs1;
347 BlockDriver *bdrv_qcow2;
348 QEMUOptionParameter *options;
350 /* if snapshot, we create a temporary backing file and open it
351 instead of opening 'filename' directly */
353 /* if there is a backing file, use it */
355 ret = bdrv_open2(bs1, filename, 0, drv);
360 total_size = bdrv_getlength(bs1) >> SECTOR_BITS;
362 if (bs1->drv && bs1->drv->protocol_name)
367 get_tmp_filename(tmp_filename, sizeof(tmp_filename));
369 /* Real path is meaningless for protocols */
371 snprintf(backing_filename, sizeof(backing_filename),
374 realpath(filename, backing_filename);
376 bdrv_qcow2 = bdrv_find_format("qcow2");
377 options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);
379 set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size * 512);
380 set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);
382 set_option_parameter(options, BLOCK_OPT_BACKING_FMT,
386 ret = bdrv_create(bdrv_qcow2, tmp_filename, options);
391 filename = tmp_filename;
393 bs->is_temporary = 1;
396 pstrcpy(bs->filename, sizeof(bs->filename), filename);
397 if (flags & BDRV_O_FILE) {
398 drv = find_protocol(filename);
400 drv = find_hdev_driver(filename);
402 drv = find_image_format(filename);
407 goto unlink_and_fail;
410 bs->opaque = qemu_mallocz(drv->instance_size);
411 /* Note: for compatibility, we open disk image files as RDWR, and
412 RDONLY as fallback */
413 if (!(flags & BDRV_O_FILE))
414 open_flags = BDRV_O_RDWR |
415 (flags & (BDRV_O_CACHE_MASK|BDRV_O_NATIVE_AIO));
417 open_flags = flags & ~(BDRV_O_FILE | BDRV_O_SNAPSHOT);
418 ret = drv->bdrv_open(bs, filename, open_flags);
419 if ((ret == -EACCES || ret == -EPERM) && !(flags & BDRV_O_FILE)) {
420 ret = drv->bdrv_open(bs, filename, open_flags & ~BDRV_O_RDWR);
424 qemu_free(bs->opaque);
428 if (bs->is_temporary)
432 if (drv->bdrv_getlength) {
433 bs->total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
436 if (bs->is_temporary) {
440 if (bs->backing_file[0] != '\0') {
441 /* if there is a backing file, use it */
442 BlockDriver *back_drv = NULL;
443 bs->backing_hd = bdrv_new("");
444 path_combine(backing_filename, sizeof(backing_filename),
445 filename, bs->backing_file);
446 if (bs->backing_format[0] != '\0')
447 back_drv = bdrv_find_format(bs->backing_format);
448 ret = bdrv_open2(bs->backing_hd, backing_filename, open_flags,
456 if (!bdrv_key_required(bs)) {
457 /* call the change callback */
458 bs->media_changed = 1;
460 bs->change_cb(bs->change_opaque);
465 void bdrv_close(BlockDriverState *bs)
469 bdrv_delete(bs->backing_hd);
470 bs->drv->bdrv_close(bs);
471 qemu_free(bs->opaque);
473 if (bs->is_temporary) {
474 unlink(bs->filename);
480 /* call the change callback */
481 bs->media_changed = 1;
483 bs->change_cb(bs->change_opaque);
487 void bdrv_delete(BlockDriverState *bs)
489 BlockDriverState **pbs;
492 while (*pbs != bs && *pbs != NULL)
502 * Run consistency checks on an image
504 * Returns the number of errors or -errno when an internal error occurs
506 int bdrv_check(BlockDriverState *bs)
508 if (bs->drv->bdrv_check == NULL) {
512 return bs->drv->bdrv_check(bs);
515 /* commit COW file into the raw image */
516 int bdrv_commit(BlockDriverState *bs)
518 BlockDriver *drv = bs->drv;
519 int64_t i, total_sectors;
521 unsigned char sector[512];
530 if (!bs->backing_hd) {
534 total_sectors = bdrv_getlength(bs) >> SECTOR_BITS;
535 for (i = 0; i < total_sectors;) {
536 if (drv->bdrv_is_allocated(bs, i, 65536, &n)) {
537 for(j = 0; j < n; j++) {
538 if (bdrv_read(bs, i, sector, 1) != 0) {
542 if (bdrv_write(bs->backing_hd, i, sector, 1) != 0) {
552 if (drv->bdrv_make_empty)
553 return drv->bdrv_make_empty(bs);
558 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
563 if (!bdrv_is_inserted(bs))
569 len = bdrv_getlength(bs);
574 if ((offset > len) || (len - offset < size))
580 static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
583 return bdrv_check_byte_request(bs, sector_num * 512, nb_sectors * 512);
586 /* return < 0 if error. See bdrv_write() for the return codes */
587 int bdrv_read(BlockDriverState *bs, int64_t sector_num,
588 uint8_t *buf, int nb_sectors)
590 BlockDriver *drv = bs->drv;
594 if (bdrv_check_request(bs, sector_num, nb_sectors))
597 return drv->bdrv_read(bs, sector_num, buf, nb_sectors);
600 /* Return < 0 if error. Important errors are:
601 -EIO generic I/O error (may happen for all errors)
602 -ENOMEDIUM No media inserted.
603 -EINVAL Invalid sector number or nb_sectors
604 -EACCES Trying to write a read-only device
606 int bdrv_write(BlockDriverState *bs, int64_t sector_num,
607 const uint8_t *buf, int nb_sectors)
609 BlockDriver *drv = bs->drv;
614 if (bdrv_check_request(bs, sector_num, nb_sectors))
617 return drv->bdrv_write(bs, sector_num, buf, nb_sectors);
620 int bdrv_pread(BlockDriverState *bs, int64_t offset,
621 void *buf, int count1)
623 uint8_t tmp_buf[SECTOR_SIZE];
624 int len, nb_sectors, count;
628 /* first read to align to sector start */
629 len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
632 sector_num = offset >> SECTOR_BITS;
634 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
636 memcpy(buf, tmp_buf + (offset & (SECTOR_SIZE - 1)), len);
644 /* read the sectors "in place" */
645 nb_sectors = count >> SECTOR_BITS;
646 if (nb_sectors > 0) {
647 if (bdrv_read(bs, sector_num, buf, nb_sectors) < 0)
649 sector_num += nb_sectors;
650 len = nb_sectors << SECTOR_BITS;
655 /* add data from the last sector */
657 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
659 memcpy(buf, tmp_buf, count);
664 int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
665 const void *buf, int count1)
667 uint8_t tmp_buf[SECTOR_SIZE];
668 int len, nb_sectors, count;
672 /* first write to align to sector start */
673 len = (SECTOR_SIZE - offset) & (SECTOR_SIZE - 1);
676 sector_num = offset >> SECTOR_BITS;
678 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
680 memcpy(tmp_buf + (offset & (SECTOR_SIZE - 1)), buf, len);
681 if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
690 /* write the sectors "in place" */
691 nb_sectors = count >> SECTOR_BITS;
692 if (nb_sectors > 0) {
693 if (bdrv_write(bs, sector_num, buf, nb_sectors) < 0)
695 sector_num += nb_sectors;
696 len = nb_sectors << SECTOR_BITS;
701 /* add data from the last sector */
703 if (bdrv_read(bs, sector_num, tmp_buf, 1) < 0)
705 memcpy(tmp_buf, buf, count);
706 if (bdrv_write(bs, sector_num, tmp_buf, 1) < 0)
713 * Truncate file to 'offset' bytes (needed only for file protocols)
715 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
717 BlockDriver *drv = bs->drv;
720 if (!drv->bdrv_truncate)
722 return drv->bdrv_truncate(bs, offset);
726 * Length of a file in bytes. Return < 0 if error or unknown.
728 int64_t bdrv_getlength(BlockDriverState *bs)
730 BlockDriver *drv = bs->drv;
733 if (!drv->bdrv_getlength) {
735 return bs->total_sectors * SECTOR_SIZE;
737 return drv->bdrv_getlength(bs);
740 /* return 0 as number of sectors if no device present or error */
741 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
744 length = bdrv_getlength(bs);
748 length = length >> SECTOR_BITS;
749 *nb_sectors_ptr = length;
753 uint8_t boot_ind; /* 0x80 - active */
754 uint8_t head; /* starting head */
755 uint8_t sector; /* starting sector */
756 uint8_t cyl; /* starting cylinder */
757 uint8_t sys_ind; /* What partition type */
758 uint8_t end_head; /* end head */
759 uint8_t end_sector; /* end sector */
760 uint8_t end_cyl; /* end cylinder */
761 uint32_t start_sect; /* starting sector counting from 0 */
762 uint32_t nr_sects; /* nr of sectors in partition */
763 } __attribute__((packed));
765 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
766 static int guess_disk_lchs(BlockDriverState *bs,
767 int *pcylinders, int *pheads, int *psectors)
770 int ret, i, heads, sectors, cylinders;
775 bdrv_get_geometry(bs, &nb_sectors);
777 ret = bdrv_read(bs, 0, buf, 1);
780 /* test msdos magic */
781 if (buf[510] != 0x55 || buf[511] != 0xaa)
783 for(i = 0; i < 4; i++) {
784 p = ((struct partition *)(buf + 0x1be)) + i;
785 nr_sects = le32_to_cpu(p->nr_sects);
786 if (nr_sects && p->end_head) {
787 /* We make the assumption that the partition terminates on
788 a cylinder boundary */
789 heads = p->end_head + 1;
790 sectors = p->end_sector & 63;
793 cylinders = nb_sectors / (heads * sectors);
794 if (cylinders < 1 || cylinders > 16383)
798 *pcylinders = cylinders;
800 printf("guessed geometry: LCHS=%d %d %d\n",
801 cylinders, heads, sectors);
809 void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)
811 int translation, lba_detected = 0;
812 int cylinders, heads, secs;
815 /* if a geometry hint is available, use it */
816 bdrv_get_geometry(bs, &nb_sectors);
817 bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);
818 translation = bdrv_get_translation_hint(bs);
819 if (cylinders != 0) {
824 if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {
826 /* if heads > 16, it means that a BIOS LBA
827 translation was active, so the default
828 hardware geometry is OK */
830 goto default_geometry;
835 /* disable any translation to be in sync with
836 the logical geometry */
837 if (translation == BIOS_ATA_TRANSLATION_AUTO) {
838 bdrv_set_translation_hint(bs,
839 BIOS_ATA_TRANSLATION_NONE);
844 /* if no geometry, use a standard physical disk geometry */
845 cylinders = nb_sectors / (16 * 63);
847 if (cylinders > 16383)
849 else if (cylinders < 2)
854 if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {
855 if ((*pcyls * *pheads) <= 131072) {
856 bdrv_set_translation_hint(bs,
857 BIOS_ATA_TRANSLATION_LARGE);
859 bdrv_set_translation_hint(bs,
860 BIOS_ATA_TRANSLATION_LBA);
864 bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);
868 void bdrv_set_geometry_hint(BlockDriverState *bs,
869 int cyls, int heads, int secs)
876 void bdrv_set_type_hint(BlockDriverState *bs, int type)
879 bs->removable = ((type == BDRV_TYPE_CDROM ||
880 type == BDRV_TYPE_FLOPPY));
883 void bdrv_set_translation_hint(BlockDriverState *bs, int translation)
885 bs->translation = translation;
888 void bdrv_get_geometry_hint(BlockDriverState *bs,
889 int *pcyls, int *pheads, int *psecs)
896 int bdrv_get_type_hint(BlockDriverState *bs)
901 int bdrv_get_translation_hint(BlockDriverState *bs)
903 return bs->translation;
906 int bdrv_is_removable(BlockDriverState *bs)
908 return bs->removable;
911 int bdrv_is_read_only(BlockDriverState *bs)
913 return bs->read_only;
916 int bdrv_is_sg(BlockDriverState *bs)
921 /* XXX: no longer used */
922 void bdrv_set_change_cb(BlockDriverState *bs,
923 void (*change_cb)(void *opaque), void *opaque)
925 bs->change_cb = change_cb;
926 bs->change_opaque = opaque;
929 int bdrv_is_encrypted(BlockDriverState *bs)
931 if (bs->backing_hd && bs->backing_hd->encrypted)
933 return bs->encrypted;
936 int bdrv_key_required(BlockDriverState *bs)
938 BlockDriverState *backing_hd = bs->backing_hd;
940 if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
942 return (bs->encrypted && !bs->valid_key);
945 int bdrv_set_key(BlockDriverState *bs, const char *key)
948 if (bs->backing_hd && bs->backing_hd->encrypted) {
949 ret = bdrv_set_key(bs->backing_hd, key);
955 if (!bs->encrypted || !bs->drv || !bs->drv->bdrv_set_key)
957 ret = bs->drv->bdrv_set_key(bs, key);
960 } else if (!bs->valid_key) {
962 /* call the change callback now, we skipped it on open */
963 bs->media_changed = 1;
965 bs->change_cb(bs->change_opaque);
970 void bdrv_get_format(BlockDriverState *bs, char *buf, int buf_size)
975 pstrcpy(buf, buf_size, bs->drv->format_name);
979 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
984 for (drv = first_drv; drv != NULL; drv = drv->next) {
985 it(opaque, drv->format_name);
989 BlockDriverState *bdrv_find(const char *name)
991 BlockDriverState *bs;
993 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
994 if (!strcmp(name, bs->device_name))
1000 void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
1002 BlockDriverState *bs;
1004 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1009 const char *bdrv_get_device_name(BlockDriverState *bs)
1011 return bs->device_name;
1014 void bdrv_flush(BlockDriverState *bs)
1018 if (bs->drv->bdrv_flush)
1019 bs->drv->bdrv_flush(bs);
1021 bdrv_flush(bs->backing_hd);
1024 void bdrv_flush_all(void)
1026 BlockDriverState *bs;
1028 for (bs = bdrv_first; bs != NULL; bs = bs->next)
1029 if (bs->drv && !bdrv_is_read_only(bs) &&
1030 (!bdrv_is_removable(bs) || bdrv_is_inserted(bs)))
1035 * Returns true iff the specified sector is present in the disk image. Drivers
1036 * not implementing the functionality are assumed to not support backing files,
1037 * hence all their sectors are reported as allocated.
1039 * 'pnum' is set to the number of sectors (including and immediately following
1040 * the specified sector) that are known to be in the same
1041 * allocated/unallocated state.
1043 * 'nb_sectors' is the max value 'pnum' should be set to.
1045 int bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num, int nb_sectors,
1049 if (!bs->drv->bdrv_is_allocated) {
1050 if (sector_num >= bs->total_sectors) {
1054 n = bs->total_sectors - sector_num;
1055 *pnum = (n < nb_sectors) ? (n) : (nb_sectors);
1058 return bs->drv->bdrv_is_allocated(bs, sector_num, nb_sectors, pnum);
1061 void bdrv_info(Monitor *mon)
1063 BlockDriverState *bs;
1065 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1066 monitor_printf(mon, "%s:", bs->device_name);
1067 monitor_printf(mon, " type=");
1070 monitor_printf(mon, "hd");
1072 case BDRV_TYPE_CDROM:
1073 monitor_printf(mon, "cdrom");
1075 case BDRV_TYPE_FLOPPY:
1076 monitor_printf(mon, "floppy");
1079 monitor_printf(mon, " removable=%d", bs->removable);
1080 if (bs->removable) {
1081 monitor_printf(mon, " locked=%d", bs->locked);
1084 monitor_printf(mon, " file=");
1085 monitor_print_filename(mon, bs->filename);
1086 if (bs->backing_file[0] != '\0') {
1087 monitor_printf(mon, " backing_file=");
1088 monitor_print_filename(mon, bs->backing_file);
1090 monitor_printf(mon, " ro=%d", bs->read_only);
1091 monitor_printf(mon, " drv=%s", bs->drv->format_name);
1092 monitor_printf(mon, " encrypted=%d", bdrv_is_encrypted(bs));
1094 monitor_printf(mon, " [not inserted]");
1096 monitor_printf(mon, "\n");
1100 /* The "info blockstats" command. */
1101 void bdrv_info_stats(Monitor *mon)
1103 BlockDriverState *bs;
1105 for (bs = bdrv_first; bs != NULL; bs = bs->next) {
1106 monitor_printf(mon, "%s:"
1107 " rd_bytes=%" PRIu64
1108 " wr_bytes=%" PRIu64
1109 " rd_operations=%" PRIu64
1110 " wr_operations=%" PRIu64
1113 bs->rd_bytes, bs->wr_bytes,
1114 bs->rd_ops, bs->wr_ops);
1118 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
1120 if (bs->backing_hd && bs->backing_hd->encrypted)
1121 return bs->backing_file;
1122 else if (bs->encrypted)
1123 return bs->filename;
1128 void bdrv_get_backing_filename(BlockDriverState *bs,
1129 char *filename, int filename_size)
1131 if (!bs->backing_hd) {
1132 pstrcpy(filename, filename_size, "");
1134 pstrcpy(filename, filename_size, bs->backing_file);
1138 int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
1139 const uint8_t *buf, int nb_sectors)
1141 BlockDriver *drv = bs->drv;
1144 if (!drv->bdrv_write_compressed)
1146 if (bdrv_check_request(bs, sector_num, nb_sectors))
1148 return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
1151 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1153 BlockDriver *drv = bs->drv;
1156 if (!drv->bdrv_get_info)
1158 memset(bdi, 0, sizeof(*bdi));
1159 return drv->bdrv_get_info(bs, bdi);
1162 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1163 int64_t pos, int size)
1165 BlockDriver *drv = bs->drv;
1168 if (!drv->bdrv_save_vmstate)
1170 return drv->bdrv_save_vmstate(bs, buf, pos, size);
1173 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1174 int64_t pos, int size)
1176 BlockDriver *drv = bs->drv;
1179 if (!drv->bdrv_load_vmstate)
1181 return drv->bdrv_load_vmstate(bs, buf, pos, size);
1184 /**************************************************************/
1185 /* handling of snapshots */
1187 int bdrv_snapshot_create(BlockDriverState *bs,
1188 QEMUSnapshotInfo *sn_info)
1190 BlockDriver *drv = bs->drv;
1193 if (!drv->bdrv_snapshot_create)
1195 return drv->bdrv_snapshot_create(bs, sn_info);
1198 int bdrv_snapshot_goto(BlockDriverState *bs,
1199 const char *snapshot_id)
1201 BlockDriver *drv = bs->drv;
1204 if (!drv->bdrv_snapshot_goto)
1206 return drv->bdrv_snapshot_goto(bs, snapshot_id);
1209 int bdrv_snapshot_delete(BlockDriverState *bs, const char *snapshot_id)
1211 BlockDriver *drv = bs->drv;
1214 if (!drv->bdrv_snapshot_delete)
1216 return drv->bdrv_snapshot_delete(bs, snapshot_id);
1219 int bdrv_snapshot_list(BlockDriverState *bs,
1220 QEMUSnapshotInfo **psn_info)
1222 BlockDriver *drv = bs->drv;
1225 if (!drv->bdrv_snapshot_list)
1227 return drv->bdrv_snapshot_list(bs, psn_info);
1230 #define NB_SUFFIXES 4
1232 char *get_human_readable_size(char *buf, int buf_size, int64_t size)
1234 static const char suffixes[NB_SUFFIXES] = "KMGT";
1239 snprintf(buf, buf_size, "%" PRId64, size);
1242 for(i = 0; i < NB_SUFFIXES; i++) {
1243 if (size < (10 * base)) {
1244 snprintf(buf, buf_size, "%0.1f%c",
1245 (double)size / base,
1248 } else if (size < (1000 * base) || i == (NB_SUFFIXES - 1)) {
1249 snprintf(buf, buf_size, "%" PRId64 "%c",
1250 ((size + (base >> 1)) / base),
1260 char *bdrv_snapshot_dump(char *buf, int buf_size, QEMUSnapshotInfo *sn)
1262 char buf1[128], date_buf[128], clock_buf[128];
1272 snprintf(buf, buf_size,
1273 "%-10s%-20s%7s%20s%15s",
1274 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1278 ptm = localtime(&ti);
1279 strftime(date_buf, sizeof(date_buf),
1280 "%Y-%m-%d %H:%M:%S", ptm);
1282 localtime_r(&ti, &tm);
1283 strftime(date_buf, sizeof(date_buf),
1284 "%Y-%m-%d %H:%M:%S", &tm);
1286 secs = sn->vm_clock_nsec / 1000000000;
1287 snprintf(clock_buf, sizeof(clock_buf),
1288 "%02d:%02d:%02d.%03d",
1290 (int)((secs / 60) % 60),
1292 (int)((sn->vm_clock_nsec / 1000000) % 1000));
1293 snprintf(buf, buf_size,
1294 "%-10s%-20s%7s%20s%15s",
1295 sn->id_str, sn->name,
1296 get_human_readable_size(buf1, sizeof(buf1), sn->vm_state_size),
1304 /**************************************************************/
1307 BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
1308 QEMUIOVector *qiov, int nb_sectors,
1309 BlockDriverCompletionFunc *cb, void *opaque)
1311 BlockDriver *drv = bs->drv;
1312 BlockDriverAIOCB *ret;
1316 if (bdrv_check_request(bs, sector_num, nb_sectors))
1319 ret = drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
1323 /* Update stats even though technically transfer has not happened. */
1324 bs->rd_bytes += (unsigned) nb_sectors * SECTOR_SIZE;
1331 BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
1332 QEMUIOVector *qiov, int nb_sectors,
1333 BlockDriverCompletionFunc *cb, void *opaque)
1335 BlockDriver *drv = bs->drv;
1336 BlockDriverAIOCB *ret;
1342 if (bdrv_check_request(bs, sector_num, nb_sectors))
1345 ret = drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
1349 /* Update stats even though technically transfer has not happened. */
1350 bs->wr_bytes += (unsigned) nb_sectors * SECTOR_SIZE;
1358 typedef struct MultiwriteCB {
1363 BlockDriverCompletionFunc *cb;
1365 QEMUIOVector *free_qiov;
1370 static void multiwrite_user_cb(MultiwriteCB *mcb)
1374 for (i = 0; i < mcb->num_callbacks; i++) {
1375 mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
1376 qemu_free(mcb->callbacks[i].free_qiov);
1377 qemu_free(mcb->callbacks[i].free_buf);
1381 static void multiwrite_cb(void *opaque, int ret)
1383 MultiwriteCB *mcb = opaque;
1387 multiwrite_user_cb(mcb);
1390 mcb->num_requests--;
1391 if (mcb->num_requests == 0) {
1392 if (mcb->error == 0) {
1393 multiwrite_user_cb(mcb);
1399 static int multiwrite_req_compare(const void *a, const void *b)
1401 return (((BlockRequest*) a)->sector - ((BlockRequest*) b)->sector);
1405 * Takes a bunch of requests and tries to merge them. Returns the number of
1406 * requests that remain after merging.
1408 static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
1409 int num_reqs, MultiwriteCB *mcb)
1413 // Sort requests by start sector
1414 qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
1416 // Check if adjacent requests touch the same clusters. If so, combine them,
1417 // filling up gaps with zero sectors.
1419 for (i = 1; i < num_reqs; i++) {
1421 int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
1423 // This handles the cases that are valid for all block drivers, namely
1424 // exactly sequential writes and overlapping writes.
1425 if (reqs[i].sector <= oldreq_last) {
1429 // The block driver may decide that it makes sense to combine requests
1430 // even if there is a gap of some sectors between them. In this case,
1431 // the gap is filled with zeros (therefore only applicable for yet
1432 // unused space in format like qcow2).
1433 if (!merge && bs->drv->bdrv_merge_requests) {
1434 merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);
1439 QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));
1440 qemu_iovec_init(qiov,
1441 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
1443 // Add the first request to the merged one. If the requests are
1444 // overlapping, drop the last sectors of the first request.
1445 size = (reqs[i].sector - reqs[outidx].sector) << 9;
1446 qemu_iovec_concat(qiov, reqs[outidx].qiov, size);
1448 // We might need to add some zeros between the two requests
1449 if (reqs[i].sector > oldreq_last) {
1450 size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;
1451 uint8_t *buf = qemu_blockalign(bs, zero_bytes);
1452 memset(buf, 0, zero_bytes);
1453 qemu_iovec_add(qiov, buf, zero_bytes);
1454 mcb->callbacks[i].free_buf = buf;
1457 // Add the second request
1458 qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);
1460 reqs[outidx].nb_sectors += reqs[i].nb_sectors;
1461 reqs[outidx].qiov = qiov;
1463 mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
1466 reqs[outidx].sector = reqs[i].sector;
1467 reqs[outidx].nb_sectors = reqs[i].nb_sectors;
1468 reqs[outidx].qiov = reqs[i].qiov;
1476 * Submit multiple AIO write requests at once.
1478 * On success, the function returns 0 and all requests in the reqs array have
1479 * been submitted. In error case this function returns -1, and any of the
1480 * requests may or may not be submitted yet. In particular, this means that the
1481 * callback will be called for some of the requests, for others it won't. The
1482 * caller must check the error field of the BlockRequest to wait for the right
1483 * callbacks (if error != 0, no callback will be called).
1485 * The implementation may modify the contents of the reqs array, e.g. to merge
1486 * requests. However, the fields opaque and error are left unmodified as they
1487 * are used to signal failure for a single request to the caller.
1489 int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
1491 BlockDriverAIOCB *acb;
1495 if (num_reqs == 0) {
1499 // Create MultiwriteCB structure
1500 mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
1501 mcb->num_requests = 0;
1502 mcb->num_callbacks = num_reqs;
1504 for (i = 0; i < num_reqs; i++) {
1505 mcb->callbacks[i].cb = reqs[i].cb;
1506 mcb->callbacks[i].opaque = reqs[i].opaque;
1509 // Check for mergable requests
1510 num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
1512 // Run the aio requests
1513 for (i = 0; i < num_reqs; i++) {
1514 acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,
1515 reqs[i].nb_sectors, multiwrite_cb, mcb);
1518 // We can only fail the whole thing if no request has been
1519 // submitted yet. Otherwise we'll wait for the submitted AIOs to
1520 // complete and report the error in the callback.
1521 if (mcb->num_requests == 0) {
1522 reqs[i].error = EIO;
1529 mcb->num_requests++;
1540 void bdrv_aio_cancel(BlockDriverAIOCB *acb)
1542 acb->pool->cancel(acb);
1546 /**************************************************************/
1547 /* async block device emulation */
1549 typedef struct BlockDriverAIOCBSync {
1550 BlockDriverAIOCB common;
1553 /* vector translation state */
1557 } BlockDriverAIOCBSync;
1559 static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
1561 BlockDriverAIOCBSync *acb = (BlockDriverAIOCBSync *)blockacb;
1562 qemu_bh_delete(acb->bh);
1564 qemu_aio_release(acb);
1567 static AIOPool bdrv_em_aio_pool = {
1568 .aiocb_size = sizeof(BlockDriverAIOCBSync),
1569 .cancel = bdrv_aio_cancel_em,
1572 static void bdrv_aio_bh_cb(void *opaque)
1574 BlockDriverAIOCBSync *acb = opaque;
1577 qemu_iovec_from_buffer(acb->qiov, acb->bounce, acb->qiov->size);
1578 qemu_vfree(acb->bounce);
1579 acb->common.cb(acb->common.opaque, acb->ret);
1580 qemu_bh_delete(acb->bh);
1582 qemu_aio_release(acb);
1585 static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
1589 BlockDriverCompletionFunc *cb,
1594 BlockDriverAIOCBSync *acb;
1596 acb = qemu_aio_get(&bdrv_em_aio_pool, bs, cb, opaque);
1597 acb->is_write = is_write;
1599 acb->bounce = qemu_blockalign(bs, qiov->size);
1602 acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
1605 qemu_iovec_to_buffer(acb->qiov, acb->bounce);
1606 acb->ret = bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
1608 acb->ret = bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
1611 qemu_bh_schedule(acb->bh);
1613 return &acb->common;
1616 static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
1617 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1618 BlockDriverCompletionFunc *cb, void *opaque)
1620 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
1623 static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
1624 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
1625 BlockDriverCompletionFunc *cb, void *opaque)
1627 return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
1630 /**************************************************************/
1631 /* sync block device emulation */
1633 static void bdrv_rw_em_cb(void *opaque, int ret)
1635 *(int *)opaque = ret;
1638 #define NOT_DONE 0x7fffffff
1640 static int bdrv_read_em(BlockDriverState *bs, int64_t sector_num,
1641 uint8_t *buf, int nb_sectors)
1644 BlockDriverAIOCB *acb;
1648 async_ret = NOT_DONE;
1649 iov.iov_base = (void *)buf;
1650 iov.iov_len = nb_sectors * 512;
1651 qemu_iovec_init_external(&qiov, &iov, 1);
1652 acb = bdrv_aio_readv(bs, sector_num, &qiov, nb_sectors,
1653 bdrv_rw_em_cb, &async_ret);
1657 while (async_ret == NOT_DONE) {
1664 static int bdrv_write_em(BlockDriverState *bs, int64_t sector_num,
1665 const uint8_t *buf, int nb_sectors)
1668 BlockDriverAIOCB *acb;
1672 async_ret = NOT_DONE;
1673 iov.iov_base = (void *)buf;
1674 iov.iov_len = nb_sectors * 512;
1675 qemu_iovec_init_external(&qiov, &iov, 1);
1676 acb = bdrv_aio_writev(bs, sector_num, &qiov, nb_sectors,
1677 bdrv_rw_em_cb, &async_ret);
1680 while (async_ret == NOT_DONE) {
1686 void bdrv_init(void)
1688 module_call_init(MODULE_INIT_BLOCK);
1691 void *qemu_aio_get(AIOPool *pool, BlockDriverState *bs,
1692 BlockDriverCompletionFunc *cb, void *opaque)
1694 BlockDriverAIOCB *acb;
1696 if (pool->free_aiocb) {
1697 acb = pool->free_aiocb;
1698 pool->free_aiocb = acb->next;
1700 acb = qemu_mallocz(pool->aiocb_size);
1705 acb->opaque = opaque;
1709 void qemu_aio_release(void *p)
1711 BlockDriverAIOCB *acb = (BlockDriverAIOCB *)p;
1712 AIOPool *pool = acb->pool;
1713 acb->next = pool->free_aiocb;
1714 pool->free_aiocb = acb;
1717 /**************************************************************/
1718 /* removable device support */
1721 * Return TRUE if the media is present
1723 int bdrv_is_inserted(BlockDriverState *bs)
1725 BlockDriver *drv = bs->drv;
1729 if (!drv->bdrv_is_inserted)
1731 ret = drv->bdrv_is_inserted(bs);
1736 * Return TRUE if the media changed since the last call to this
1737 * function. It is currently only used for floppy disks
1739 int bdrv_media_changed(BlockDriverState *bs)
1741 BlockDriver *drv = bs->drv;
1744 if (!drv || !drv->bdrv_media_changed)
1747 ret = drv->bdrv_media_changed(bs);
1748 if (ret == -ENOTSUP)
1749 ret = bs->media_changed;
1750 bs->media_changed = 0;
1755 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
1757 int bdrv_eject(BlockDriverState *bs, int eject_flag)
1759 BlockDriver *drv = bs->drv;
1766 if (!drv || !drv->bdrv_eject) {
1769 ret = drv->bdrv_eject(bs, eject_flag);
1771 if (ret == -ENOTSUP) {
1780 int bdrv_is_locked(BlockDriverState *bs)
1786 * Lock or unlock the media (if it is locked, the user won't be able
1787 * to eject it manually).
1789 void bdrv_set_locked(BlockDriverState *bs, int locked)
1791 BlockDriver *drv = bs->drv;
1793 bs->locked = locked;
1794 if (drv && drv->bdrv_set_locked) {
1795 drv->bdrv_set_locked(bs, locked);
1799 /* needed for generic scsi interface */
1801 int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
1803 BlockDriver *drv = bs->drv;
1805 if (drv && drv->bdrv_ioctl)
1806 return drv->bdrv_ioctl(bs, req, buf);
1810 BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
1811 unsigned long int req, void *buf,
1812 BlockDriverCompletionFunc *cb, void *opaque)
1814 BlockDriver *drv = bs->drv;
1816 if (drv && drv->bdrv_aio_ioctl)
1817 return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
1821 void *qemu_blockalign(BlockDriverState *bs, size_t size)
1823 return qemu_memalign((bs && bs->buffer_alignment) ? bs->buffer_alignment : 512, size);