2 * QEMU System Emulator block driver
4 * Copyright (c) 2003 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 #include "config-host.h"
25 #include "qemu-common.h"
27 #include "block_int.h"
29 #include "qemu-objects.h"
32 #include <sys/types.h>
34 #include <sys/ioctl.h>
35 #include <sys/queue.h>
45 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
46 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
47 BlockDriverCompletionFunc
*cb
, void *opaque
);
48 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
49 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
50 BlockDriverCompletionFunc
*cb
, void *opaque
);
51 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
52 BlockDriverCompletionFunc
*cb
, void *opaque
);
53 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
54 uint8_t *buf
, int nb_sectors
);
55 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
56 const uint8_t *buf
, int nb_sectors
);
58 static QTAILQ_HEAD(, BlockDriverState
) bdrv_states
=
59 QTAILQ_HEAD_INITIALIZER(bdrv_states
);
61 static QLIST_HEAD(, BlockDriver
) bdrv_drivers
=
62 QLIST_HEAD_INITIALIZER(bdrv_drivers
);
64 /* If non-zero, use only whitelisted block drivers */
65 static int use_bdrv_whitelist
;
67 int path_is_absolute(const char *path
)
71 /* specific case for names like: "\\.\d:" */
72 if (*path
== '/' || *path
== '\\')
75 p
= strchr(path
, ':');
81 return (*p
== '/' || *p
== '\\');
87 /* if filename is absolute, just copy it to dest. Otherwise, build a
88 path to it by considering it is relative to base_path. URL are
90 void path_combine(char *dest
, int dest_size
,
91 const char *base_path
,
99 if (path_is_absolute(filename
)) {
100 pstrcpy(dest
, dest_size
, filename
);
102 p
= strchr(base_path
, ':');
107 p1
= strrchr(base_path
, '/');
111 p2
= strrchr(base_path
, '\\');
123 if (len
> dest_size
- 1)
125 memcpy(dest
, base_path
, len
);
127 pstrcat(dest
, dest_size
, filename
);
131 void bdrv_register(BlockDriver
*bdrv
)
133 if (!bdrv
->bdrv_aio_readv
) {
134 /* add AIO emulation layer */
135 bdrv
->bdrv_aio_readv
= bdrv_aio_readv_em
;
136 bdrv
->bdrv_aio_writev
= bdrv_aio_writev_em
;
137 } else if (!bdrv
->bdrv_read
) {
138 /* add synchronous IO emulation layer */
139 bdrv
->bdrv_read
= bdrv_read_em
;
140 bdrv
->bdrv_write
= bdrv_write_em
;
143 if (!bdrv
->bdrv_aio_flush
)
144 bdrv
->bdrv_aio_flush
= bdrv_aio_flush_em
;
146 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
149 /* create a new block device (by default it is empty) */
150 BlockDriverState
*bdrv_new(const char *device_name
)
152 BlockDriverState
*bs
;
154 bs
= qemu_mallocz(sizeof(BlockDriverState
));
155 pstrcpy(bs
->device_name
, sizeof(bs
->device_name
), device_name
);
156 if (device_name
[0] != '\0') {
157 QTAILQ_INSERT_TAIL(&bdrv_states
, bs
, list
);
162 BlockDriver
*bdrv_find_format(const char *format_name
)
165 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
166 if (!strcmp(drv1
->format_name
, format_name
)) {
173 static int bdrv_is_whitelisted(BlockDriver
*drv
)
175 static const char *whitelist
[] = {
176 CONFIG_BDRV_WHITELIST
181 return 1; /* no whitelist, anything goes */
183 for (p
= whitelist
; *p
; p
++) {
184 if (!strcmp(drv
->format_name
, *p
)) {
191 BlockDriver
*bdrv_find_whitelisted_format(const char *format_name
)
193 BlockDriver
*drv
= bdrv_find_format(format_name
);
194 return drv
&& bdrv_is_whitelisted(drv
) ? drv
: NULL
;
197 int bdrv_create(BlockDriver
*drv
, const char* filename
,
198 QEMUOptionParameter
*options
)
200 if (!drv
->bdrv_create
)
203 return drv
->bdrv_create(filename
, options
);
207 void get_tmp_filename(char *filename
, int size
)
209 char temp_dir
[MAX_PATH
];
211 GetTempPath(MAX_PATH
, temp_dir
);
212 GetTempFileName(temp_dir
, "qem", 0, filename
);
215 void get_tmp_filename(char *filename
, int size
)
219 /* XXX: race condition possible */
220 tmpdir
= getenv("TMPDIR");
223 snprintf(filename
, size
, "%s/vl.XXXXXX", tmpdir
);
224 fd
= mkstemp(filename
);
230 static int is_windows_drive_prefix(const char *filename
)
232 return (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
233 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
237 int is_windows_drive(const char *filename
)
239 if (is_windows_drive_prefix(filename
) &&
242 if (strstart(filename
, "\\\\.\\", NULL
) ||
243 strstart(filename
, "//./", NULL
))
249 static BlockDriver
*find_protocol(const char *filename
)
257 if (is_windows_drive(filename
) ||
258 is_windows_drive_prefix(filename
))
259 return bdrv_find_format("raw");
261 p
= strchr(filename
, ':');
263 return bdrv_find_format("raw");
265 if (len
> sizeof(protocol
) - 1)
266 len
= sizeof(protocol
) - 1;
267 memcpy(protocol
, filename
, len
);
268 protocol
[len
] = '\0';
269 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
270 if (drv1
->protocol_name
&&
271 !strcmp(drv1
->protocol_name
, protocol
)) {
279 * Detect host devices. By convention, /dev/cdrom[N] is always
280 * recognized as a host CDROM.
282 static BlockDriver
*find_hdev_driver(const char *filename
)
284 int score_max
= 0, score
;
285 BlockDriver
*drv
= NULL
, *d
;
287 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
288 if (d
->bdrv_probe_device
) {
289 score
= d
->bdrv_probe_device(filename
);
290 if (score
> score_max
) {
300 static BlockDriver
*find_image_format(const char *filename
)
302 int ret
, score
, score_max
;
303 BlockDriver
*drv1
, *drv
;
305 BlockDriverState
*bs
;
307 drv
= find_protocol(filename
);
308 /* no need to test disk image formats for vvfat */
309 if (drv
&& strcmp(drv
->format_name
, "vvfat") == 0)
312 ret
= bdrv_file_open(&bs
, filename
, 0);
315 ret
= bdrv_pread(bs
, 0, buf
, sizeof(buf
));
322 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
323 if (drv1
->bdrv_probe
) {
324 score
= drv1
->bdrv_probe(buf
, ret
, filename
);
325 if (score
> score_max
) {
334 int bdrv_file_open(BlockDriverState
**pbs
, const char *filename
, int flags
)
336 BlockDriverState
*bs
;
340 drv
= find_protocol(filename
);
346 ret
= bdrv_open(bs
, filename
, flags
, drv
);
356 int bdrv_open(BlockDriverState
*bs
, const char *filename
, int flags
,
360 char tmp_filename
[PATH_MAX
];
361 char backing_filename
[PATH_MAX
];
363 bs
->is_temporary
= 0;
366 bs
->open_flags
= flags
;
367 /* buffer_alignment defaulted to 512, drivers can change this value */
368 bs
->buffer_alignment
= 512;
370 if (flags
& BDRV_O_SNAPSHOT
) {
371 BlockDriverState
*bs1
;
374 BlockDriver
*bdrv_qcow2
;
375 QEMUOptionParameter
*options
;
377 /* if snapshot, we create a temporary backing file and open it
378 instead of opening 'filename' directly */
380 /* if there is a backing file, use it */
382 ret
= bdrv_open(bs1
, filename
, 0, drv
);
387 total_size
= bdrv_getlength(bs1
) >> BDRV_SECTOR_BITS
;
389 if (bs1
->drv
&& bs1
->drv
->protocol_name
)
394 get_tmp_filename(tmp_filename
, sizeof(tmp_filename
));
396 /* Real path is meaningless for protocols */
398 snprintf(backing_filename
, sizeof(backing_filename
),
400 else if (!realpath(filename
, backing_filename
))
403 bdrv_qcow2
= bdrv_find_format("qcow2");
404 options
= parse_option_parameters("", bdrv_qcow2
->create_options
, NULL
);
406 set_option_parameter_int(options
, BLOCK_OPT_SIZE
, total_size
* 512);
407 set_option_parameter(options
, BLOCK_OPT_BACKING_FILE
, backing_filename
);
409 set_option_parameter(options
, BLOCK_OPT_BACKING_FMT
,
413 ret
= bdrv_create(bdrv_qcow2
, tmp_filename
, options
);
418 filename
= tmp_filename
;
420 bs
->is_temporary
= 1;
423 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
426 drv
= find_hdev_driver(filename
);
428 drv
= find_image_format(filename
);
434 goto unlink_and_fail
;
436 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
)) {
438 goto unlink_and_fail
;
442 bs
->opaque
= qemu_mallocz(drv
->instance_size
);
445 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
446 * write cache to the guest. We do need the fdatasync to flush
447 * out transactions for block allocations, and we maybe have a
448 * volatile write cache in our backing device to deal with.
450 if (flags
& (BDRV_O_CACHE_WB
|BDRV_O_NOCACHE
))
451 bs
->enable_write_cache
= 1;
454 * Clear flags that are internal to the block layer before opening the
457 open_flags
= flags
& ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
460 * Snapshots should be writeable.
462 if (bs
->is_temporary
) {
463 open_flags
|= BDRV_O_RDWR
;
466 ret
= drv
->bdrv_open(bs
, filename
, open_flags
);
471 bs
->keep_read_only
= bs
->read_only
= !(open_flags
& BDRV_O_RDWR
);
472 if (drv
->bdrv_getlength
) {
473 bs
->total_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
476 if (bs
->is_temporary
) {
480 if ((flags
& BDRV_O_NO_BACKING
) == 0 && bs
->backing_file
[0] != '\0') {
481 /* if there is a backing file, use it */
482 BlockDriver
*back_drv
= NULL
;
483 bs
->backing_hd
= bdrv_new("");
484 path_combine(backing_filename
, sizeof(backing_filename
),
485 filename
, bs
->backing_file
);
486 if (bs
->backing_format
[0] != '\0')
487 back_drv
= bdrv_find_format(bs
->backing_format
);
489 /* backing files always opened read-only */
490 open_flags
&= ~BDRV_O_RDWR
;
492 ret
= bdrv_open(bs
->backing_hd
, backing_filename
, open_flags
, back_drv
);
497 if (bs
->is_temporary
) {
498 bs
->backing_hd
->keep_read_only
= !(flags
& BDRV_O_RDWR
);
500 /* base image inherits from "parent" */
501 bs
->backing_hd
->keep_read_only
= bs
->keep_read_only
;
505 if (!bdrv_key_required(bs
)) {
506 /* call the change callback */
507 bs
->media_changed
= 1;
509 bs
->change_cb(bs
->change_opaque
);
514 qemu_free(bs
->opaque
);
518 if (bs
->is_temporary
)
523 void bdrv_close(BlockDriverState
*bs
)
527 bdrv_delete(bs
->backing_hd
);
528 bs
->drv
->bdrv_close(bs
);
529 qemu_free(bs
->opaque
);
531 if (bs
->is_temporary
) {
532 unlink(bs
->filename
);
538 /* call the change callback */
539 bs
->media_changed
= 1;
541 bs
->change_cb(bs
->change_opaque
);
545 void bdrv_delete(BlockDriverState
*bs
)
547 /* remove from list, if necessary */
548 if (bs
->device_name
[0] != '\0') {
549 QTAILQ_REMOVE(&bdrv_states
, bs
, list
);
557 * Run consistency checks on an image
559 * Returns the number of errors or -errno when an internal error occurs
561 int bdrv_check(BlockDriverState
*bs
)
563 if (bs
->drv
->bdrv_check
== NULL
) {
567 return bs
->drv
->bdrv_check(bs
);
570 /* commit COW file into the raw image */
571 int bdrv_commit(BlockDriverState
*bs
)
573 BlockDriver
*drv
= bs
->drv
;
574 int64_t i
, total_sectors
;
575 int n
, j
, ro
, open_flags
;
576 int ret
= 0, rw_ret
= 0;
577 unsigned char sector
[512];
579 BlockDriverState
*bs_rw
, *bs_ro
;
584 if (!bs
->backing_hd
) {
588 if (bs
->backing_hd
->keep_read_only
) {
592 ro
= bs
->backing_hd
->read_only
;
593 strncpy(filename
, bs
->backing_hd
->filename
, sizeof(filename
));
594 open_flags
= bs
->backing_hd
->open_flags
;
598 bdrv_delete(bs
->backing_hd
);
599 bs
->backing_hd
= NULL
;
600 bs_rw
= bdrv_new("");
601 rw_ret
= bdrv_open(bs_rw
, filename
, open_flags
| BDRV_O_RDWR
, NULL
);
604 /* try to re-open read-only */
605 bs_ro
= bdrv_new("");
606 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
, NULL
);
609 /* drive not functional anymore */
613 bs
->backing_hd
= bs_ro
;
616 bs
->backing_hd
= bs_rw
;
619 total_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
620 for (i
= 0; i
< total_sectors
;) {
621 if (drv
->bdrv_is_allocated(bs
, i
, 65536, &n
)) {
622 for(j
= 0; j
< n
; j
++) {
623 if (bdrv_read(bs
, i
, sector
, 1) != 0) {
628 if (bdrv_write(bs
->backing_hd
, i
, sector
, 1) != 0) {
639 if (drv
->bdrv_make_empty
) {
640 ret
= drv
->bdrv_make_empty(bs
);
645 * Make sure all data we wrote to the backing device is actually
649 bdrv_flush(bs
->backing_hd
);
655 bdrv_delete(bs
->backing_hd
);
656 bs
->backing_hd
= NULL
;
657 bs_ro
= bdrv_new("");
658 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
, NULL
);
661 /* drive not functional anymore */
665 bs
->backing_hd
= bs_ro
;
666 bs
->backing_hd
->keep_read_only
= 0;
675 * -EINVAL - backing format specified, but no file
676 * -ENOSPC - can't update the backing file because no space is left in the
678 * -ENOTSUP - format driver doesn't support changing the backing file
680 int bdrv_change_backing_file(BlockDriverState
*bs
,
681 const char *backing_file
, const char *backing_fmt
)
683 BlockDriver
*drv
= bs
->drv
;
685 if (drv
->bdrv_change_backing_file
!= NULL
) {
686 return drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
692 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
697 if (!bdrv_is_inserted(bs
))
703 len
= bdrv_getlength(bs
);
708 if ((offset
> len
) || (len
- offset
< size
))
714 static int bdrv_check_request(BlockDriverState
*bs
, int64_t sector_num
,
717 return bdrv_check_byte_request(bs
, sector_num
* 512, nb_sectors
* 512);
720 /* return < 0 if error. See bdrv_write() for the return codes */
721 int bdrv_read(BlockDriverState
*bs
, int64_t sector_num
,
722 uint8_t *buf
, int nb_sectors
)
724 BlockDriver
*drv
= bs
->drv
;
728 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
731 return drv
->bdrv_read(bs
, sector_num
, buf
, nb_sectors
);
734 static void set_dirty_bitmap(BlockDriverState
*bs
, int64_t sector_num
,
735 int nb_sectors
, int dirty
)
738 unsigned long val
, idx
, bit
;
740 start
= sector_num
/ BDRV_SECTORS_PER_DIRTY_CHUNK
;
741 end
= (sector_num
+ nb_sectors
- 1) / BDRV_SECTORS_PER_DIRTY_CHUNK
;
743 for (; start
<= end
; start
++) {
744 idx
= start
/ (sizeof(unsigned long) * 8);
745 bit
= start
% (sizeof(unsigned long) * 8);
746 val
= bs
->dirty_bitmap
[idx
];
748 if (!(val
& (1 << bit
))) {
753 if (val
& (1 << bit
)) {
758 bs
->dirty_bitmap
[idx
] = val
;
762 /* Return < 0 if error. Important errors are:
763 -EIO generic I/O error (may happen for all errors)
764 -ENOMEDIUM No media inserted.
765 -EINVAL Invalid sector number or nb_sectors
766 -EACCES Trying to write a read-only device
768 int bdrv_write(BlockDriverState
*bs
, int64_t sector_num
,
769 const uint8_t *buf
, int nb_sectors
)
771 BlockDriver
*drv
= bs
->drv
;
776 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
779 if (bs
->dirty_bitmap
) {
780 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
783 return drv
->bdrv_write(bs
, sector_num
, buf
, nb_sectors
);
786 int bdrv_pread(BlockDriverState
*bs
, int64_t offset
,
787 void *buf
, int count1
)
789 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
790 int len
, nb_sectors
, count
;
795 /* first read to align to sector start */
796 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
799 sector_num
= offset
>> BDRV_SECTOR_BITS
;
801 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
803 memcpy(buf
, tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), len
);
811 /* read the sectors "in place" */
812 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
813 if (nb_sectors
> 0) {
814 if ((ret
= bdrv_read(bs
, sector_num
, buf
, nb_sectors
)) < 0)
816 sector_num
+= nb_sectors
;
817 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
822 /* add data from the last sector */
824 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
826 memcpy(buf
, tmp_buf
, count
);
831 int bdrv_pwrite(BlockDriverState
*bs
, int64_t offset
,
832 const void *buf
, int count1
)
834 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
835 int len
, nb_sectors
, count
;
840 /* first write to align to sector start */
841 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
844 sector_num
= offset
>> BDRV_SECTOR_BITS
;
846 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
848 memcpy(tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), buf
, len
);
849 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
858 /* write the sectors "in place" */
859 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
860 if (nb_sectors
> 0) {
861 if ((ret
= bdrv_write(bs
, sector_num
, buf
, nb_sectors
)) < 0)
863 sector_num
+= nb_sectors
;
864 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
869 /* add data from the last sector */
871 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
873 memcpy(tmp_buf
, buf
, count
);
874 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
881 * Truncate file to 'offset' bytes (needed only for file protocols)
883 int bdrv_truncate(BlockDriverState
*bs
, int64_t offset
)
885 BlockDriver
*drv
= bs
->drv
;
888 if (!drv
->bdrv_truncate
)
892 return drv
->bdrv_truncate(bs
, offset
);
896 * Length of a file in bytes. Return < 0 if error or unknown.
898 int64_t bdrv_getlength(BlockDriverState
*bs
)
900 BlockDriver
*drv
= bs
->drv
;
903 if (!drv
->bdrv_getlength
) {
905 return bs
->total_sectors
* BDRV_SECTOR_SIZE
;
907 return drv
->bdrv_getlength(bs
);
910 /* return 0 as number of sectors if no device present or error */
911 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
914 length
= bdrv_getlength(bs
);
918 length
= length
>> BDRV_SECTOR_BITS
;
919 *nb_sectors_ptr
= length
;
923 uint8_t boot_ind
; /* 0x80 - active */
924 uint8_t head
; /* starting head */
925 uint8_t sector
; /* starting sector */
926 uint8_t cyl
; /* starting cylinder */
927 uint8_t sys_ind
; /* What partition type */
928 uint8_t end_head
; /* end head */
929 uint8_t end_sector
; /* end sector */
930 uint8_t end_cyl
; /* end cylinder */
931 uint32_t start_sect
; /* starting sector counting from 0 */
932 uint32_t nr_sects
; /* nr of sectors in partition */
933 } __attribute__((packed
));
935 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
936 static int guess_disk_lchs(BlockDriverState
*bs
,
937 int *pcylinders
, int *pheads
, int *psectors
)
940 int ret
, i
, heads
, sectors
, cylinders
;
945 bdrv_get_geometry(bs
, &nb_sectors
);
947 ret
= bdrv_read(bs
, 0, buf
, 1);
950 /* test msdos magic */
951 if (buf
[510] != 0x55 || buf
[511] != 0xaa)
953 for(i
= 0; i
< 4; i
++) {
954 p
= ((struct partition
*)(buf
+ 0x1be)) + i
;
955 nr_sects
= le32_to_cpu(p
->nr_sects
);
956 if (nr_sects
&& p
->end_head
) {
957 /* We make the assumption that the partition terminates on
958 a cylinder boundary */
959 heads
= p
->end_head
+ 1;
960 sectors
= p
->end_sector
& 63;
963 cylinders
= nb_sectors
/ (heads
* sectors
);
964 if (cylinders
< 1 || cylinders
> 16383)
968 *pcylinders
= cylinders
;
970 printf("guessed geometry: LCHS=%d %d %d\n",
971 cylinders
, heads
, sectors
);
979 void bdrv_guess_geometry(BlockDriverState
*bs
, int *pcyls
, int *pheads
, int *psecs
)
981 int translation
, lba_detected
= 0;
982 int cylinders
, heads
, secs
;
985 /* if a geometry hint is available, use it */
986 bdrv_get_geometry(bs
, &nb_sectors
);
987 bdrv_get_geometry_hint(bs
, &cylinders
, &heads
, &secs
);
988 translation
= bdrv_get_translation_hint(bs
);
989 if (cylinders
!= 0) {
994 if (guess_disk_lchs(bs
, &cylinders
, &heads
, &secs
) == 0) {
996 /* if heads > 16, it means that a BIOS LBA
997 translation was active, so the default
998 hardware geometry is OK */
1000 goto default_geometry
;
1005 /* disable any translation to be in sync with
1006 the logical geometry */
1007 if (translation
== BIOS_ATA_TRANSLATION_AUTO
) {
1008 bdrv_set_translation_hint(bs
,
1009 BIOS_ATA_TRANSLATION_NONE
);
1014 /* if no geometry, use a standard physical disk geometry */
1015 cylinders
= nb_sectors
/ (16 * 63);
1017 if (cylinders
> 16383)
1019 else if (cylinders
< 2)
1024 if ((lba_detected
== 1) && (translation
== BIOS_ATA_TRANSLATION_AUTO
)) {
1025 if ((*pcyls
* *pheads
) <= 131072) {
1026 bdrv_set_translation_hint(bs
,
1027 BIOS_ATA_TRANSLATION_LARGE
);
1029 bdrv_set_translation_hint(bs
,
1030 BIOS_ATA_TRANSLATION_LBA
);
1034 bdrv_set_geometry_hint(bs
, *pcyls
, *pheads
, *psecs
);
1038 void bdrv_set_geometry_hint(BlockDriverState
*bs
,
1039 int cyls
, int heads
, int secs
)
1046 void bdrv_set_type_hint(BlockDriverState
*bs
, int type
)
1049 bs
->removable
= ((type
== BDRV_TYPE_CDROM
||
1050 type
== BDRV_TYPE_FLOPPY
));
1053 void bdrv_set_translation_hint(BlockDriverState
*bs
, int translation
)
1055 bs
->translation
= translation
;
1058 void bdrv_get_geometry_hint(BlockDriverState
*bs
,
1059 int *pcyls
, int *pheads
, int *psecs
)
1062 *pheads
= bs
->heads
;
1066 int bdrv_get_type_hint(BlockDriverState
*bs
)
1071 int bdrv_get_translation_hint(BlockDriverState
*bs
)
1073 return bs
->translation
;
1076 int bdrv_is_removable(BlockDriverState
*bs
)
1078 return bs
->removable
;
1081 int bdrv_is_read_only(BlockDriverState
*bs
)
1083 return bs
->read_only
;
1086 int bdrv_is_sg(BlockDriverState
*bs
)
1091 int bdrv_enable_write_cache(BlockDriverState
*bs
)
1093 return bs
->enable_write_cache
;
1096 /* XXX: no longer used */
1097 void bdrv_set_change_cb(BlockDriverState
*bs
,
1098 void (*change_cb
)(void *opaque
), void *opaque
)
1100 bs
->change_cb
= change_cb
;
1101 bs
->change_opaque
= opaque
;
1104 int bdrv_is_encrypted(BlockDriverState
*bs
)
1106 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1108 return bs
->encrypted
;
1111 int bdrv_key_required(BlockDriverState
*bs
)
1113 BlockDriverState
*backing_hd
= bs
->backing_hd
;
1115 if (backing_hd
&& backing_hd
->encrypted
&& !backing_hd
->valid_key
)
1117 return (bs
->encrypted
&& !bs
->valid_key
);
1120 int bdrv_set_key(BlockDriverState
*bs
, const char *key
)
1123 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
) {
1124 ret
= bdrv_set_key(bs
->backing_hd
, key
);
1130 if (!bs
->encrypted
) {
1132 } else if (!bs
->drv
|| !bs
->drv
->bdrv_set_key
) {
1135 ret
= bs
->drv
->bdrv_set_key(bs
, key
);
1138 } else if (!bs
->valid_key
) {
1140 /* call the change callback now, we skipped it on open */
1141 bs
->media_changed
= 1;
1143 bs
->change_cb(bs
->change_opaque
);
1148 void bdrv_get_format(BlockDriverState
*bs
, char *buf
, int buf_size
)
1153 pstrcpy(buf
, buf_size
, bs
->drv
->format_name
);
1157 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
1162 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
1163 it(opaque
, drv
->format_name
);
1167 BlockDriverState
*bdrv_find(const char *name
)
1169 BlockDriverState
*bs
;
1171 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1172 if (!strcmp(name
, bs
->device_name
)) {
1179 void bdrv_iterate(void (*it
)(void *opaque
, BlockDriverState
*bs
), void *opaque
)
1181 BlockDriverState
*bs
;
1183 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1188 const char *bdrv_get_device_name(BlockDriverState
*bs
)
1190 return bs
->device_name
;
1193 void bdrv_flush(BlockDriverState
*bs
)
1195 if (bs
->drv
&& bs
->drv
->bdrv_flush
)
1196 bs
->drv
->bdrv_flush(bs
);
1199 void bdrv_flush_all(void)
1201 BlockDriverState
*bs
;
1203 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1204 if (bs
->drv
&& !bdrv_is_read_only(bs
) &&
1205 (!bdrv_is_removable(bs
) || bdrv_is_inserted(bs
))) {
1212 * Returns true iff the specified sector is present in the disk image. Drivers
1213 * not implementing the functionality are assumed to not support backing files,
1214 * hence all their sectors are reported as allocated.
1216 * 'pnum' is set to the number of sectors (including and immediately following
1217 * the specified sector) that are known to be in the same
1218 * allocated/unallocated state.
1220 * 'nb_sectors' is the max value 'pnum' should be set to.
1222 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
,
1226 if (!bs
->drv
->bdrv_is_allocated
) {
1227 if (sector_num
>= bs
->total_sectors
) {
1231 n
= bs
->total_sectors
- sector_num
;
1232 *pnum
= (n
< nb_sectors
) ? (n
) : (nb_sectors
);
1235 return bs
->drv
->bdrv_is_allocated(bs
, sector_num
, nb_sectors
, pnum
);
1238 void bdrv_mon_event(const BlockDriverState
*bdrv
,
1239 BlockMonEventAction action
, int is_read
)
1242 const char *action_str
;
1245 case BDRV_ACTION_REPORT
:
1246 action_str
= "report";
1248 case BDRV_ACTION_IGNORE
:
1249 action_str
= "ignore";
1251 case BDRV_ACTION_STOP
:
1252 action_str
= "stop";
1258 data
= qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1261 is_read
? "read" : "write");
1262 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR
, data
);
1264 qobject_decref(data
);
1267 static void bdrv_print_dict(QObject
*obj
, void *opaque
)
1270 Monitor
*mon
= opaque
;
1272 bs_dict
= qobject_to_qdict(obj
);
1274 monitor_printf(mon
, "%s: type=%s removable=%d",
1275 qdict_get_str(bs_dict
, "device"),
1276 qdict_get_str(bs_dict
, "type"),
1277 qdict_get_bool(bs_dict
, "removable"));
1279 if (qdict_get_bool(bs_dict
, "removable")) {
1280 monitor_printf(mon
, " locked=%d", qdict_get_bool(bs_dict
, "locked"));
1283 if (qdict_haskey(bs_dict
, "inserted")) {
1284 QDict
*qdict
= qobject_to_qdict(qdict_get(bs_dict
, "inserted"));
1286 monitor_printf(mon
, " file=");
1287 monitor_print_filename(mon
, qdict_get_str(qdict
, "file"));
1288 if (qdict_haskey(qdict
, "backing_file")) {
1289 monitor_printf(mon
, " backing_file=");
1290 monitor_print_filename(mon
, qdict_get_str(qdict
, "backing_file"));
1292 monitor_printf(mon
, " ro=%d drv=%s encrypted=%d",
1293 qdict_get_bool(qdict
, "ro"),
1294 qdict_get_str(qdict
, "drv"),
1295 qdict_get_bool(qdict
, "encrypted"));
1297 monitor_printf(mon
, " [not inserted]");
1300 monitor_printf(mon
, "\n");
1303 void bdrv_info_print(Monitor
*mon
, const QObject
*data
)
1305 qlist_iter(qobject_to_qlist(data
), bdrv_print_dict
, mon
);
1309 * bdrv_info(): Block devices information
1311 * Each block device information is stored in a QDict and the
1312 * returned QObject is a QList of all devices.
1314 * The QDict contains the following:
1316 * - "device": device name
1317 * - "type": device type
1318 * - "removable": true if the device is removable, false otherwise
1319 * - "locked": true if the device is locked, false otherwise
1320 * - "inserted": only present if the device is inserted, it is a QDict
1321 * containing the following:
1322 * - "file": device file name
1323 * - "ro": true if read-only, false otherwise
1324 * - "drv": driver format name
1325 * - "backing_file": backing file name if one is used
1326 * - "encrypted": true if encrypted, false otherwise
1330 * [ { "device": "ide0-hd0", "type": "hd", "removable": false, "locked": false,
1331 * "inserted": { "file": "/tmp/foobar", "ro": false, "drv": "qcow2" } },
1332 * { "device": "floppy0", "type": "floppy", "removable": true,
1333 * "locked": false } ]
1335 void bdrv_info(Monitor
*mon
, QObject
**ret_data
)
1338 BlockDriverState
*bs
;
1340 bs_list
= qlist_new();
1342 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1344 const char *type
= "unknown";
1350 case BDRV_TYPE_CDROM
:
1353 case BDRV_TYPE_FLOPPY
:
1358 bs_obj
= qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1359 "'removable': %i, 'locked': %i }",
1360 bs
->device_name
, type
, bs
->removable
,
1365 QDict
*bs_dict
= qobject_to_qdict(bs_obj
);
1367 obj
= qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1368 "'encrypted': %i }",
1369 bs
->filename
, bs
->read_only
,
1370 bs
->drv
->format_name
,
1371 bdrv_is_encrypted(bs
));
1372 if (bs
->backing_file
[0] != '\0') {
1373 QDict
*qdict
= qobject_to_qdict(obj
);
1374 qdict_put(qdict
, "backing_file",
1375 qstring_from_str(bs
->backing_file
));
1378 qdict_put_obj(bs_dict
, "inserted", obj
);
1380 qlist_append_obj(bs_list
, bs_obj
);
1383 *ret_data
= QOBJECT(bs_list
);
1386 static void bdrv_stats_iter(QObject
*data
, void *opaque
)
1389 Monitor
*mon
= opaque
;
1391 qdict
= qobject_to_qdict(data
);
1392 monitor_printf(mon
, "%s:", qdict_get_str(qdict
, "device"));
1394 qdict
= qobject_to_qdict(qdict_get(qdict
, "stats"));
1395 monitor_printf(mon
, " rd_bytes=%" PRId64
1396 " wr_bytes=%" PRId64
1397 " rd_operations=%" PRId64
1398 " wr_operations=%" PRId64
1400 qdict_get_int(qdict
, "rd_bytes"),
1401 qdict_get_int(qdict
, "wr_bytes"),
1402 qdict_get_int(qdict
, "rd_operations"),
1403 qdict_get_int(qdict
, "wr_operations"));
1406 void bdrv_stats_print(Monitor
*mon
, const QObject
*data
)
1408 qlist_iter(qobject_to_qlist(data
), bdrv_stats_iter
, mon
);
1412 * bdrv_info_stats(): show block device statistics
1414 * Each device statistic information is stored in a QDict and
1415 * the returned QObject is a QList of all devices.
1417 * The QDict contains the following:
1419 * - "device": device name
1420 * - "stats": A QDict with the statistics information, it contains:
1421 * - "rd_bytes": bytes read
1422 * - "wr_bytes": bytes written
1423 * - "rd_operations": read operations
1424 * - "wr_operations": write operations
1428 * [ { "device": "ide0-hd0",
1429 * "stats": { "rd_bytes": 512,
1431 * "rd_operations": 1,
1432 * "wr_operations": 0 } },
1433 * { "device": "ide1-cd0",
1434 * "stats": { "rd_bytes": 0,
1436 * "rd_operations": 0,
1437 * "wr_operations": 0 } } ]
1439 void bdrv_info_stats(Monitor
*mon
, QObject
**ret_data
)
1443 BlockDriverState
*bs
;
1445 devices
= qlist_new();
1447 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1448 obj
= qobject_from_jsonf("{ 'device': %s, 'stats': {"
1449 "'rd_bytes': %" PRId64
","
1450 "'wr_bytes': %" PRId64
","
1451 "'rd_operations': %" PRId64
","
1452 "'wr_operations': %" PRId64
1455 bs
->rd_bytes
, bs
->wr_bytes
,
1456 bs
->rd_ops
, bs
->wr_ops
);
1457 qlist_append_obj(devices
, obj
);
1460 *ret_data
= QOBJECT(devices
);
1463 const char *bdrv_get_encrypted_filename(BlockDriverState
*bs
)
1465 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1466 return bs
->backing_file
;
1467 else if (bs
->encrypted
)
1468 return bs
->filename
;
1473 void bdrv_get_backing_filename(BlockDriverState
*bs
,
1474 char *filename
, int filename_size
)
1476 if (!bs
->backing_file
) {
1477 pstrcpy(filename
, filename_size
, "");
1479 pstrcpy(filename
, filename_size
, bs
->backing_file
);
1483 int bdrv_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
1484 const uint8_t *buf
, int nb_sectors
)
1486 BlockDriver
*drv
= bs
->drv
;
1489 if (!drv
->bdrv_write_compressed
)
1491 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1494 if (bs
->dirty_bitmap
) {
1495 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1498 return drv
->bdrv_write_compressed(bs
, sector_num
, buf
, nb_sectors
);
1501 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1503 BlockDriver
*drv
= bs
->drv
;
1506 if (!drv
->bdrv_get_info
)
1508 memset(bdi
, 0, sizeof(*bdi
));
1509 return drv
->bdrv_get_info(bs
, bdi
);
1512 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
1513 int64_t pos
, int size
)
1515 BlockDriver
*drv
= bs
->drv
;
1518 if (!drv
->bdrv_save_vmstate
)
1520 return drv
->bdrv_save_vmstate(bs
, buf
, pos
, size
);
1523 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
1524 int64_t pos
, int size
)
1526 BlockDriver
*drv
= bs
->drv
;
1529 if (!drv
->bdrv_load_vmstate
)
1531 return drv
->bdrv_load_vmstate(bs
, buf
, pos
, size
);
1534 void bdrv_debug_event(BlockDriverState
*bs
, BlkDebugEvent event
)
1536 BlockDriver
*drv
= bs
->drv
;
1538 if (!drv
|| !drv
->bdrv_debug_event
) {
1542 return drv
->bdrv_debug_event(bs
, event
);
1546 /**************************************************************/
1547 /* handling of snapshots */
1549 int bdrv_snapshot_create(BlockDriverState
*bs
,
1550 QEMUSnapshotInfo
*sn_info
)
1552 BlockDriver
*drv
= bs
->drv
;
1555 if (!drv
->bdrv_snapshot_create
)
1557 return drv
->bdrv_snapshot_create(bs
, sn_info
);
1560 int bdrv_snapshot_goto(BlockDriverState
*bs
,
1561 const char *snapshot_id
)
1563 BlockDriver
*drv
= bs
->drv
;
1566 if (!drv
->bdrv_snapshot_goto
)
1568 return drv
->bdrv_snapshot_goto(bs
, snapshot_id
);
1571 int bdrv_snapshot_delete(BlockDriverState
*bs
, const char *snapshot_id
)
1573 BlockDriver
*drv
= bs
->drv
;
1576 if (!drv
->bdrv_snapshot_delete
)
1578 return drv
->bdrv_snapshot_delete(bs
, snapshot_id
);
1581 int bdrv_snapshot_list(BlockDriverState
*bs
,
1582 QEMUSnapshotInfo
**psn_info
)
1584 BlockDriver
*drv
= bs
->drv
;
1587 if (!drv
->bdrv_snapshot_list
)
1589 return drv
->bdrv_snapshot_list(bs
, psn_info
);
1592 #define NB_SUFFIXES 4
1594 char *get_human_readable_size(char *buf
, int buf_size
, int64_t size
)
1596 static const char suffixes
[NB_SUFFIXES
] = "KMGT";
1601 snprintf(buf
, buf_size
, "%" PRId64
, size
);
1604 for(i
= 0; i
< NB_SUFFIXES
; i
++) {
1605 if (size
< (10 * base
)) {
1606 snprintf(buf
, buf_size
, "%0.1f%c",
1607 (double)size
/ base
,
1610 } else if (size
< (1000 * base
) || i
== (NB_SUFFIXES
- 1)) {
1611 snprintf(buf
, buf_size
, "%" PRId64
"%c",
1612 ((size
+ (base
>> 1)) / base
),
1622 char *bdrv_snapshot_dump(char *buf
, int buf_size
, QEMUSnapshotInfo
*sn
)
1624 char buf1
[128], date_buf
[128], clock_buf
[128];
1634 snprintf(buf
, buf_size
,
1635 "%-10s%-20s%7s%20s%15s",
1636 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1640 ptm
= localtime(&ti
);
1641 strftime(date_buf
, sizeof(date_buf
),
1642 "%Y-%m-%d %H:%M:%S", ptm
);
1644 localtime_r(&ti
, &tm
);
1645 strftime(date_buf
, sizeof(date_buf
),
1646 "%Y-%m-%d %H:%M:%S", &tm
);
1648 secs
= sn
->vm_clock_nsec
/ 1000000000;
1649 snprintf(clock_buf
, sizeof(clock_buf
),
1650 "%02d:%02d:%02d.%03d",
1652 (int)((secs
/ 60) % 60),
1654 (int)((sn
->vm_clock_nsec
/ 1000000) % 1000));
1655 snprintf(buf
, buf_size
,
1656 "%-10s%-20s%7s%20s%15s",
1657 sn
->id_str
, sn
->name
,
1658 get_human_readable_size(buf1
, sizeof(buf1
), sn
->vm_state_size
),
1666 /**************************************************************/
1669 BlockDriverAIOCB
*bdrv_aio_readv(BlockDriverState
*bs
, int64_t sector_num
,
1670 QEMUIOVector
*qiov
, int nb_sectors
,
1671 BlockDriverCompletionFunc
*cb
, void *opaque
)
1673 BlockDriver
*drv
= bs
->drv
;
1674 BlockDriverAIOCB
*ret
;
1678 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1681 ret
= drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
1685 /* Update stats even though technically transfer has not happened. */
1686 bs
->rd_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
1693 BlockDriverAIOCB
*bdrv_aio_writev(BlockDriverState
*bs
, int64_t sector_num
,
1694 QEMUIOVector
*qiov
, int nb_sectors
,
1695 BlockDriverCompletionFunc
*cb
, void *opaque
)
1697 BlockDriver
*drv
= bs
->drv
;
1698 BlockDriverAIOCB
*ret
;
1704 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1707 if (bs
->dirty_bitmap
) {
1708 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1711 ret
= drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
1715 /* Update stats even though technically transfer has not happened. */
1716 bs
->wr_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
1724 typedef struct MultiwriteCB
{
1729 BlockDriverCompletionFunc
*cb
;
1731 QEMUIOVector
*free_qiov
;
1736 static void multiwrite_user_cb(MultiwriteCB
*mcb
)
1740 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
1741 mcb
->callbacks
[i
].cb(mcb
->callbacks
[i
].opaque
, mcb
->error
);
1742 if (mcb
->callbacks
[i
].free_qiov
) {
1743 qemu_iovec_destroy(mcb
->callbacks
[i
].free_qiov
);
1745 qemu_free(mcb
->callbacks
[i
].free_qiov
);
1746 qemu_vfree(mcb
->callbacks
[i
].free_buf
);
1750 static void multiwrite_cb(void *opaque
, int ret
)
1752 MultiwriteCB
*mcb
= opaque
;
1754 if (ret
< 0 && !mcb
->error
) {
1756 multiwrite_user_cb(mcb
);
1759 mcb
->num_requests
--;
1760 if (mcb
->num_requests
== 0) {
1761 if (mcb
->error
== 0) {
1762 multiwrite_user_cb(mcb
);
1768 static int multiwrite_req_compare(const void *a
, const void *b
)
1770 return (((BlockRequest
*) a
)->sector
- ((BlockRequest
*) b
)->sector
);
1774 * Takes a bunch of requests and tries to merge them. Returns the number of
1775 * requests that remain after merging.
1777 static int multiwrite_merge(BlockDriverState
*bs
, BlockRequest
*reqs
,
1778 int num_reqs
, MultiwriteCB
*mcb
)
1782 // Sort requests by start sector
1783 qsort(reqs
, num_reqs
, sizeof(*reqs
), &multiwrite_req_compare
);
1785 // Check if adjacent requests touch the same clusters. If so, combine them,
1786 // filling up gaps with zero sectors.
1788 for (i
= 1; i
< num_reqs
; i
++) {
1790 int64_t oldreq_last
= reqs
[outidx
].sector
+ reqs
[outidx
].nb_sectors
;
1792 // This handles the cases that are valid for all block drivers, namely
1793 // exactly sequential writes and overlapping writes.
1794 if (reqs
[i
].sector
<= oldreq_last
) {
1798 // The block driver may decide that it makes sense to combine requests
1799 // even if there is a gap of some sectors between them. In this case,
1800 // the gap is filled with zeros (therefore only applicable for yet
1801 // unused space in format like qcow2).
1802 if (!merge
&& bs
->drv
->bdrv_merge_requests
) {
1803 merge
= bs
->drv
->bdrv_merge_requests(bs
, &reqs
[outidx
], &reqs
[i
]);
1806 if (reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1 > IOV_MAX
) {
1812 QEMUIOVector
*qiov
= qemu_mallocz(sizeof(*qiov
));
1813 qemu_iovec_init(qiov
,
1814 reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1);
1816 // Add the first request to the merged one. If the requests are
1817 // overlapping, drop the last sectors of the first request.
1818 size
= (reqs
[i
].sector
- reqs
[outidx
].sector
) << 9;
1819 qemu_iovec_concat(qiov
, reqs
[outidx
].qiov
, size
);
1821 // We might need to add some zeros between the two requests
1822 if (reqs
[i
].sector
> oldreq_last
) {
1823 size_t zero_bytes
= (reqs
[i
].sector
- oldreq_last
) << 9;
1824 uint8_t *buf
= qemu_blockalign(bs
, zero_bytes
);
1825 memset(buf
, 0, zero_bytes
);
1826 qemu_iovec_add(qiov
, buf
, zero_bytes
);
1827 mcb
->callbacks
[i
].free_buf
= buf
;
1830 // Add the second request
1831 qemu_iovec_concat(qiov
, reqs
[i
].qiov
, reqs
[i
].qiov
->size
);
1833 reqs
[outidx
].nb_sectors
+= reqs
[i
].nb_sectors
;
1834 reqs
[outidx
].qiov
= qiov
;
1836 mcb
->callbacks
[i
].free_qiov
= reqs
[outidx
].qiov
;
1839 reqs
[outidx
].sector
= reqs
[i
].sector
;
1840 reqs
[outidx
].nb_sectors
= reqs
[i
].nb_sectors
;
1841 reqs
[outidx
].qiov
= reqs
[i
].qiov
;
1849 * Submit multiple AIO write requests at once.
1851 * On success, the function returns 0 and all requests in the reqs array have
1852 * been submitted. In error case this function returns -1, and any of the
1853 * requests may or may not be submitted yet. In particular, this means that the
1854 * callback will be called for some of the requests, for others it won't. The
1855 * caller must check the error field of the BlockRequest to wait for the right
1856 * callbacks (if error != 0, no callback will be called).
1858 * The implementation may modify the contents of the reqs array, e.g. to merge
1859 * requests. However, the fields opaque and error are left unmodified as they
1860 * are used to signal failure for a single request to the caller.
1862 int bdrv_aio_multiwrite(BlockDriverState
*bs
, BlockRequest
*reqs
, int num_reqs
)
1864 BlockDriverAIOCB
*acb
;
1868 if (num_reqs
== 0) {
1872 // Create MultiwriteCB structure
1873 mcb
= qemu_mallocz(sizeof(*mcb
) + num_reqs
* sizeof(*mcb
->callbacks
));
1874 mcb
->num_requests
= 0;
1875 mcb
->num_callbacks
= num_reqs
;
1877 for (i
= 0; i
< num_reqs
; i
++) {
1878 mcb
->callbacks
[i
].cb
= reqs
[i
].cb
;
1879 mcb
->callbacks
[i
].opaque
= reqs
[i
].opaque
;
1882 // Check for mergable requests
1883 num_reqs
= multiwrite_merge(bs
, reqs
, num_reqs
, mcb
);
1885 // Run the aio requests
1886 for (i
= 0; i
< num_reqs
; i
++) {
1887 acb
= bdrv_aio_writev(bs
, reqs
[i
].sector
, reqs
[i
].qiov
,
1888 reqs
[i
].nb_sectors
, multiwrite_cb
, mcb
);
1891 // We can only fail the whole thing if no request has been
1892 // submitted yet. Otherwise we'll wait for the submitted AIOs to
1893 // complete and report the error in the callback.
1894 if (mcb
->num_requests
== 0) {
1895 reqs
[i
].error
= -EIO
;
1898 mcb
->num_requests
++;
1899 multiwrite_cb(mcb
, -EIO
);
1903 mcb
->num_requests
++;
1914 BlockDriverAIOCB
*bdrv_aio_flush(BlockDriverState
*bs
,
1915 BlockDriverCompletionFunc
*cb
, void *opaque
)
1917 BlockDriver
*drv
= bs
->drv
;
1921 return drv
->bdrv_aio_flush(bs
, cb
, opaque
);
1924 void bdrv_aio_cancel(BlockDriverAIOCB
*acb
)
1926 acb
->pool
->cancel(acb
);
1930 /**************************************************************/
1931 /* async block device emulation */
1933 typedef struct BlockDriverAIOCBSync
{
1934 BlockDriverAIOCB common
;
1937 /* vector translation state */
1941 } BlockDriverAIOCBSync
;
1943 static void bdrv_aio_cancel_em(BlockDriverAIOCB
*blockacb
)
1945 BlockDriverAIOCBSync
*acb
= (BlockDriverAIOCBSync
*)blockacb
;
1946 qemu_bh_delete(acb
->bh
);
1948 qemu_aio_release(acb
);
1951 static AIOPool bdrv_em_aio_pool
= {
1952 .aiocb_size
= sizeof(BlockDriverAIOCBSync
),
1953 .cancel
= bdrv_aio_cancel_em
,
1956 static void bdrv_aio_bh_cb(void *opaque
)
1958 BlockDriverAIOCBSync
*acb
= opaque
;
1961 qemu_iovec_from_buffer(acb
->qiov
, acb
->bounce
, acb
->qiov
->size
);
1962 qemu_vfree(acb
->bounce
);
1963 acb
->common
.cb(acb
->common
.opaque
, acb
->ret
);
1964 qemu_bh_delete(acb
->bh
);
1966 qemu_aio_release(acb
);
1969 static BlockDriverAIOCB
*bdrv_aio_rw_vector(BlockDriverState
*bs
,
1973 BlockDriverCompletionFunc
*cb
,
1978 BlockDriverAIOCBSync
*acb
;
1980 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
1981 acb
->is_write
= is_write
;
1983 acb
->bounce
= qemu_blockalign(bs
, qiov
->size
);
1986 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
1989 qemu_iovec_to_buffer(acb
->qiov
, acb
->bounce
);
1990 acb
->ret
= bdrv_write(bs
, sector_num
, acb
->bounce
, nb_sectors
);
1992 acb
->ret
= bdrv_read(bs
, sector_num
, acb
->bounce
, nb_sectors
);
1995 qemu_bh_schedule(acb
->bh
);
1997 return &acb
->common
;
2000 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
2001 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2002 BlockDriverCompletionFunc
*cb
, void *opaque
)
2004 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 0);
2007 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
2008 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2009 BlockDriverCompletionFunc
*cb
, void *opaque
)
2011 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 1);
2014 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
2015 BlockDriverCompletionFunc
*cb
, void *opaque
)
2017 BlockDriverAIOCBSync
*acb
;
2019 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2020 acb
->is_write
= 1; /* don't bounce in the completion hadler */
2026 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2029 qemu_bh_schedule(acb
->bh
);
2030 return &acb
->common
;
2033 /**************************************************************/
2034 /* sync block device emulation */
2036 static void bdrv_rw_em_cb(void *opaque
, int ret
)
2038 *(int *)opaque
= ret
;
2041 #define NOT_DONE 0x7fffffff
2043 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
2044 uint8_t *buf
, int nb_sectors
)
2047 BlockDriverAIOCB
*acb
;
2051 async_context_push();
2053 async_ret
= NOT_DONE
;
2054 iov
.iov_base
= (void *)buf
;
2055 iov
.iov_len
= nb_sectors
* 512;
2056 qemu_iovec_init_external(&qiov
, &iov
, 1);
2057 acb
= bdrv_aio_readv(bs
, sector_num
, &qiov
, nb_sectors
,
2058 bdrv_rw_em_cb
, &async_ret
);
2064 while (async_ret
== NOT_DONE
) {
2070 async_context_pop();
2074 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
2075 const uint8_t *buf
, int nb_sectors
)
2078 BlockDriverAIOCB
*acb
;
2082 async_context_push();
2084 async_ret
= NOT_DONE
;
2085 iov
.iov_base
= (void *)buf
;
2086 iov
.iov_len
= nb_sectors
* 512;
2087 qemu_iovec_init_external(&qiov
, &iov
, 1);
2088 acb
= bdrv_aio_writev(bs
, sector_num
, &qiov
, nb_sectors
,
2089 bdrv_rw_em_cb
, &async_ret
);
2094 while (async_ret
== NOT_DONE
) {
2099 async_context_pop();
2103 void bdrv_init(void)
2105 module_call_init(MODULE_INIT_BLOCK
);
2108 void bdrv_init_with_whitelist(void)
2110 use_bdrv_whitelist
= 1;
2114 void *qemu_aio_get(AIOPool
*pool
, BlockDriverState
*bs
,
2115 BlockDriverCompletionFunc
*cb
, void *opaque
)
2117 BlockDriverAIOCB
*acb
;
2119 if (pool
->free_aiocb
) {
2120 acb
= pool
->free_aiocb
;
2121 pool
->free_aiocb
= acb
->next
;
2123 acb
= qemu_mallocz(pool
->aiocb_size
);
2128 acb
->opaque
= opaque
;
2132 void qemu_aio_release(void *p
)
2134 BlockDriverAIOCB
*acb
= (BlockDriverAIOCB
*)p
;
2135 AIOPool
*pool
= acb
->pool
;
2136 acb
->next
= pool
->free_aiocb
;
2137 pool
->free_aiocb
= acb
;
2140 /**************************************************************/
2141 /* removable device support */
2144 * Return TRUE if the media is present
2146 int bdrv_is_inserted(BlockDriverState
*bs
)
2148 BlockDriver
*drv
= bs
->drv
;
2152 if (!drv
->bdrv_is_inserted
)
2154 ret
= drv
->bdrv_is_inserted(bs
);
2159 * Return TRUE if the media changed since the last call to this
2160 * function. It is currently only used for floppy disks
2162 int bdrv_media_changed(BlockDriverState
*bs
)
2164 BlockDriver
*drv
= bs
->drv
;
2167 if (!drv
|| !drv
->bdrv_media_changed
)
2170 ret
= drv
->bdrv_media_changed(bs
);
2171 if (ret
== -ENOTSUP
)
2172 ret
= bs
->media_changed
;
2173 bs
->media_changed
= 0;
2178 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2180 int bdrv_eject(BlockDriverState
*bs
, int eject_flag
)
2182 BlockDriver
*drv
= bs
->drv
;
2189 if (!drv
|| !drv
->bdrv_eject
) {
2192 ret
= drv
->bdrv_eject(bs
, eject_flag
);
2194 if (ret
== -ENOTSUP
) {
2203 int bdrv_is_locked(BlockDriverState
*bs
)
2209 * Lock or unlock the media (if it is locked, the user won't be able
2210 * to eject it manually).
2212 void bdrv_set_locked(BlockDriverState
*bs
, int locked
)
2214 BlockDriver
*drv
= bs
->drv
;
2216 bs
->locked
= locked
;
2217 if (drv
&& drv
->bdrv_set_locked
) {
2218 drv
->bdrv_set_locked(bs
, locked
);
2222 /* needed for generic scsi interface */
2224 int bdrv_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
2226 BlockDriver
*drv
= bs
->drv
;
2228 if (drv
&& drv
->bdrv_ioctl
)
2229 return drv
->bdrv_ioctl(bs
, req
, buf
);
2233 BlockDriverAIOCB
*bdrv_aio_ioctl(BlockDriverState
*bs
,
2234 unsigned long int req
, void *buf
,
2235 BlockDriverCompletionFunc
*cb
, void *opaque
)
2237 BlockDriver
*drv
= bs
->drv
;
2239 if (drv
&& drv
->bdrv_aio_ioctl
)
2240 return drv
->bdrv_aio_ioctl(bs
, req
, buf
, cb
, opaque
);
2246 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
2248 return qemu_memalign((bs
&& bs
->buffer_alignment
) ? bs
->buffer_alignment
: 512, size
);
2251 void bdrv_set_dirty_tracking(BlockDriverState
*bs
, int enable
)
2253 int64_t bitmap_size
;
2255 bs
->dirty_count
= 0;
2257 if (!bs
->dirty_bitmap
) {
2258 bitmap_size
= (bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
) +
2259 BDRV_SECTORS_PER_DIRTY_CHUNK
* 8 - 1;
2260 bitmap_size
/= BDRV_SECTORS_PER_DIRTY_CHUNK
* 8;
2262 bs
->dirty_bitmap
= qemu_mallocz(bitmap_size
);
2265 if (bs
->dirty_bitmap
) {
2266 qemu_free(bs
->dirty_bitmap
);
2267 bs
->dirty_bitmap
= NULL
;
2272 int bdrv_get_dirty(BlockDriverState
*bs
, int64_t sector
)
2274 int64_t chunk
= sector
/ (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK
;
2276 if (bs
->dirty_bitmap
&&
2277 (sector
<< BDRV_SECTOR_BITS
) < bdrv_getlength(bs
)) {
2278 return bs
->dirty_bitmap
[chunk
/ (sizeof(unsigned long) * 8)] &
2279 (1 << (chunk
% (sizeof(unsigned long) * 8)));
2285 void bdrv_reset_dirty(BlockDriverState
*bs
, int64_t cur_sector
,
2288 set_dirty_bitmap(bs
, cur_sector
, nr_sectors
, 0);
2291 int64_t bdrv_get_dirty_count(BlockDriverState
*bs
)
2293 return bs
->dirty_count
;