2 * QEMU System Emulator block driver
4 * Copyright (c) 2003 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 #include "config-host.h"
25 #include "qemu-common.h"
27 #include "block_int.h"
29 #include "qemu-objects.h"
32 #include <sys/types.h>
34 #include <sys/ioctl.h>
35 #include <sys/queue.h>
45 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
46 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
47 BlockDriverCompletionFunc
*cb
, void *opaque
);
48 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
49 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
50 BlockDriverCompletionFunc
*cb
, void *opaque
);
51 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
52 BlockDriverCompletionFunc
*cb
, void *opaque
);
53 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
54 BlockDriverCompletionFunc
*cb
, void *opaque
);
55 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
56 uint8_t *buf
, int nb_sectors
);
57 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
58 const uint8_t *buf
, int nb_sectors
);
59 static BlockDriver
*find_protocol(const char *filename
);
61 static QTAILQ_HEAD(, BlockDriverState
) bdrv_states
=
62 QTAILQ_HEAD_INITIALIZER(bdrv_states
);
64 static QLIST_HEAD(, BlockDriver
) bdrv_drivers
=
65 QLIST_HEAD_INITIALIZER(bdrv_drivers
);
67 /* If non-zero, use only whitelisted block drivers */
68 static int use_bdrv_whitelist
;
70 int path_is_absolute(const char *path
)
74 /* specific case for names like: "\\.\d:" */
75 if (*path
== '/' || *path
== '\\')
78 p
= strchr(path
, ':');
84 return (*p
== '/' || *p
== '\\');
90 /* if filename is absolute, just copy it to dest. Otherwise, build a
91 path to it by considering it is relative to base_path. URL are
93 void path_combine(char *dest
, int dest_size
,
94 const char *base_path
,
102 if (path_is_absolute(filename
)) {
103 pstrcpy(dest
, dest_size
, filename
);
105 p
= strchr(base_path
, ':');
110 p1
= strrchr(base_path
, '/');
114 p2
= strrchr(base_path
, '\\');
126 if (len
> dest_size
- 1)
128 memcpy(dest
, base_path
, len
);
130 pstrcat(dest
, dest_size
, filename
);
134 void bdrv_register(BlockDriver
*bdrv
)
136 if (!bdrv
->bdrv_aio_readv
) {
137 /* add AIO emulation layer */
138 bdrv
->bdrv_aio_readv
= bdrv_aio_readv_em
;
139 bdrv
->bdrv_aio_writev
= bdrv_aio_writev_em
;
140 } else if (!bdrv
->bdrv_read
) {
141 /* add synchronous IO emulation layer */
142 bdrv
->bdrv_read
= bdrv_read_em
;
143 bdrv
->bdrv_write
= bdrv_write_em
;
146 if (!bdrv
->bdrv_aio_flush
)
147 bdrv
->bdrv_aio_flush
= bdrv_aio_flush_em
;
149 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
152 /* create a new block device (by default it is empty) */
153 BlockDriverState
*bdrv_new(const char *device_name
)
155 BlockDriverState
*bs
;
157 bs
= qemu_mallocz(sizeof(BlockDriverState
));
158 pstrcpy(bs
->device_name
, sizeof(bs
->device_name
), device_name
);
159 if (device_name
[0] != '\0') {
160 QTAILQ_INSERT_TAIL(&bdrv_states
, bs
, list
);
165 BlockDriver
*bdrv_find_format(const char *format_name
)
168 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
169 if (!strcmp(drv1
->format_name
, format_name
)) {
176 static int bdrv_is_whitelisted(BlockDriver
*drv
)
178 static const char *whitelist
[] = {
179 CONFIG_BDRV_WHITELIST
184 return 1; /* no whitelist, anything goes */
186 for (p
= whitelist
; *p
; p
++) {
187 if (!strcmp(drv
->format_name
, *p
)) {
194 BlockDriver
*bdrv_find_whitelisted_format(const char *format_name
)
196 BlockDriver
*drv
= bdrv_find_format(format_name
);
197 return drv
&& bdrv_is_whitelisted(drv
) ? drv
: NULL
;
200 int bdrv_create(BlockDriver
*drv
, const char* filename
,
201 QEMUOptionParameter
*options
)
203 if (!drv
->bdrv_create
)
206 return drv
->bdrv_create(filename
, options
);
209 int bdrv_create_file(const char* filename
, QEMUOptionParameter
*options
)
213 drv
= find_protocol(filename
);
215 drv
= bdrv_find_format("file");
218 return bdrv_create(drv
, filename
, options
);
222 void get_tmp_filename(char *filename
, int size
)
224 char temp_dir
[MAX_PATH
];
226 GetTempPath(MAX_PATH
, temp_dir
);
227 GetTempFileName(temp_dir
, "qem", 0, filename
);
230 void get_tmp_filename(char *filename
, int size
)
234 /* XXX: race condition possible */
235 tmpdir
= getenv("TMPDIR");
238 snprintf(filename
, size
, "%s/vl.XXXXXX", tmpdir
);
239 fd
= mkstemp(filename
);
245 static int is_windows_drive_prefix(const char *filename
)
247 return (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
248 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
252 int is_windows_drive(const char *filename
)
254 if (is_windows_drive_prefix(filename
) &&
257 if (strstart(filename
, "\\\\.\\", NULL
) ||
258 strstart(filename
, "//./", NULL
))
265 * Detect host devices. By convention, /dev/cdrom[N] is always
266 * recognized as a host CDROM.
268 static BlockDriver
*find_hdev_driver(const char *filename
)
270 int score_max
= 0, score
;
271 BlockDriver
*drv
= NULL
, *d
;
273 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
274 if (d
->bdrv_probe_device
) {
275 score
= d
->bdrv_probe_device(filename
);
276 if (score
> score_max
) {
286 static BlockDriver
*find_protocol(const char *filename
)
294 /* TODO Drivers without bdrv_file_open must be specified explicitly */
297 is_drive
= is_windows_drive(filename
) ||
298 is_windows_drive_prefix(filename
);
302 p
= strchr(filename
, ':');
303 if (!p
|| is_drive
) {
304 drv1
= find_hdev_driver(filename
);
306 drv1
= bdrv_find_format("file");
311 if (len
> sizeof(protocol
) - 1)
312 len
= sizeof(protocol
) - 1;
313 memcpy(protocol
, filename
, len
);
314 protocol
[len
] = '\0';
315 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
316 if (drv1
->protocol_name
&&
317 !strcmp(drv1
->protocol_name
, protocol
)) {
324 static BlockDriver
*find_image_format(const char *filename
)
326 int ret
, score
, score_max
;
327 BlockDriver
*drv1
, *drv
;
329 BlockDriverState
*bs
;
331 ret
= bdrv_file_open(&bs
, filename
, 0);
335 /* Return the raw BlockDriver * to scsi-generic devices */
337 return bdrv_find_format("raw");
339 ret
= bdrv_pread(bs
, 0, buf
, sizeof(buf
));
347 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
348 if (drv1
->bdrv_probe
) {
349 score
= drv1
->bdrv_probe(buf
, ret
, filename
);
350 if (score
> score_max
) {
360 * Set the current 'total_sectors' value
362 static int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
364 BlockDriver
*drv
= bs
->drv
;
366 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
370 /* query actual device if possible, otherwise just trust the hint */
371 if (drv
->bdrv_getlength
) {
372 int64_t length
= drv
->bdrv_getlength(bs
);
376 hint
= length
>> BDRV_SECTOR_BITS
;
379 bs
->total_sectors
= hint
;
384 * Common part for opening disk images and files
386 static int bdrv_open_common(BlockDriverState
*bs
, const char *filename
,
387 int flags
, BlockDriver
*drv
)
394 bs
->total_sectors
= 0;
395 bs
->is_temporary
= 0;
398 bs
->open_flags
= flags
;
399 /* buffer_alignment defaulted to 512, drivers can change this value */
400 bs
->buffer_alignment
= 512;
402 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
404 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
)) {
409 bs
->opaque
= qemu_mallocz(drv
->instance_size
);
412 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
413 * write cache to the guest. We do need the fdatasync to flush
414 * out transactions for block allocations, and we maybe have a
415 * volatile write cache in our backing device to deal with.
417 if (flags
& (BDRV_O_CACHE_WB
|BDRV_O_NOCACHE
))
418 bs
->enable_write_cache
= 1;
421 * Clear flags that are internal to the block layer before opening the
424 open_flags
= flags
& ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
427 * Snapshots should be writeable.
429 if (bs
->is_temporary
) {
430 open_flags
|= BDRV_O_RDWR
;
433 /* Open the image, either directly or using a protocol */
434 if (drv
->bdrv_file_open
) {
435 ret
= drv
->bdrv_file_open(bs
, filename
, open_flags
);
437 ret
= bdrv_file_open(&bs
->file
, filename
, open_flags
);
439 ret
= drv
->bdrv_open(bs
, open_flags
);
447 bs
->keep_read_only
= bs
->read_only
= !(open_flags
& BDRV_O_RDWR
);
449 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
455 if (bs
->is_temporary
) {
463 bdrv_delete(bs
->file
);
466 qemu_free(bs
->opaque
);
473 * Opens a file using a protocol (file, host_device, nbd, ...)
475 int bdrv_file_open(BlockDriverState
**pbs
, const char *filename
, int flags
)
477 BlockDriverState
*bs
;
481 drv
= find_protocol(filename
);
487 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
498 * Opens a disk image (raw, qcow2, vmdk, ...)
500 int bdrv_open(BlockDriverState
*bs
, const char *filename
, int flags
,
505 if (flags
& BDRV_O_SNAPSHOT
) {
506 BlockDriverState
*bs1
;
509 BlockDriver
*bdrv_qcow2
;
510 QEMUOptionParameter
*options
;
511 char tmp_filename
[PATH_MAX
];
512 char backing_filename
[PATH_MAX
];
514 /* if snapshot, we create a temporary backing file and open it
515 instead of opening 'filename' directly */
517 /* if there is a backing file, use it */
519 ret
= bdrv_open(bs1
, filename
, 0, drv
);
524 total_size
= bdrv_getlength(bs1
) >> BDRV_SECTOR_BITS
;
526 if (bs1
->drv
&& bs1
->drv
->protocol_name
)
531 get_tmp_filename(tmp_filename
, sizeof(tmp_filename
));
533 /* Real path is meaningless for protocols */
535 snprintf(backing_filename
, sizeof(backing_filename
),
537 else if (!realpath(filename
, backing_filename
))
540 bdrv_qcow2
= bdrv_find_format("qcow2");
541 options
= parse_option_parameters("", bdrv_qcow2
->create_options
, NULL
);
543 set_option_parameter_int(options
, BLOCK_OPT_SIZE
, total_size
* 512);
544 set_option_parameter(options
, BLOCK_OPT_BACKING_FILE
, backing_filename
);
546 set_option_parameter(options
, BLOCK_OPT_BACKING_FMT
,
550 ret
= bdrv_create(bdrv_qcow2
, tmp_filename
, options
);
551 free_option_parameters(options
);
556 filename
= tmp_filename
;
558 bs
->is_temporary
= 1;
561 /* Find the right image format driver */
563 drv
= find_image_format(filename
);
568 goto unlink_and_fail
;
572 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
574 goto unlink_and_fail
;
577 /* If there is a backing file, use it */
578 if ((flags
& BDRV_O_NO_BACKING
) == 0 && bs
->backing_file
[0] != '\0') {
579 char backing_filename
[PATH_MAX
];
581 BlockDriver
*back_drv
= NULL
;
583 bs
->backing_hd
= bdrv_new("");
584 path_combine(backing_filename
, sizeof(backing_filename
),
585 filename
, bs
->backing_file
);
586 if (bs
->backing_format
[0] != '\0')
587 back_drv
= bdrv_find_format(bs
->backing_format
);
589 /* backing files always opened read-only */
591 flags
& ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
593 ret
= bdrv_open(bs
->backing_hd
, backing_filename
, back_flags
, back_drv
);
598 if (bs
->is_temporary
) {
599 bs
->backing_hd
->keep_read_only
= !(flags
& BDRV_O_RDWR
);
601 /* base image inherits from "parent" */
602 bs
->backing_hd
->keep_read_only
= bs
->keep_read_only
;
606 if (!bdrv_key_required(bs
)) {
607 /* call the change callback */
608 bs
->media_changed
= 1;
610 bs
->change_cb(bs
->change_opaque
);
616 if (bs
->is_temporary
) {
622 void bdrv_close(BlockDriverState
*bs
)
625 if (bs
->backing_hd
) {
626 bdrv_delete(bs
->backing_hd
);
627 bs
->backing_hd
= NULL
;
629 bs
->drv
->bdrv_close(bs
);
630 qemu_free(bs
->opaque
);
632 if (bs
->is_temporary
) {
633 unlink(bs
->filename
);
639 if (bs
->file
!= NULL
) {
640 bdrv_close(bs
->file
);
643 /* call the change callback */
644 bs
->media_changed
= 1;
646 bs
->change_cb(bs
->change_opaque
);
650 void bdrv_delete(BlockDriverState
*bs
)
652 /* remove from list, if necessary */
653 if (bs
->device_name
[0] != '\0') {
654 QTAILQ_REMOVE(&bdrv_states
, bs
, list
);
658 if (bs
->file
!= NULL
) {
659 bdrv_delete(bs
->file
);
666 * Run consistency checks on an image
668 * Returns the number of errors or -errno when an internal error occurs
670 int bdrv_check(BlockDriverState
*bs
)
672 if (bs
->drv
->bdrv_check
== NULL
) {
676 return bs
->drv
->bdrv_check(bs
);
679 /* commit COW file into the raw image */
680 int bdrv_commit(BlockDriverState
*bs
)
682 BlockDriver
*drv
= bs
->drv
;
683 int64_t i
, total_sectors
;
684 int n
, j
, ro
, open_flags
;
685 int ret
= 0, rw_ret
= 0;
686 unsigned char sector
[512];
688 BlockDriverState
*bs_rw
, *bs_ro
;
693 if (!bs
->backing_hd
) {
697 if (bs
->backing_hd
->keep_read_only
) {
701 ro
= bs
->backing_hd
->read_only
;
702 strncpy(filename
, bs
->backing_hd
->filename
, sizeof(filename
));
703 open_flags
= bs
->backing_hd
->open_flags
;
707 bdrv_delete(bs
->backing_hd
);
708 bs
->backing_hd
= NULL
;
709 bs_rw
= bdrv_new("");
710 rw_ret
= bdrv_open(bs_rw
, filename
, open_flags
| BDRV_O_RDWR
, drv
);
713 /* try to re-open read-only */
714 bs_ro
= bdrv_new("");
715 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
, drv
);
718 /* drive not functional anymore */
722 bs
->backing_hd
= bs_ro
;
725 bs
->backing_hd
= bs_rw
;
728 total_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
729 for (i
= 0; i
< total_sectors
;) {
730 if (drv
->bdrv_is_allocated(bs
, i
, 65536, &n
)) {
731 for(j
= 0; j
< n
; j
++) {
732 if (bdrv_read(bs
, i
, sector
, 1) != 0) {
737 if (bdrv_write(bs
->backing_hd
, i
, sector
, 1) != 0) {
748 if (drv
->bdrv_make_empty
) {
749 ret
= drv
->bdrv_make_empty(bs
);
754 * Make sure all data we wrote to the backing device is actually
758 bdrv_flush(bs
->backing_hd
);
764 bdrv_delete(bs
->backing_hd
);
765 bs
->backing_hd
= NULL
;
766 bs_ro
= bdrv_new("");
767 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
, drv
);
770 /* drive not functional anymore */
774 bs
->backing_hd
= bs_ro
;
775 bs
->backing_hd
->keep_read_only
= 0;
784 * -EINVAL - backing format specified, but no file
785 * -ENOSPC - can't update the backing file because no space is left in the
787 * -ENOTSUP - format driver doesn't support changing the backing file
789 int bdrv_change_backing_file(BlockDriverState
*bs
,
790 const char *backing_file
, const char *backing_fmt
)
792 BlockDriver
*drv
= bs
->drv
;
794 if (drv
->bdrv_change_backing_file
!= NULL
) {
795 return drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
801 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
806 if (!bdrv_is_inserted(bs
))
812 len
= bdrv_getlength(bs
);
817 if ((offset
> len
) || (len
- offset
< size
))
823 static int bdrv_check_request(BlockDriverState
*bs
, int64_t sector_num
,
826 return bdrv_check_byte_request(bs
, sector_num
* 512, nb_sectors
* 512);
829 /* return < 0 if error. See bdrv_write() for the return codes */
830 int bdrv_read(BlockDriverState
*bs
, int64_t sector_num
,
831 uint8_t *buf
, int nb_sectors
)
833 BlockDriver
*drv
= bs
->drv
;
837 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
840 return drv
->bdrv_read(bs
, sector_num
, buf
, nb_sectors
);
843 static void set_dirty_bitmap(BlockDriverState
*bs
, int64_t sector_num
,
844 int nb_sectors
, int dirty
)
847 unsigned long val
, idx
, bit
;
849 start
= sector_num
/ BDRV_SECTORS_PER_DIRTY_CHUNK
;
850 end
= (sector_num
+ nb_sectors
- 1) / BDRV_SECTORS_PER_DIRTY_CHUNK
;
852 for (; start
<= end
; start
++) {
853 idx
= start
/ (sizeof(unsigned long) * 8);
854 bit
= start
% (sizeof(unsigned long) * 8);
855 val
= bs
->dirty_bitmap
[idx
];
857 if (!(val
& (1 << bit
))) {
862 if (val
& (1 << bit
)) {
867 bs
->dirty_bitmap
[idx
] = val
;
871 /* Return < 0 if error. Important errors are:
872 -EIO generic I/O error (may happen for all errors)
873 -ENOMEDIUM No media inserted.
874 -EINVAL Invalid sector number or nb_sectors
875 -EACCES Trying to write a read-only device
877 int bdrv_write(BlockDriverState
*bs
, int64_t sector_num
,
878 const uint8_t *buf
, int nb_sectors
)
880 BlockDriver
*drv
= bs
->drv
;
885 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
888 if (bs
->dirty_bitmap
) {
889 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
892 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
893 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
896 return drv
->bdrv_write(bs
, sector_num
, buf
, nb_sectors
);
899 int bdrv_pread(BlockDriverState
*bs
, int64_t offset
,
900 void *buf
, int count1
)
902 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
903 int len
, nb_sectors
, count
;
908 /* first read to align to sector start */
909 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
912 sector_num
= offset
>> BDRV_SECTOR_BITS
;
914 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
916 memcpy(buf
, tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), len
);
924 /* read the sectors "in place" */
925 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
926 if (nb_sectors
> 0) {
927 if ((ret
= bdrv_read(bs
, sector_num
, buf
, nb_sectors
)) < 0)
929 sector_num
+= nb_sectors
;
930 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
935 /* add data from the last sector */
937 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
939 memcpy(buf
, tmp_buf
, count
);
944 int bdrv_pwrite(BlockDriverState
*bs
, int64_t offset
,
945 const void *buf
, int count1
)
947 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
948 int len
, nb_sectors
, count
;
953 /* first write to align to sector start */
954 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
957 sector_num
= offset
>> BDRV_SECTOR_BITS
;
959 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
961 memcpy(tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), buf
, len
);
962 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
971 /* write the sectors "in place" */
972 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
973 if (nb_sectors
> 0) {
974 if ((ret
= bdrv_write(bs
, sector_num
, buf
, nb_sectors
)) < 0)
976 sector_num
+= nb_sectors
;
977 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
982 /* add data from the last sector */
984 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
986 memcpy(tmp_buf
, buf
, count
);
987 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
994 * Truncate file to 'offset' bytes (needed only for file protocols)
996 int bdrv_truncate(BlockDriverState
*bs
, int64_t offset
)
998 BlockDriver
*drv
= bs
->drv
;
1002 if (!drv
->bdrv_truncate
)
1006 ret
= drv
->bdrv_truncate(bs
, offset
);
1008 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
1014 * Length of a file in bytes. Return < 0 if error or unknown.
1016 int64_t bdrv_getlength(BlockDriverState
*bs
)
1018 BlockDriver
*drv
= bs
->drv
;
1022 /* Fixed size devices use the total_sectors value for speed instead of
1023 issuing a length query (like lseek) on each call. Also, legacy block
1024 drivers don't provide a bdrv_getlength function and must use
1026 if (!bs
->growable
|| !drv
->bdrv_getlength
) {
1027 return bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1029 return drv
->bdrv_getlength(bs
);
1032 /* return 0 as number of sectors if no device present or error */
1033 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
1036 length
= bdrv_getlength(bs
);
1040 length
= length
>> BDRV_SECTOR_BITS
;
1041 *nb_sectors_ptr
= length
;
1045 uint8_t boot_ind
; /* 0x80 - active */
1046 uint8_t head
; /* starting head */
1047 uint8_t sector
; /* starting sector */
1048 uint8_t cyl
; /* starting cylinder */
1049 uint8_t sys_ind
; /* What partition type */
1050 uint8_t end_head
; /* end head */
1051 uint8_t end_sector
; /* end sector */
1052 uint8_t end_cyl
; /* end cylinder */
1053 uint32_t start_sect
; /* starting sector counting from 0 */
1054 uint32_t nr_sects
; /* nr of sectors in partition */
1055 } __attribute__((packed
));
1057 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1058 static int guess_disk_lchs(BlockDriverState
*bs
,
1059 int *pcylinders
, int *pheads
, int *psectors
)
1062 int ret
, i
, heads
, sectors
, cylinders
;
1063 struct partition
*p
;
1065 uint64_t nb_sectors
;
1067 bdrv_get_geometry(bs
, &nb_sectors
);
1069 ret
= bdrv_read(bs
, 0, buf
, 1);
1072 /* test msdos magic */
1073 if (buf
[510] != 0x55 || buf
[511] != 0xaa)
1075 for(i
= 0; i
< 4; i
++) {
1076 p
= ((struct partition
*)(buf
+ 0x1be)) + i
;
1077 nr_sects
= le32_to_cpu(p
->nr_sects
);
1078 if (nr_sects
&& p
->end_head
) {
1079 /* We make the assumption that the partition terminates on
1080 a cylinder boundary */
1081 heads
= p
->end_head
+ 1;
1082 sectors
= p
->end_sector
& 63;
1085 cylinders
= nb_sectors
/ (heads
* sectors
);
1086 if (cylinders
< 1 || cylinders
> 16383)
1089 *psectors
= sectors
;
1090 *pcylinders
= cylinders
;
1092 printf("guessed geometry: LCHS=%d %d %d\n",
1093 cylinders
, heads
, sectors
);
1101 void bdrv_guess_geometry(BlockDriverState
*bs
, int *pcyls
, int *pheads
, int *psecs
)
1103 int translation
, lba_detected
= 0;
1104 int cylinders
, heads
, secs
;
1105 uint64_t nb_sectors
;
1107 /* if a geometry hint is available, use it */
1108 bdrv_get_geometry(bs
, &nb_sectors
);
1109 bdrv_get_geometry_hint(bs
, &cylinders
, &heads
, &secs
);
1110 translation
= bdrv_get_translation_hint(bs
);
1111 if (cylinders
!= 0) {
1116 if (guess_disk_lchs(bs
, &cylinders
, &heads
, &secs
) == 0) {
1118 /* if heads > 16, it means that a BIOS LBA
1119 translation was active, so the default
1120 hardware geometry is OK */
1122 goto default_geometry
;
1127 /* disable any translation to be in sync with
1128 the logical geometry */
1129 if (translation
== BIOS_ATA_TRANSLATION_AUTO
) {
1130 bdrv_set_translation_hint(bs
,
1131 BIOS_ATA_TRANSLATION_NONE
);
1136 /* if no geometry, use a standard physical disk geometry */
1137 cylinders
= nb_sectors
/ (16 * 63);
1139 if (cylinders
> 16383)
1141 else if (cylinders
< 2)
1146 if ((lba_detected
== 1) && (translation
== BIOS_ATA_TRANSLATION_AUTO
)) {
1147 if ((*pcyls
* *pheads
) <= 131072) {
1148 bdrv_set_translation_hint(bs
,
1149 BIOS_ATA_TRANSLATION_LARGE
);
1151 bdrv_set_translation_hint(bs
,
1152 BIOS_ATA_TRANSLATION_LBA
);
1156 bdrv_set_geometry_hint(bs
, *pcyls
, *pheads
, *psecs
);
1160 void bdrv_set_geometry_hint(BlockDriverState
*bs
,
1161 int cyls
, int heads
, int secs
)
1168 void bdrv_set_type_hint(BlockDriverState
*bs
, int type
)
1171 bs
->removable
= ((type
== BDRV_TYPE_CDROM
||
1172 type
== BDRV_TYPE_FLOPPY
));
1175 void bdrv_set_translation_hint(BlockDriverState
*bs
, int translation
)
1177 bs
->translation
= translation
;
1180 void bdrv_get_geometry_hint(BlockDriverState
*bs
,
1181 int *pcyls
, int *pheads
, int *psecs
)
1184 *pheads
= bs
->heads
;
1188 int bdrv_get_type_hint(BlockDriverState
*bs
)
1193 int bdrv_get_translation_hint(BlockDriverState
*bs
)
1195 return bs
->translation
;
1198 int bdrv_is_removable(BlockDriverState
*bs
)
1200 return bs
->removable
;
1203 int bdrv_is_read_only(BlockDriverState
*bs
)
1205 return bs
->read_only
;
1208 int bdrv_is_sg(BlockDriverState
*bs
)
1213 int bdrv_enable_write_cache(BlockDriverState
*bs
)
1215 return bs
->enable_write_cache
;
1218 /* XXX: no longer used */
1219 void bdrv_set_change_cb(BlockDriverState
*bs
,
1220 void (*change_cb
)(void *opaque
), void *opaque
)
1222 bs
->change_cb
= change_cb
;
1223 bs
->change_opaque
= opaque
;
1226 int bdrv_is_encrypted(BlockDriverState
*bs
)
1228 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1230 return bs
->encrypted
;
1233 int bdrv_key_required(BlockDriverState
*bs
)
1235 BlockDriverState
*backing_hd
= bs
->backing_hd
;
1237 if (backing_hd
&& backing_hd
->encrypted
&& !backing_hd
->valid_key
)
1239 return (bs
->encrypted
&& !bs
->valid_key
);
1242 int bdrv_set_key(BlockDriverState
*bs
, const char *key
)
1245 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
) {
1246 ret
= bdrv_set_key(bs
->backing_hd
, key
);
1252 if (!bs
->encrypted
) {
1254 } else if (!bs
->drv
|| !bs
->drv
->bdrv_set_key
) {
1257 ret
= bs
->drv
->bdrv_set_key(bs
, key
);
1260 } else if (!bs
->valid_key
) {
1262 /* call the change callback now, we skipped it on open */
1263 bs
->media_changed
= 1;
1265 bs
->change_cb(bs
->change_opaque
);
1270 void bdrv_get_format(BlockDriverState
*bs
, char *buf
, int buf_size
)
1275 pstrcpy(buf
, buf_size
, bs
->drv
->format_name
);
1279 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
1284 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
1285 it(opaque
, drv
->format_name
);
1289 BlockDriverState
*bdrv_find(const char *name
)
1291 BlockDriverState
*bs
;
1293 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1294 if (!strcmp(name
, bs
->device_name
)) {
1301 void bdrv_iterate(void (*it
)(void *opaque
, BlockDriverState
*bs
), void *opaque
)
1303 BlockDriverState
*bs
;
1305 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1310 const char *bdrv_get_device_name(BlockDriverState
*bs
)
1312 return bs
->device_name
;
1315 void bdrv_flush(BlockDriverState
*bs
)
1317 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
1321 if (bs
->drv
&& bs
->drv
->bdrv_flush
)
1322 bs
->drv
->bdrv_flush(bs
);
1325 void bdrv_flush_all(void)
1327 BlockDriverState
*bs
;
1329 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1330 if (bs
->drv
&& !bdrv_is_read_only(bs
) &&
1331 (!bdrv_is_removable(bs
) || bdrv_is_inserted(bs
))) {
1337 int bdrv_has_zero_init(BlockDriverState
*bs
)
1341 if (bs
->drv
->no_zero_init
) {
1343 } else if (bs
->file
) {
1344 return bdrv_has_zero_init(bs
->file
);
1351 * Returns true iff the specified sector is present in the disk image. Drivers
1352 * not implementing the functionality are assumed to not support backing files,
1353 * hence all their sectors are reported as allocated.
1355 * 'pnum' is set to the number of sectors (including and immediately following
1356 * the specified sector) that are known to be in the same
1357 * allocated/unallocated state.
1359 * 'nb_sectors' is the max value 'pnum' should be set to.
1361 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
,
1365 if (!bs
->drv
->bdrv_is_allocated
) {
1366 if (sector_num
>= bs
->total_sectors
) {
1370 n
= bs
->total_sectors
- sector_num
;
1371 *pnum
= (n
< nb_sectors
) ? (n
) : (nb_sectors
);
1374 return bs
->drv
->bdrv_is_allocated(bs
, sector_num
, nb_sectors
, pnum
);
1377 void bdrv_mon_event(const BlockDriverState
*bdrv
,
1378 BlockMonEventAction action
, int is_read
)
1381 const char *action_str
;
1384 case BDRV_ACTION_REPORT
:
1385 action_str
= "report";
1387 case BDRV_ACTION_IGNORE
:
1388 action_str
= "ignore";
1390 case BDRV_ACTION_STOP
:
1391 action_str
= "stop";
1397 data
= qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1400 is_read
? "read" : "write");
1401 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR
, data
);
1403 qobject_decref(data
);
1406 static void bdrv_print_dict(QObject
*obj
, void *opaque
)
1409 Monitor
*mon
= opaque
;
1411 bs_dict
= qobject_to_qdict(obj
);
1413 monitor_printf(mon
, "%s: type=%s removable=%d",
1414 qdict_get_str(bs_dict
, "device"),
1415 qdict_get_str(bs_dict
, "type"),
1416 qdict_get_bool(bs_dict
, "removable"));
1418 if (qdict_get_bool(bs_dict
, "removable")) {
1419 monitor_printf(mon
, " locked=%d", qdict_get_bool(bs_dict
, "locked"));
1422 if (qdict_haskey(bs_dict
, "inserted")) {
1423 QDict
*qdict
= qobject_to_qdict(qdict_get(bs_dict
, "inserted"));
1425 monitor_printf(mon
, " file=");
1426 monitor_print_filename(mon
, qdict_get_str(qdict
, "file"));
1427 if (qdict_haskey(qdict
, "backing_file")) {
1428 monitor_printf(mon
, " backing_file=");
1429 monitor_print_filename(mon
, qdict_get_str(qdict
, "backing_file"));
1431 monitor_printf(mon
, " ro=%d drv=%s encrypted=%d",
1432 qdict_get_bool(qdict
, "ro"),
1433 qdict_get_str(qdict
, "drv"),
1434 qdict_get_bool(qdict
, "encrypted"));
1436 monitor_printf(mon
, " [not inserted]");
1439 monitor_printf(mon
, "\n");
1442 void bdrv_info_print(Monitor
*mon
, const QObject
*data
)
1444 qlist_iter(qobject_to_qlist(data
), bdrv_print_dict
, mon
);
1448 * bdrv_info(): Block devices information
1450 * Each block device information is stored in a QDict and the
1451 * returned QObject is a QList of all devices.
1453 * The QDict contains the following:
1455 * - "device": device name
1456 * - "type": device type
1457 * - "removable": true if the device is removable, false otherwise
1458 * - "locked": true if the device is locked, false otherwise
1459 * - "inserted": only present if the device is inserted, it is a QDict
1460 * containing the following:
1461 * - "file": device file name
1462 * - "ro": true if read-only, false otherwise
1463 * - "drv": driver format name
1464 * - "backing_file": backing file name if one is used
1465 * - "encrypted": true if encrypted, false otherwise
1469 * [ { "device": "ide0-hd0", "type": "hd", "removable": false, "locked": false,
1470 * "inserted": { "file": "/tmp/foobar", "ro": false, "drv": "qcow2" } },
1471 * { "device": "floppy0", "type": "floppy", "removable": true,
1472 * "locked": false } ]
1474 void bdrv_info(Monitor
*mon
, QObject
**ret_data
)
1477 BlockDriverState
*bs
;
1479 bs_list
= qlist_new();
1481 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1483 const char *type
= "unknown";
1489 case BDRV_TYPE_CDROM
:
1492 case BDRV_TYPE_FLOPPY
:
1497 bs_obj
= qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1498 "'removable': %i, 'locked': %i }",
1499 bs
->device_name
, type
, bs
->removable
,
1504 QDict
*bs_dict
= qobject_to_qdict(bs_obj
);
1506 obj
= qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1507 "'encrypted': %i }",
1508 bs
->filename
, bs
->read_only
,
1509 bs
->drv
->format_name
,
1510 bdrv_is_encrypted(bs
));
1511 if (bs
->backing_file
[0] != '\0') {
1512 QDict
*qdict
= qobject_to_qdict(obj
);
1513 qdict_put(qdict
, "backing_file",
1514 qstring_from_str(bs
->backing_file
));
1517 qdict_put_obj(bs_dict
, "inserted", obj
);
1519 qlist_append_obj(bs_list
, bs_obj
);
1522 *ret_data
= QOBJECT(bs_list
);
1525 static void bdrv_stats_iter(QObject
*data
, void *opaque
)
1528 Monitor
*mon
= opaque
;
1530 qdict
= qobject_to_qdict(data
);
1531 monitor_printf(mon
, "%s:", qdict_get_str(qdict
, "device"));
1533 qdict
= qobject_to_qdict(qdict_get(qdict
, "stats"));
1534 monitor_printf(mon
, " rd_bytes=%" PRId64
1535 " wr_bytes=%" PRId64
1536 " rd_operations=%" PRId64
1537 " wr_operations=%" PRId64
1539 qdict_get_int(qdict
, "rd_bytes"),
1540 qdict_get_int(qdict
, "wr_bytes"),
1541 qdict_get_int(qdict
, "rd_operations"),
1542 qdict_get_int(qdict
, "wr_operations"));
1545 void bdrv_stats_print(Monitor
*mon
, const QObject
*data
)
1547 qlist_iter(qobject_to_qlist(data
), bdrv_stats_iter
, mon
);
1550 static QObject
* bdrv_info_stats_bs(BlockDriverState
*bs
)
1555 res
= qobject_from_jsonf("{ 'stats': {"
1556 "'rd_bytes': %" PRId64
","
1557 "'wr_bytes': %" PRId64
","
1558 "'rd_operations': %" PRId64
","
1559 "'wr_operations': %" PRId64
","
1560 "'wr_highest_offset': %" PRId64
1562 bs
->rd_bytes
, bs
->wr_bytes
,
1563 bs
->rd_ops
, bs
->wr_ops
,
1564 bs
->wr_highest_sector
* 512);
1565 dict
= qobject_to_qdict(res
);
1567 if (*bs
->device_name
) {
1568 qdict_put(dict
, "device", qstring_from_str(bs
->device_name
));
1572 QObject
*parent
= bdrv_info_stats_bs(bs
->file
);
1573 qdict_put_obj(dict
, "parent", parent
);
1580 * bdrv_info_stats(): show block device statistics
1582 * Each device statistic information is stored in a QDict and
1583 * the returned QObject is a QList of all devices.
1585 * The QDict contains the following:
1587 * - "device": device name
1588 * - "stats": A QDict with the statistics information, it contains:
1589 * - "rd_bytes": bytes read
1590 * - "wr_bytes": bytes written
1591 * - "rd_operations": read operations
1592 * - "wr_operations": write operations
1593 * - "wr_highest_offset": Highest offset of a sector written since the
1594 * BlockDriverState has been opened
1595 * - "parent": A QDict recursively holding the statistics of the underlying
1596 * protocol (e.g. the host file for a qcow2 image). If there is no
1597 * underlying protocol, this field is omitted.
1601 * [ { "device": "ide0-hd0",
1602 * "stats": { "rd_bytes": 512,
1604 * "rd_operations": 1,
1605 * "wr_operations": 0,
1606 * "wr_highest_offset": 0 },
1608 * "stats": { "rd_bytes": 1024,
1610 * "rd_operations": 2,
1611 * "wr_operations": 0,
1612 * "wr_highest_offset": 0,
1614 * { "device": "ide1-cd0",
1615 * "stats": { "rd_bytes": 0,
1617 * "rd_operations": 0,
1618 * "wr_operations": 0,
1619 * "wr_highest_offset": 0 } },
1621 void bdrv_info_stats(Monitor
*mon
, QObject
**ret_data
)
1625 BlockDriverState
*bs
;
1627 devices
= qlist_new();
1629 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1630 obj
= bdrv_info_stats_bs(bs
);
1631 qlist_append_obj(devices
, obj
);
1634 *ret_data
= QOBJECT(devices
);
1637 const char *bdrv_get_encrypted_filename(BlockDriverState
*bs
)
1639 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1640 return bs
->backing_file
;
1641 else if (bs
->encrypted
)
1642 return bs
->filename
;
1647 void bdrv_get_backing_filename(BlockDriverState
*bs
,
1648 char *filename
, int filename_size
)
1650 if (!bs
->backing_file
) {
1651 pstrcpy(filename
, filename_size
, "");
1653 pstrcpy(filename
, filename_size
, bs
->backing_file
);
1657 int bdrv_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
1658 const uint8_t *buf
, int nb_sectors
)
1660 BlockDriver
*drv
= bs
->drv
;
1663 if (!drv
->bdrv_write_compressed
)
1665 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1668 if (bs
->dirty_bitmap
) {
1669 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1672 return drv
->bdrv_write_compressed(bs
, sector_num
, buf
, nb_sectors
);
1675 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1677 BlockDriver
*drv
= bs
->drv
;
1680 if (!drv
->bdrv_get_info
)
1682 memset(bdi
, 0, sizeof(*bdi
));
1683 return drv
->bdrv_get_info(bs
, bdi
);
1686 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
1687 int64_t pos
, int size
)
1689 BlockDriver
*drv
= bs
->drv
;
1692 if (!drv
->bdrv_save_vmstate
)
1694 return drv
->bdrv_save_vmstate(bs
, buf
, pos
, size
);
1697 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
1698 int64_t pos
, int size
)
1700 BlockDriver
*drv
= bs
->drv
;
1703 if (!drv
->bdrv_load_vmstate
)
1705 return drv
->bdrv_load_vmstate(bs
, buf
, pos
, size
);
1708 void bdrv_debug_event(BlockDriverState
*bs
, BlkDebugEvent event
)
1710 BlockDriver
*drv
= bs
->drv
;
1712 if (!drv
|| !drv
->bdrv_debug_event
) {
1716 return drv
->bdrv_debug_event(bs
, event
);
1720 /**************************************************************/
1721 /* handling of snapshots */
1723 int bdrv_snapshot_create(BlockDriverState
*bs
,
1724 QEMUSnapshotInfo
*sn_info
)
1726 BlockDriver
*drv
= bs
->drv
;
1729 if (!drv
->bdrv_snapshot_create
)
1731 return drv
->bdrv_snapshot_create(bs
, sn_info
);
1734 int bdrv_snapshot_goto(BlockDriverState
*bs
,
1735 const char *snapshot_id
)
1737 BlockDriver
*drv
= bs
->drv
;
1740 if (!drv
->bdrv_snapshot_goto
)
1742 return drv
->bdrv_snapshot_goto(bs
, snapshot_id
);
1745 int bdrv_snapshot_delete(BlockDriverState
*bs
, const char *snapshot_id
)
1747 BlockDriver
*drv
= bs
->drv
;
1750 if (!drv
->bdrv_snapshot_delete
)
1752 return drv
->bdrv_snapshot_delete(bs
, snapshot_id
);
1755 int bdrv_snapshot_list(BlockDriverState
*bs
,
1756 QEMUSnapshotInfo
**psn_info
)
1758 BlockDriver
*drv
= bs
->drv
;
1761 if (!drv
->bdrv_snapshot_list
)
1763 return drv
->bdrv_snapshot_list(bs
, psn_info
);
1766 #define NB_SUFFIXES 4
1768 char *get_human_readable_size(char *buf
, int buf_size
, int64_t size
)
1770 static const char suffixes
[NB_SUFFIXES
] = "KMGT";
1775 snprintf(buf
, buf_size
, "%" PRId64
, size
);
1778 for(i
= 0; i
< NB_SUFFIXES
; i
++) {
1779 if (size
< (10 * base
)) {
1780 snprintf(buf
, buf_size
, "%0.1f%c",
1781 (double)size
/ base
,
1784 } else if (size
< (1000 * base
) || i
== (NB_SUFFIXES
- 1)) {
1785 snprintf(buf
, buf_size
, "%" PRId64
"%c",
1786 ((size
+ (base
>> 1)) / base
),
1796 char *bdrv_snapshot_dump(char *buf
, int buf_size
, QEMUSnapshotInfo
*sn
)
1798 char buf1
[128], date_buf
[128], clock_buf
[128];
1808 snprintf(buf
, buf_size
,
1809 "%-10s%-20s%7s%20s%15s",
1810 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1814 ptm
= localtime(&ti
);
1815 strftime(date_buf
, sizeof(date_buf
),
1816 "%Y-%m-%d %H:%M:%S", ptm
);
1818 localtime_r(&ti
, &tm
);
1819 strftime(date_buf
, sizeof(date_buf
),
1820 "%Y-%m-%d %H:%M:%S", &tm
);
1822 secs
= sn
->vm_clock_nsec
/ 1000000000;
1823 snprintf(clock_buf
, sizeof(clock_buf
),
1824 "%02d:%02d:%02d.%03d",
1826 (int)((secs
/ 60) % 60),
1828 (int)((sn
->vm_clock_nsec
/ 1000000) % 1000));
1829 snprintf(buf
, buf_size
,
1830 "%-10s%-20s%7s%20s%15s",
1831 sn
->id_str
, sn
->name
,
1832 get_human_readable_size(buf1
, sizeof(buf1
), sn
->vm_state_size
),
1840 /**************************************************************/
1843 BlockDriverAIOCB
*bdrv_aio_readv(BlockDriverState
*bs
, int64_t sector_num
,
1844 QEMUIOVector
*qiov
, int nb_sectors
,
1845 BlockDriverCompletionFunc
*cb
, void *opaque
)
1847 BlockDriver
*drv
= bs
->drv
;
1848 BlockDriverAIOCB
*ret
;
1852 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1855 ret
= drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
1859 /* Update stats even though technically transfer has not happened. */
1860 bs
->rd_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
1867 BlockDriverAIOCB
*bdrv_aio_writev(BlockDriverState
*bs
, int64_t sector_num
,
1868 QEMUIOVector
*qiov
, int nb_sectors
,
1869 BlockDriverCompletionFunc
*cb
, void *opaque
)
1871 BlockDriver
*drv
= bs
->drv
;
1872 BlockDriverAIOCB
*ret
;
1878 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1881 if (bs
->dirty_bitmap
) {
1882 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1885 ret
= drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
1889 /* Update stats even though technically transfer has not happened. */
1890 bs
->wr_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
1892 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1893 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1901 typedef struct MultiwriteCB
{
1906 BlockDriverCompletionFunc
*cb
;
1908 QEMUIOVector
*free_qiov
;
1913 static void multiwrite_user_cb(MultiwriteCB
*mcb
)
1917 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
1918 mcb
->callbacks
[i
].cb(mcb
->callbacks
[i
].opaque
, mcb
->error
);
1919 if (mcb
->callbacks
[i
].free_qiov
) {
1920 qemu_iovec_destroy(mcb
->callbacks
[i
].free_qiov
);
1922 qemu_free(mcb
->callbacks
[i
].free_qiov
);
1923 qemu_vfree(mcb
->callbacks
[i
].free_buf
);
1927 static void multiwrite_cb(void *opaque
, int ret
)
1929 MultiwriteCB
*mcb
= opaque
;
1931 if (ret
< 0 && !mcb
->error
) {
1933 multiwrite_user_cb(mcb
);
1936 mcb
->num_requests
--;
1937 if (mcb
->num_requests
== 0) {
1938 if (mcb
->error
== 0) {
1939 multiwrite_user_cb(mcb
);
1945 static int multiwrite_req_compare(const void *a
, const void *b
)
1947 const BlockRequest
*req1
= a
, *req2
= b
;
1950 * Note that we can't simply subtract req2->sector from req1->sector
1951 * here as that could overflow the return value.
1953 if (req1
->sector
> req2
->sector
) {
1955 } else if (req1
->sector
< req2
->sector
) {
1963 * Takes a bunch of requests and tries to merge them. Returns the number of
1964 * requests that remain after merging.
1966 static int multiwrite_merge(BlockDriverState
*bs
, BlockRequest
*reqs
,
1967 int num_reqs
, MultiwriteCB
*mcb
)
1971 // Sort requests by start sector
1972 qsort(reqs
, num_reqs
, sizeof(*reqs
), &multiwrite_req_compare
);
1974 // Check if adjacent requests touch the same clusters. If so, combine them,
1975 // filling up gaps with zero sectors.
1977 for (i
= 1; i
< num_reqs
; i
++) {
1979 int64_t oldreq_last
= reqs
[outidx
].sector
+ reqs
[outidx
].nb_sectors
;
1981 // This handles the cases that are valid for all block drivers, namely
1982 // exactly sequential writes and overlapping writes.
1983 if (reqs
[i
].sector
<= oldreq_last
) {
1987 // The block driver may decide that it makes sense to combine requests
1988 // even if there is a gap of some sectors between them. In this case,
1989 // the gap is filled with zeros (therefore only applicable for yet
1990 // unused space in format like qcow2).
1991 if (!merge
&& bs
->drv
->bdrv_merge_requests
) {
1992 merge
= bs
->drv
->bdrv_merge_requests(bs
, &reqs
[outidx
], &reqs
[i
]);
1995 if (reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1 > IOV_MAX
) {
2001 QEMUIOVector
*qiov
= qemu_mallocz(sizeof(*qiov
));
2002 qemu_iovec_init(qiov
,
2003 reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1);
2005 // Add the first request to the merged one. If the requests are
2006 // overlapping, drop the last sectors of the first request.
2007 size
= (reqs
[i
].sector
- reqs
[outidx
].sector
) << 9;
2008 qemu_iovec_concat(qiov
, reqs
[outidx
].qiov
, size
);
2010 // We might need to add some zeros between the two requests
2011 if (reqs
[i
].sector
> oldreq_last
) {
2012 size_t zero_bytes
= (reqs
[i
].sector
- oldreq_last
) << 9;
2013 uint8_t *buf
= qemu_blockalign(bs
, zero_bytes
);
2014 memset(buf
, 0, zero_bytes
);
2015 qemu_iovec_add(qiov
, buf
, zero_bytes
);
2016 mcb
->callbacks
[i
].free_buf
= buf
;
2019 // Add the second request
2020 qemu_iovec_concat(qiov
, reqs
[i
].qiov
, reqs
[i
].qiov
->size
);
2022 reqs
[outidx
].nb_sectors
+= reqs
[i
].nb_sectors
;
2023 reqs
[outidx
].qiov
= qiov
;
2025 mcb
->callbacks
[i
].free_qiov
= reqs
[outidx
].qiov
;
2028 reqs
[outidx
].sector
= reqs
[i
].sector
;
2029 reqs
[outidx
].nb_sectors
= reqs
[i
].nb_sectors
;
2030 reqs
[outidx
].qiov
= reqs
[i
].qiov
;
2038 * Submit multiple AIO write requests at once.
2040 * On success, the function returns 0 and all requests in the reqs array have
2041 * been submitted. In error case this function returns -1, and any of the
2042 * requests may or may not be submitted yet. In particular, this means that the
2043 * callback will be called for some of the requests, for others it won't. The
2044 * caller must check the error field of the BlockRequest to wait for the right
2045 * callbacks (if error != 0, no callback will be called).
2047 * The implementation may modify the contents of the reqs array, e.g. to merge
2048 * requests. However, the fields opaque and error are left unmodified as they
2049 * are used to signal failure for a single request to the caller.
2051 int bdrv_aio_multiwrite(BlockDriverState
*bs
, BlockRequest
*reqs
, int num_reqs
)
2053 BlockDriverAIOCB
*acb
;
2057 if (num_reqs
== 0) {
2061 // Create MultiwriteCB structure
2062 mcb
= qemu_mallocz(sizeof(*mcb
) + num_reqs
* sizeof(*mcb
->callbacks
));
2063 mcb
->num_requests
= 0;
2064 mcb
->num_callbacks
= num_reqs
;
2066 for (i
= 0; i
< num_reqs
; i
++) {
2067 mcb
->callbacks
[i
].cb
= reqs
[i
].cb
;
2068 mcb
->callbacks
[i
].opaque
= reqs
[i
].opaque
;
2071 // Check for mergable requests
2072 num_reqs
= multiwrite_merge(bs
, reqs
, num_reqs
, mcb
);
2074 // Run the aio requests
2075 for (i
= 0; i
< num_reqs
; i
++) {
2076 acb
= bdrv_aio_writev(bs
, reqs
[i
].sector
, reqs
[i
].qiov
,
2077 reqs
[i
].nb_sectors
, multiwrite_cb
, mcb
);
2080 // We can only fail the whole thing if no request has been
2081 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2082 // complete and report the error in the callback.
2083 if (mcb
->num_requests
== 0) {
2084 reqs
[i
].error
= -EIO
;
2087 mcb
->num_requests
++;
2088 multiwrite_cb(mcb
, -EIO
);
2092 mcb
->num_requests
++;
2103 BlockDriverAIOCB
*bdrv_aio_flush(BlockDriverState
*bs
,
2104 BlockDriverCompletionFunc
*cb
, void *opaque
)
2106 BlockDriver
*drv
= bs
->drv
;
2108 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2109 return bdrv_aio_noop_em(bs
, cb
, opaque
);
2114 return drv
->bdrv_aio_flush(bs
, cb
, opaque
);
2117 void bdrv_aio_cancel(BlockDriverAIOCB
*acb
)
2119 acb
->pool
->cancel(acb
);
2123 /**************************************************************/
2124 /* async block device emulation */
2126 typedef struct BlockDriverAIOCBSync
{
2127 BlockDriverAIOCB common
;
2130 /* vector translation state */
2134 } BlockDriverAIOCBSync
;
2136 static void bdrv_aio_cancel_em(BlockDriverAIOCB
*blockacb
)
2138 BlockDriverAIOCBSync
*acb
=
2139 container_of(blockacb
, BlockDriverAIOCBSync
, common
);
2140 qemu_bh_delete(acb
->bh
);
2142 qemu_aio_release(acb
);
2145 static AIOPool bdrv_em_aio_pool
= {
2146 .aiocb_size
= sizeof(BlockDriverAIOCBSync
),
2147 .cancel
= bdrv_aio_cancel_em
,
2150 static void bdrv_aio_bh_cb(void *opaque
)
2152 BlockDriverAIOCBSync
*acb
= opaque
;
2155 qemu_iovec_from_buffer(acb
->qiov
, acb
->bounce
, acb
->qiov
->size
);
2156 qemu_vfree(acb
->bounce
);
2157 acb
->common
.cb(acb
->common
.opaque
, acb
->ret
);
2158 qemu_bh_delete(acb
->bh
);
2160 qemu_aio_release(acb
);
2163 static BlockDriverAIOCB
*bdrv_aio_rw_vector(BlockDriverState
*bs
,
2167 BlockDriverCompletionFunc
*cb
,
2172 BlockDriverAIOCBSync
*acb
;
2174 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2175 acb
->is_write
= is_write
;
2177 acb
->bounce
= qemu_blockalign(bs
, qiov
->size
);
2180 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2183 qemu_iovec_to_buffer(acb
->qiov
, acb
->bounce
);
2184 acb
->ret
= bdrv_write(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2186 acb
->ret
= bdrv_read(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2189 qemu_bh_schedule(acb
->bh
);
2191 return &acb
->common
;
2194 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
2195 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2196 BlockDriverCompletionFunc
*cb
, void *opaque
)
2198 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 0);
2201 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
2202 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2203 BlockDriverCompletionFunc
*cb
, void *opaque
)
2205 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 1);
2208 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
2209 BlockDriverCompletionFunc
*cb
, void *opaque
)
2211 BlockDriverAIOCBSync
*acb
;
2213 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2214 acb
->is_write
= 1; /* don't bounce in the completion hadler */
2220 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2223 qemu_bh_schedule(acb
->bh
);
2224 return &acb
->common
;
2227 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
2228 BlockDriverCompletionFunc
*cb
, void *opaque
)
2230 BlockDriverAIOCBSync
*acb
;
2232 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2233 acb
->is_write
= 1; /* don't bounce in the completion handler */
2239 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2242 qemu_bh_schedule(acb
->bh
);
2243 return &acb
->common
;
2246 /**************************************************************/
2247 /* sync block device emulation */
2249 static void bdrv_rw_em_cb(void *opaque
, int ret
)
2251 *(int *)opaque
= ret
;
2254 #define NOT_DONE 0x7fffffff
2256 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
2257 uint8_t *buf
, int nb_sectors
)
2260 BlockDriverAIOCB
*acb
;
2264 async_context_push();
2266 async_ret
= NOT_DONE
;
2267 iov
.iov_base
= (void *)buf
;
2268 iov
.iov_len
= nb_sectors
* 512;
2269 qemu_iovec_init_external(&qiov
, &iov
, 1);
2270 acb
= bdrv_aio_readv(bs
, sector_num
, &qiov
, nb_sectors
,
2271 bdrv_rw_em_cb
, &async_ret
);
2277 while (async_ret
== NOT_DONE
) {
2283 async_context_pop();
2287 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
2288 const uint8_t *buf
, int nb_sectors
)
2291 BlockDriverAIOCB
*acb
;
2295 async_context_push();
2297 async_ret
= NOT_DONE
;
2298 iov
.iov_base
= (void *)buf
;
2299 iov
.iov_len
= nb_sectors
* 512;
2300 qemu_iovec_init_external(&qiov
, &iov
, 1);
2301 acb
= bdrv_aio_writev(bs
, sector_num
, &qiov
, nb_sectors
,
2302 bdrv_rw_em_cb
, &async_ret
);
2307 while (async_ret
== NOT_DONE
) {
2312 async_context_pop();
2316 void bdrv_init(void)
2318 module_call_init(MODULE_INIT_BLOCK
);
2321 void bdrv_init_with_whitelist(void)
2323 use_bdrv_whitelist
= 1;
2327 void *qemu_aio_get(AIOPool
*pool
, BlockDriverState
*bs
,
2328 BlockDriverCompletionFunc
*cb
, void *opaque
)
2330 BlockDriverAIOCB
*acb
;
2332 if (pool
->free_aiocb
) {
2333 acb
= pool
->free_aiocb
;
2334 pool
->free_aiocb
= acb
->next
;
2336 acb
= qemu_mallocz(pool
->aiocb_size
);
2341 acb
->opaque
= opaque
;
2345 void qemu_aio_release(void *p
)
2347 BlockDriverAIOCB
*acb
= (BlockDriverAIOCB
*)p
;
2348 AIOPool
*pool
= acb
->pool
;
2349 acb
->next
= pool
->free_aiocb
;
2350 pool
->free_aiocb
= acb
;
2353 /**************************************************************/
2354 /* removable device support */
2357 * Return TRUE if the media is present
2359 int bdrv_is_inserted(BlockDriverState
*bs
)
2361 BlockDriver
*drv
= bs
->drv
;
2365 if (!drv
->bdrv_is_inserted
)
2367 ret
= drv
->bdrv_is_inserted(bs
);
2372 * Return TRUE if the media changed since the last call to this
2373 * function. It is currently only used for floppy disks
2375 int bdrv_media_changed(BlockDriverState
*bs
)
2377 BlockDriver
*drv
= bs
->drv
;
2380 if (!drv
|| !drv
->bdrv_media_changed
)
2383 ret
= drv
->bdrv_media_changed(bs
);
2384 if (ret
== -ENOTSUP
)
2385 ret
= bs
->media_changed
;
2386 bs
->media_changed
= 0;
2391 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2393 int bdrv_eject(BlockDriverState
*bs
, int eject_flag
)
2395 BlockDriver
*drv
= bs
->drv
;
2402 if (!drv
|| !drv
->bdrv_eject
) {
2405 ret
= drv
->bdrv_eject(bs
, eject_flag
);
2407 if (ret
== -ENOTSUP
) {
2416 int bdrv_is_locked(BlockDriverState
*bs
)
2422 * Lock or unlock the media (if it is locked, the user won't be able
2423 * to eject it manually).
2425 void bdrv_set_locked(BlockDriverState
*bs
, int locked
)
2427 BlockDriver
*drv
= bs
->drv
;
2429 bs
->locked
= locked
;
2430 if (drv
&& drv
->bdrv_set_locked
) {
2431 drv
->bdrv_set_locked(bs
, locked
);
2435 /* needed for generic scsi interface */
2437 int bdrv_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
2439 BlockDriver
*drv
= bs
->drv
;
2441 if (drv
&& drv
->bdrv_ioctl
)
2442 return drv
->bdrv_ioctl(bs
, req
, buf
);
2446 BlockDriverAIOCB
*bdrv_aio_ioctl(BlockDriverState
*bs
,
2447 unsigned long int req
, void *buf
,
2448 BlockDriverCompletionFunc
*cb
, void *opaque
)
2450 BlockDriver
*drv
= bs
->drv
;
2452 if (drv
&& drv
->bdrv_aio_ioctl
)
2453 return drv
->bdrv_aio_ioctl(bs
, req
, buf
, cb
, opaque
);
2459 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
2461 return qemu_memalign((bs
&& bs
->buffer_alignment
) ? bs
->buffer_alignment
: 512, size
);
2464 void bdrv_set_dirty_tracking(BlockDriverState
*bs
, int enable
)
2466 int64_t bitmap_size
;
2468 bs
->dirty_count
= 0;
2470 if (!bs
->dirty_bitmap
) {
2471 bitmap_size
= (bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
) +
2472 BDRV_SECTORS_PER_DIRTY_CHUNK
* 8 - 1;
2473 bitmap_size
/= BDRV_SECTORS_PER_DIRTY_CHUNK
* 8;
2475 bs
->dirty_bitmap
= qemu_mallocz(bitmap_size
);
2478 if (bs
->dirty_bitmap
) {
2479 qemu_free(bs
->dirty_bitmap
);
2480 bs
->dirty_bitmap
= NULL
;
2485 int bdrv_get_dirty(BlockDriverState
*bs
, int64_t sector
)
2487 int64_t chunk
= sector
/ (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK
;
2489 if (bs
->dirty_bitmap
&&
2490 (sector
<< BDRV_SECTOR_BITS
) < bdrv_getlength(bs
)) {
2491 return bs
->dirty_bitmap
[chunk
/ (sizeof(unsigned long) * 8)] &
2492 (1 << (chunk
% (sizeof(unsigned long) * 8)));
2498 void bdrv_reset_dirty(BlockDriverState
*bs
, int64_t cur_sector
,
2501 set_dirty_bitmap(bs
, cur_sector
, nr_sectors
, 0);
2504 int64_t bdrv_get_dirty_count(BlockDriverState
*bs
)
2506 return bs
->dirty_count
;