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
);
60 static QTAILQ_HEAD(, BlockDriverState
) bdrv_states
=
61 QTAILQ_HEAD_INITIALIZER(bdrv_states
);
63 static QLIST_HEAD(, BlockDriver
) bdrv_drivers
=
64 QLIST_HEAD_INITIALIZER(bdrv_drivers
);
66 /* If non-zero, use only whitelisted block drivers */
67 static int use_bdrv_whitelist
;
69 int path_is_absolute(const char *path
)
73 /* specific case for names like: "\\.\d:" */
74 if (*path
== '/' || *path
== '\\')
77 p
= strchr(path
, ':');
83 return (*p
== '/' || *p
== '\\');
89 /* if filename is absolute, just copy it to dest. Otherwise, build a
90 path to it by considering it is relative to base_path. URL are
92 void path_combine(char *dest
, int dest_size
,
93 const char *base_path
,
101 if (path_is_absolute(filename
)) {
102 pstrcpy(dest
, dest_size
, filename
);
104 p
= strchr(base_path
, ':');
109 p1
= strrchr(base_path
, '/');
113 p2
= strrchr(base_path
, '\\');
125 if (len
> dest_size
- 1)
127 memcpy(dest
, base_path
, len
);
129 pstrcat(dest
, dest_size
, filename
);
133 void bdrv_register(BlockDriver
*bdrv
)
135 if (!bdrv
->bdrv_aio_readv
) {
136 /* add AIO emulation layer */
137 bdrv
->bdrv_aio_readv
= bdrv_aio_readv_em
;
138 bdrv
->bdrv_aio_writev
= bdrv_aio_writev_em
;
139 } else if (!bdrv
->bdrv_read
) {
140 /* add synchronous IO emulation layer */
141 bdrv
->bdrv_read
= bdrv_read_em
;
142 bdrv
->bdrv_write
= bdrv_write_em
;
145 if (!bdrv
->bdrv_aio_flush
)
146 bdrv
->bdrv_aio_flush
= bdrv_aio_flush_em
;
148 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
151 /* create a new block device (by default it is empty) */
152 BlockDriverState
*bdrv_new(const char *device_name
)
154 BlockDriverState
*bs
;
156 bs
= qemu_mallocz(sizeof(BlockDriverState
));
157 pstrcpy(bs
->device_name
, sizeof(bs
->device_name
), device_name
);
158 if (device_name
[0] != '\0') {
159 QTAILQ_INSERT_TAIL(&bdrv_states
, bs
, list
);
164 BlockDriver
*bdrv_find_format(const char *format_name
)
167 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
168 if (!strcmp(drv1
->format_name
, format_name
)) {
175 static int bdrv_is_whitelisted(BlockDriver
*drv
)
177 static const char *whitelist
[] = {
178 CONFIG_BDRV_WHITELIST
183 return 1; /* no whitelist, anything goes */
185 for (p
= whitelist
; *p
; p
++) {
186 if (!strcmp(drv
->format_name
, *p
)) {
193 BlockDriver
*bdrv_find_whitelisted_format(const char *format_name
)
195 BlockDriver
*drv
= bdrv_find_format(format_name
);
196 return drv
&& bdrv_is_whitelisted(drv
) ? drv
: NULL
;
199 int bdrv_create(BlockDriver
*drv
, const char* filename
,
200 QEMUOptionParameter
*options
)
202 if (!drv
->bdrv_create
)
205 return drv
->bdrv_create(filename
, options
);
208 int bdrv_create_file(const char* filename
, QEMUOptionParameter
*options
)
212 drv
= bdrv_find_protocol(filename
);
214 drv
= bdrv_find_format("file");
217 return bdrv_create(drv
, filename
, options
);
221 void get_tmp_filename(char *filename
, int size
)
223 char temp_dir
[MAX_PATH
];
225 GetTempPath(MAX_PATH
, temp_dir
);
226 GetTempFileName(temp_dir
, "qem", 0, filename
);
229 void get_tmp_filename(char *filename
, int size
)
233 /* XXX: race condition possible */
234 tmpdir
= getenv("TMPDIR");
237 snprintf(filename
, size
, "%s/vl.XXXXXX", tmpdir
);
238 fd
= mkstemp(filename
);
244 static int is_windows_drive_prefix(const char *filename
)
246 return (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
247 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
251 int is_windows_drive(const char *filename
)
253 if (is_windows_drive_prefix(filename
) &&
256 if (strstart(filename
, "\\\\.\\", NULL
) ||
257 strstart(filename
, "//./", NULL
))
264 * Detect host devices. By convention, /dev/cdrom[N] is always
265 * recognized as a host CDROM.
267 static BlockDriver
*find_hdev_driver(const char *filename
)
269 int score_max
= 0, score
;
270 BlockDriver
*drv
= NULL
, *d
;
272 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
273 if (d
->bdrv_probe_device
) {
274 score
= d
->bdrv_probe_device(filename
);
275 if (score
> score_max
) {
285 BlockDriver
*bdrv_find_protocol(const char *filename
)
293 /* TODO Drivers without bdrv_file_open must be specified explicitly */
296 is_drive
= is_windows_drive(filename
) ||
297 is_windows_drive_prefix(filename
);
301 p
= strchr(filename
, ':');
302 if (!p
|| is_drive
) {
303 drv1
= find_hdev_driver(filename
);
305 drv1
= bdrv_find_format("file");
310 if (len
> sizeof(protocol
) - 1)
311 len
= sizeof(protocol
) - 1;
312 memcpy(protocol
, filename
, len
);
313 protocol
[len
] = '\0';
314 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
315 if (drv1
->protocol_name
&&
316 !strcmp(drv1
->protocol_name
, protocol
)) {
323 static BlockDriver
*find_image_format(const char *filename
)
325 int ret
, score
, score_max
;
326 BlockDriver
*drv1
, *drv
;
328 BlockDriverState
*bs
;
330 ret
= bdrv_file_open(&bs
, filename
, 0);
334 /* Return the raw BlockDriver * to scsi-generic devices */
336 return bdrv_find_format("raw");
338 ret
= bdrv_pread(bs
, 0, buf
, sizeof(buf
));
346 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
347 if (drv1
->bdrv_probe
) {
348 score
= drv1
->bdrv_probe(buf
, ret
, filename
);
349 if (score
> score_max
) {
359 * Set the current 'total_sectors' value
361 static int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
363 BlockDriver
*drv
= bs
->drv
;
365 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
369 /* query actual device if possible, otherwise just trust the hint */
370 if (drv
->bdrv_getlength
) {
371 int64_t length
= drv
->bdrv_getlength(bs
);
375 hint
= length
>> BDRV_SECTOR_BITS
;
378 bs
->total_sectors
= hint
;
383 * Common part for opening disk images and files
385 static int bdrv_open_common(BlockDriverState
*bs
, const char *filename
,
386 int flags
, BlockDriver
*drv
)
393 bs
->total_sectors
= 0;
394 bs
->is_temporary
= 0;
397 bs
->open_flags
= flags
;
398 /* buffer_alignment defaulted to 512, drivers can change this value */
399 bs
->buffer_alignment
= 512;
401 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
403 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
)) {
408 bs
->opaque
= qemu_mallocz(drv
->instance_size
);
411 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
412 * write cache to the guest. We do need the fdatasync to flush
413 * out transactions for block allocations, and we maybe have a
414 * volatile write cache in our backing device to deal with.
416 if (flags
& (BDRV_O_CACHE_WB
|BDRV_O_NOCACHE
))
417 bs
->enable_write_cache
= 1;
420 * Clear flags that are internal to the block layer before opening the
423 open_flags
= flags
& ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
426 * Snapshots should be writeable.
428 if (bs
->is_temporary
) {
429 open_flags
|= BDRV_O_RDWR
;
432 /* Open the image, either directly or using a protocol */
433 if (drv
->bdrv_file_open
) {
434 ret
= drv
->bdrv_file_open(bs
, filename
, open_flags
);
436 ret
= bdrv_file_open(&bs
->file
, filename
, open_flags
);
438 ret
= drv
->bdrv_open(bs
, open_flags
);
446 bs
->keep_read_only
= bs
->read_only
= !(open_flags
& BDRV_O_RDWR
);
448 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
454 if (bs
->is_temporary
) {
462 bdrv_delete(bs
->file
);
465 qemu_free(bs
->opaque
);
472 * Opens a file using a protocol (file, host_device, nbd, ...)
474 int bdrv_file_open(BlockDriverState
**pbs
, const char *filename
, int flags
)
476 BlockDriverState
*bs
;
480 drv
= bdrv_find_protocol(filename
);
486 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
497 * Opens a disk image (raw, qcow2, vmdk, ...)
499 int bdrv_open(BlockDriverState
*bs
, const char *filename
, int flags
,
504 if (flags
& BDRV_O_SNAPSHOT
) {
505 BlockDriverState
*bs1
;
508 BlockDriver
*bdrv_qcow2
;
509 QEMUOptionParameter
*options
;
510 char tmp_filename
[PATH_MAX
];
511 char backing_filename
[PATH_MAX
];
513 /* if snapshot, we create a temporary backing file and open it
514 instead of opening 'filename' directly */
516 /* if there is a backing file, use it */
518 ret
= bdrv_open(bs1
, filename
, 0, drv
);
523 total_size
= bdrv_getlength(bs1
) >> BDRV_SECTOR_BITS
;
525 if (bs1
->drv
&& bs1
->drv
->protocol_name
)
530 get_tmp_filename(tmp_filename
, sizeof(tmp_filename
));
532 /* Real path is meaningless for protocols */
534 snprintf(backing_filename
, sizeof(backing_filename
),
536 else if (!realpath(filename
, backing_filename
))
539 bdrv_qcow2
= bdrv_find_format("qcow2");
540 options
= parse_option_parameters("", bdrv_qcow2
->create_options
, NULL
);
542 set_option_parameter_int(options
, BLOCK_OPT_SIZE
, total_size
* 512);
543 set_option_parameter(options
, BLOCK_OPT_BACKING_FILE
, backing_filename
);
545 set_option_parameter(options
, BLOCK_OPT_BACKING_FMT
,
549 ret
= bdrv_create(bdrv_qcow2
, tmp_filename
, options
);
550 free_option_parameters(options
);
555 filename
= tmp_filename
;
557 bs
->is_temporary
= 1;
560 /* Find the right image format driver */
562 drv
= find_image_format(filename
);
567 goto unlink_and_fail
;
571 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
573 goto unlink_and_fail
;
576 /* If there is a backing file, use it */
577 if ((flags
& BDRV_O_NO_BACKING
) == 0 && bs
->backing_file
[0] != '\0') {
578 char backing_filename
[PATH_MAX
];
580 BlockDriver
*back_drv
= NULL
;
582 bs
->backing_hd
= bdrv_new("");
583 path_combine(backing_filename
, sizeof(backing_filename
),
584 filename
, bs
->backing_file
);
585 if (bs
->backing_format
[0] != '\0')
586 back_drv
= bdrv_find_format(bs
->backing_format
);
588 /* backing files always opened read-only */
590 flags
& ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
592 ret
= bdrv_open(bs
->backing_hd
, backing_filename
, back_flags
, back_drv
);
597 if (bs
->is_temporary
) {
598 bs
->backing_hd
->keep_read_only
= !(flags
& BDRV_O_RDWR
);
600 /* base image inherits from "parent" */
601 bs
->backing_hd
->keep_read_only
= bs
->keep_read_only
;
605 if (!bdrv_key_required(bs
)) {
606 /* call the change callback */
607 bs
->media_changed
= 1;
609 bs
->change_cb(bs
->change_opaque
);
615 if (bs
->is_temporary
) {
621 void bdrv_close(BlockDriverState
*bs
)
624 if (bs
->backing_hd
) {
625 bdrv_delete(bs
->backing_hd
);
626 bs
->backing_hd
= NULL
;
628 bs
->drv
->bdrv_close(bs
);
629 qemu_free(bs
->opaque
);
631 if (bs
->is_temporary
) {
632 unlink(bs
->filename
);
638 if (bs
->file
!= NULL
) {
639 bdrv_close(bs
->file
);
642 /* call the change callback */
643 bs
->media_changed
= 1;
645 bs
->change_cb(bs
->change_opaque
);
649 void bdrv_delete(BlockDriverState
*bs
)
651 /* remove from list, if necessary */
652 if (bs
->device_name
[0] != '\0') {
653 QTAILQ_REMOVE(&bdrv_states
, bs
, list
);
657 if (bs
->file
!= NULL
) {
658 bdrv_delete(bs
->file
);
665 * Run consistency checks on an image
667 * Returns the number of errors or -errno when an internal error occurs
669 int bdrv_check(BlockDriverState
*bs
)
671 if (bs
->drv
->bdrv_check
== NULL
) {
675 return bs
->drv
->bdrv_check(bs
);
678 /* commit COW file into the raw image */
679 int bdrv_commit(BlockDriverState
*bs
)
681 BlockDriver
*drv
= bs
->drv
;
682 int64_t i
, total_sectors
;
683 int n
, j
, ro
, open_flags
;
684 int ret
= 0, rw_ret
= 0;
685 unsigned char sector
[512];
687 BlockDriverState
*bs_rw
, *bs_ro
;
692 if (!bs
->backing_hd
) {
696 if (bs
->backing_hd
->keep_read_only
) {
700 ro
= bs
->backing_hd
->read_only
;
701 strncpy(filename
, bs
->backing_hd
->filename
, sizeof(filename
));
702 open_flags
= bs
->backing_hd
->open_flags
;
706 bdrv_delete(bs
->backing_hd
);
707 bs
->backing_hd
= NULL
;
708 bs_rw
= bdrv_new("");
709 rw_ret
= bdrv_open(bs_rw
, filename
, open_flags
| BDRV_O_RDWR
, drv
);
712 /* try to re-open read-only */
713 bs_ro
= bdrv_new("");
714 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
, drv
);
717 /* drive not functional anymore */
721 bs
->backing_hd
= bs_ro
;
724 bs
->backing_hd
= bs_rw
;
727 total_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
728 for (i
= 0; i
< total_sectors
;) {
729 if (drv
->bdrv_is_allocated(bs
, i
, 65536, &n
)) {
730 for(j
= 0; j
< n
; j
++) {
731 if (bdrv_read(bs
, i
, sector
, 1) != 0) {
736 if (bdrv_write(bs
->backing_hd
, i
, sector
, 1) != 0) {
747 if (drv
->bdrv_make_empty
) {
748 ret
= drv
->bdrv_make_empty(bs
);
753 * Make sure all data we wrote to the backing device is actually
757 bdrv_flush(bs
->backing_hd
);
763 bdrv_delete(bs
->backing_hd
);
764 bs
->backing_hd
= NULL
;
765 bs_ro
= bdrv_new("");
766 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
, drv
);
769 /* drive not functional anymore */
773 bs
->backing_hd
= bs_ro
;
774 bs
->backing_hd
->keep_read_only
= 0;
783 * -EINVAL - backing format specified, but no file
784 * -ENOSPC - can't update the backing file because no space is left in the
786 * -ENOTSUP - format driver doesn't support changing the backing file
788 int bdrv_change_backing_file(BlockDriverState
*bs
,
789 const char *backing_file
, const char *backing_fmt
)
791 BlockDriver
*drv
= bs
->drv
;
793 if (drv
->bdrv_change_backing_file
!= NULL
) {
794 return drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
800 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
805 if (!bdrv_is_inserted(bs
))
811 len
= bdrv_getlength(bs
);
816 if ((offset
> len
) || (len
- offset
< size
))
822 static int bdrv_check_request(BlockDriverState
*bs
, int64_t sector_num
,
825 return bdrv_check_byte_request(bs
, sector_num
* 512, nb_sectors
* 512);
828 /* return < 0 if error. See bdrv_write() for the return codes */
829 int bdrv_read(BlockDriverState
*bs
, int64_t sector_num
,
830 uint8_t *buf
, int nb_sectors
)
832 BlockDriver
*drv
= bs
->drv
;
836 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
839 return drv
->bdrv_read(bs
, sector_num
, buf
, nb_sectors
);
842 static void set_dirty_bitmap(BlockDriverState
*bs
, int64_t sector_num
,
843 int nb_sectors
, int dirty
)
846 unsigned long val
, idx
, bit
;
848 start
= sector_num
/ BDRV_SECTORS_PER_DIRTY_CHUNK
;
849 end
= (sector_num
+ nb_sectors
- 1) / BDRV_SECTORS_PER_DIRTY_CHUNK
;
851 for (; start
<= end
; start
++) {
852 idx
= start
/ (sizeof(unsigned long) * 8);
853 bit
= start
% (sizeof(unsigned long) * 8);
854 val
= bs
->dirty_bitmap
[idx
];
856 if (!(val
& (1 << bit
))) {
861 if (val
& (1 << bit
)) {
866 bs
->dirty_bitmap
[idx
] = val
;
870 /* Return < 0 if error. Important errors are:
871 -EIO generic I/O error (may happen for all errors)
872 -ENOMEDIUM No media inserted.
873 -EINVAL Invalid sector number or nb_sectors
874 -EACCES Trying to write a read-only device
876 int bdrv_write(BlockDriverState
*bs
, int64_t sector_num
,
877 const uint8_t *buf
, int nb_sectors
)
879 BlockDriver
*drv
= bs
->drv
;
884 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
887 if (bs
->dirty_bitmap
) {
888 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
891 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
892 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
895 return drv
->bdrv_write(bs
, sector_num
, buf
, nb_sectors
);
898 int bdrv_pread(BlockDriverState
*bs
, int64_t offset
,
899 void *buf
, int count1
)
901 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
902 int len
, nb_sectors
, count
;
907 /* first read to align to sector start */
908 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
911 sector_num
= offset
>> BDRV_SECTOR_BITS
;
913 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
915 memcpy(buf
, tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), len
);
923 /* read the sectors "in place" */
924 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
925 if (nb_sectors
> 0) {
926 if ((ret
= bdrv_read(bs
, sector_num
, buf
, nb_sectors
)) < 0)
928 sector_num
+= nb_sectors
;
929 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
934 /* add data from the last sector */
936 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
938 memcpy(buf
, tmp_buf
, count
);
943 int bdrv_pwrite(BlockDriverState
*bs
, int64_t offset
,
944 const void *buf
, int count1
)
946 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
947 int len
, nb_sectors
, count
;
952 /* first write to align to sector start */
953 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
956 sector_num
= offset
>> BDRV_SECTOR_BITS
;
958 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
960 memcpy(tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), buf
, len
);
961 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
970 /* write the sectors "in place" */
971 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
972 if (nb_sectors
> 0) {
973 if ((ret
= bdrv_write(bs
, sector_num
, buf
, nb_sectors
)) < 0)
975 sector_num
+= nb_sectors
;
976 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
981 /* add data from the last sector */
983 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
985 memcpy(tmp_buf
, buf
, count
);
986 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
993 * Truncate file to 'offset' bytes (needed only for file protocols)
995 int bdrv_truncate(BlockDriverState
*bs
, int64_t offset
)
997 BlockDriver
*drv
= bs
->drv
;
1001 if (!drv
->bdrv_truncate
)
1005 ret
= drv
->bdrv_truncate(bs
, offset
);
1007 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
1013 * Length of a file in bytes. Return < 0 if error or unknown.
1015 int64_t bdrv_getlength(BlockDriverState
*bs
)
1017 BlockDriver
*drv
= bs
->drv
;
1021 /* Fixed size devices use the total_sectors value for speed instead of
1022 issuing a length query (like lseek) on each call. Also, legacy block
1023 drivers don't provide a bdrv_getlength function and must use
1025 if (!bs
->growable
|| !drv
->bdrv_getlength
) {
1026 return bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1028 return drv
->bdrv_getlength(bs
);
1031 /* return 0 as number of sectors if no device present or error */
1032 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
1035 length
= bdrv_getlength(bs
);
1039 length
= length
>> BDRV_SECTOR_BITS
;
1040 *nb_sectors_ptr
= length
;
1044 uint8_t boot_ind
; /* 0x80 - active */
1045 uint8_t head
; /* starting head */
1046 uint8_t sector
; /* starting sector */
1047 uint8_t cyl
; /* starting cylinder */
1048 uint8_t sys_ind
; /* What partition type */
1049 uint8_t end_head
; /* end head */
1050 uint8_t end_sector
; /* end sector */
1051 uint8_t end_cyl
; /* end cylinder */
1052 uint32_t start_sect
; /* starting sector counting from 0 */
1053 uint32_t nr_sects
; /* nr of sectors in partition */
1054 } __attribute__((packed
));
1056 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1057 static int guess_disk_lchs(BlockDriverState
*bs
,
1058 int *pcylinders
, int *pheads
, int *psectors
)
1061 int ret
, i
, heads
, sectors
, cylinders
;
1062 struct partition
*p
;
1064 uint64_t nb_sectors
;
1066 bdrv_get_geometry(bs
, &nb_sectors
);
1068 ret
= bdrv_read(bs
, 0, buf
, 1);
1071 /* test msdos magic */
1072 if (buf
[510] != 0x55 || buf
[511] != 0xaa)
1074 for(i
= 0; i
< 4; i
++) {
1075 p
= ((struct partition
*)(buf
+ 0x1be)) + i
;
1076 nr_sects
= le32_to_cpu(p
->nr_sects
);
1077 if (nr_sects
&& p
->end_head
) {
1078 /* We make the assumption that the partition terminates on
1079 a cylinder boundary */
1080 heads
= p
->end_head
+ 1;
1081 sectors
= p
->end_sector
& 63;
1084 cylinders
= nb_sectors
/ (heads
* sectors
);
1085 if (cylinders
< 1 || cylinders
> 16383)
1088 *psectors
= sectors
;
1089 *pcylinders
= cylinders
;
1091 printf("guessed geometry: LCHS=%d %d %d\n",
1092 cylinders
, heads
, sectors
);
1100 void bdrv_guess_geometry(BlockDriverState
*bs
, int *pcyls
, int *pheads
, int *psecs
)
1102 int translation
, lba_detected
= 0;
1103 int cylinders
, heads
, secs
;
1104 uint64_t nb_sectors
;
1106 /* if a geometry hint is available, use it */
1107 bdrv_get_geometry(bs
, &nb_sectors
);
1108 bdrv_get_geometry_hint(bs
, &cylinders
, &heads
, &secs
);
1109 translation
= bdrv_get_translation_hint(bs
);
1110 if (cylinders
!= 0) {
1115 if (guess_disk_lchs(bs
, &cylinders
, &heads
, &secs
) == 0) {
1117 /* if heads > 16, it means that a BIOS LBA
1118 translation was active, so the default
1119 hardware geometry is OK */
1121 goto default_geometry
;
1126 /* disable any translation to be in sync with
1127 the logical geometry */
1128 if (translation
== BIOS_ATA_TRANSLATION_AUTO
) {
1129 bdrv_set_translation_hint(bs
,
1130 BIOS_ATA_TRANSLATION_NONE
);
1135 /* if no geometry, use a standard physical disk geometry */
1136 cylinders
= nb_sectors
/ (16 * 63);
1138 if (cylinders
> 16383)
1140 else if (cylinders
< 2)
1145 if ((lba_detected
== 1) && (translation
== BIOS_ATA_TRANSLATION_AUTO
)) {
1146 if ((*pcyls
* *pheads
) <= 131072) {
1147 bdrv_set_translation_hint(bs
,
1148 BIOS_ATA_TRANSLATION_LARGE
);
1150 bdrv_set_translation_hint(bs
,
1151 BIOS_ATA_TRANSLATION_LBA
);
1155 bdrv_set_geometry_hint(bs
, *pcyls
, *pheads
, *psecs
);
1159 void bdrv_set_geometry_hint(BlockDriverState
*bs
,
1160 int cyls
, int heads
, int secs
)
1167 void bdrv_set_type_hint(BlockDriverState
*bs
, int type
)
1170 bs
->removable
= ((type
== BDRV_TYPE_CDROM
||
1171 type
== BDRV_TYPE_FLOPPY
));
1174 void bdrv_set_translation_hint(BlockDriverState
*bs
, int translation
)
1176 bs
->translation
= translation
;
1179 void bdrv_get_geometry_hint(BlockDriverState
*bs
,
1180 int *pcyls
, int *pheads
, int *psecs
)
1183 *pheads
= bs
->heads
;
1187 int bdrv_get_type_hint(BlockDriverState
*bs
)
1192 int bdrv_get_translation_hint(BlockDriverState
*bs
)
1194 return bs
->translation
;
1197 int bdrv_is_removable(BlockDriverState
*bs
)
1199 return bs
->removable
;
1202 int bdrv_is_read_only(BlockDriverState
*bs
)
1204 return bs
->read_only
;
1207 int bdrv_is_sg(BlockDriverState
*bs
)
1212 int bdrv_enable_write_cache(BlockDriverState
*bs
)
1214 return bs
->enable_write_cache
;
1217 /* XXX: no longer used */
1218 void bdrv_set_change_cb(BlockDriverState
*bs
,
1219 void (*change_cb
)(void *opaque
), void *opaque
)
1221 bs
->change_cb
= change_cb
;
1222 bs
->change_opaque
= opaque
;
1225 int bdrv_is_encrypted(BlockDriverState
*bs
)
1227 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1229 return bs
->encrypted
;
1232 int bdrv_key_required(BlockDriverState
*bs
)
1234 BlockDriverState
*backing_hd
= bs
->backing_hd
;
1236 if (backing_hd
&& backing_hd
->encrypted
&& !backing_hd
->valid_key
)
1238 return (bs
->encrypted
&& !bs
->valid_key
);
1241 int bdrv_set_key(BlockDriverState
*bs
, const char *key
)
1244 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
) {
1245 ret
= bdrv_set_key(bs
->backing_hd
, key
);
1251 if (!bs
->encrypted
) {
1253 } else if (!bs
->drv
|| !bs
->drv
->bdrv_set_key
) {
1256 ret
= bs
->drv
->bdrv_set_key(bs
, key
);
1259 } else if (!bs
->valid_key
) {
1261 /* call the change callback now, we skipped it on open */
1262 bs
->media_changed
= 1;
1264 bs
->change_cb(bs
->change_opaque
);
1269 void bdrv_get_format(BlockDriverState
*bs
, char *buf
, int buf_size
)
1274 pstrcpy(buf
, buf_size
, bs
->drv
->format_name
);
1278 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
1283 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
1284 it(opaque
, drv
->format_name
);
1288 BlockDriverState
*bdrv_find(const char *name
)
1290 BlockDriverState
*bs
;
1292 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1293 if (!strcmp(name
, bs
->device_name
)) {
1300 void bdrv_iterate(void (*it
)(void *opaque
, BlockDriverState
*bs
), void *opaque
)
1302 BlockDriverState
*bs
;
1304 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1309 const char *bdrv_get_device_name(BlockDriverState
*bs
)
1311 return bs
->device_name
;
1314 void bdrv_flush(BlockDriverState
*bs
)
1316 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
1320 if (bs
->drv
&& bs
->drv
->bdrv_flush
)
1321 bs
->drv
->bdrv_flush(bs
);
1324 void bdrv_flush_all(void)
1326 BlockDriverState
*bs
;
1328 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1329 if (bs
->drv
&& !bdrv_is_read_only(bs
) &&
1330 (!bdrv_is_removable(bs
) || bdrv_is_inserted(bs
))) {
1336 int bdrv_has_zero_init(BlockDriverState
*bs
)
1340 if (bs
->drv
->no_zero_init
) {
1342 } else if (bs
->file
) {
1343 return bdrv_has_zero_init(bs
->file
);
1350 * Returns true iff the specified sector is present in the disk image. Drivers
1351 * not implementing the functionality are assumed to not support backing files,
1352 * hence all their sectors are reported as allocated.
1354 * 'pnum' is set to the number of sectors (including and immediately following
1355 * the specified sector) that are known to be in the same
1356 * allocated/unallocated state.
1358 * 'nb_sectors' is the max value 'pnum' should be set to.
1360 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
,
1364 if (!bs
->drv
->bdrv_is_allocated
) {
1365 if (sector_num
>= bs
->total_sectors
) {
1369 n
= bs
->total_sectors
- sector_num
;
1370 *pnum
= (n
< nb_sectors
) ? (n
) : (nb_sectors
);
1373 return bs
->drv
->bdrv_is_allocated(bs
, sector_num
, nb_sectors
, pnum
);
1376 void bdrv_mon_event(const BlockDriverState
*bdrv
,
1377 BlockMonEventAction action
, int is_read
)
1380 const char *action_str
;
1383 case BDRV_ACTION_REPORT
:
1384 action_str
= "report";
1386 case BDRV_ACTION_IGNORE
:
1387 action_str
= "ignore";
1389 case BDRV_ACTION_STOP
:
1390 action_str
= "stop";
1396 data
= qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1399 is_read
? "read" : "write");
1400 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR
, data
);
1402 qobject_decref(data
);
1405 static void bdrv_print_dict(QObject
*obj
, void *opaque
)
1408 Monitor
*mon
= opaque
;
1410 bs_dict
= qobject_to_qdict(obj
);
1412 monitor_printf(mon
, "%s: type=%s removable=%d",
1413 qdict_get_str(bs_dict
, "device"),
1414 qdict_get_str(bs_dict
, "type"),
1415 qdict_get_bool(bs_dict
, "removable"));
1417 if (qdict_get_bool(bs_dict
, "removable")) {
1418 monitor_printf(mon
, " locked=%d", qdict_get_bool(bs_dict
, "locked"));
1421 if (qdict_haskey(bs_dict
, "inserted")) {
1422 QDict
*qdict
= qobject_to_qdict(qdict_get(bs_dict
, "inserted"));
1424 monitor_printf(mon
, " file=");
1425 monitor_print_filename(mon
, qdict_get_str(qdict
, "file"));
1426 if (qdict_haskey(qdict
, "backing_file")) {
1427 monitor_printf(mon
, " backing_file=");
1428 monitor_print_filename(mon
, qdict_get_str(qdict
, "backing_file"));
1430 monitor_printf(mon
, " ro=%d drv=%s encrypted=%d",
1431 qdict_get_bool(qdict
, "ro"),
1432 qdict_get_str(qdict
, "drv"),
1433 qdict_get_bool(qdict
, "encrypted"));
1435 monitor_printf(mon
, " [not inserted]");
1438 monitor_printf(mon
, "\n");
1441 void bdrv_info_print(Monitor
*mon
, const QObject
*data
)
1443 qlist_iter(qobject_to_qlist(data
), bdrv_print_dict
, mon
);
1447 * bdrv_info(): Block devices information
1449 * Each block device information is stored in a QDict and the
1450 * returned QObject is a QList of all devices.
1452 * The QDict contains the following:
1454 * - "device": device name
1455 * - "type": device type
1456 * - "removable": true if the device is removable, false otherwise
1457 * - "locked": true if the device is locked, false otherwise
1458 * - "inserted": only present if the device is inserted, it is a QDict
1459 * containing the following:
1460 * - "file": device file name
1461 * - "ro": true if read-only, false otherwise
1462 * - "drv": driver format name
1463 * - "backing_file": backing file name if one is used
1464 * - "encrypted": true if encrypted, false otherwise
1468 * [ { "device": "ide0-hd0", "type": "hd", "removable": false, "locked": false,
1469 * "inserted": { "file": "/tmp/foobar", "ro": false, "drv": "qcow2" } },
1470 * { "device": "floppy0", "type": "floppy", "removable": true,
1471 * "locked": false } ]
1473 void bdrv_info(Monitor
*mon
, QObject
**ret_data
)
1476 BlockDriverState
*bs
;
1478 bs_list
= qlist_new();
1480 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1482 const char *type
= "unknown";
1488 case BDRV_TYPE_CDROM
:
1491 case BDRV_TYPE_FLOPPY
:
1496 bs_obj
= qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1497 "'removable': %i, 'locked': %i }",
1498 bs
->device_name
, type
, bs
->removable
,
1503 QDict
*bs_dict
= qobject_to_qdict(bs_obj
);
1505 obj
= qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1506 "'encrypted': %i }",
1507 bs
->filename
, bs
->read_only
,
1508 bs
->drv
->format_name
,
1509 bdrv_is_encrypted(bs
));
1510 if (bs
->backing_file
[0] != '\0') {
1511 QDict
*qdict
= qobject_to_qdict(obj
);
1512 qdict_put(qdict
, "backing_file",
1513 qstring_from_str(bs
->backing_file
));
1516 qdict_put_obj(bs_dict
, "inserted", obj
);
1518 qlist_append_obj(bs_list
, bs_obj
);
1521 *ret_data
= QOBJECT(bs_list
);
1524 static void bdrv_stats_iter(QObject
*data
, void *opaque
)
1527 Monitor
*mon
= opaque
;
1529 qdict
= qobject_to_qdict(data
);
1530 monitor_printf(mon
, "%s:", qdict_get_str(qdict
, "device"));
1532 qdict
= qobject_to_qdict(qdict_get(qdict
, "stats"));
1533 monitor_printf(mon
, " rd_bytes=%" PRId64
1534 " wr_bytes=%" PRId64
1535 " rd_operations=%" PRId64
1536 " wr_operations=%" PRId64
1538 qdict_get_int(qdict
, "rd_bytes"),
1539 qdict_get_int(qdict
, "wr_bytes"),
1540 qdict_get_int(qdict
, "rd_operations"),
1541 qdict_get_int(qdict
, "wr_operations"));
1544 void bdrv_stats_print(Monitor
*mon
, const QObject
*data
)
1546 qlist_iter(qobject_to_qlist(data
), bdrv_stats_iter
, mon
);
1549 static QObject
* bdrv_info_stats_bs(BlockDriverState
*bs
)
1554 res
= qobject_from_jsonf("{ 'stats': {"
1555 "'rd_bytes': %" PRId64
","
1556 "'wr_bytes': %" PRId64
","
1557 "'rd_operations': %" PRId64
","
1558 "'wr_operations': %" PRId64
","
1559 "'wr_highest_offset': %" PRId64
1561 bs
->rd_bytes
, bs
->wr_bytes
,
1562 bs
->rd_ops
, bs
->wr_ops
,
1563 bs
->wr_highest_sector
* 512);
1564 dict
= qobject_to_qdict(res
);
1566 if (*bs
->device_name
) {
1567 qdict_put(dict
, "device", qstring_from_str(bs
->device_name
));
1571 QObject
*parent
= bdrv_info_stats_bs(bs
->file
);
1572 qdict_put_obj(dict
, "parent", parent
);
1579 * bdrv_info_stats(): show block device statistics
1581 * Each device statistic information is stored in a QDict and
1582 * the returned QObject is a QList of all devices.
1584 * The QDict contains the following:
1586 * - "device": device name
1587 * - "stats": A QDict with the statistics information, it contains:
1588 * - "rd_bytes": bytes read
1589 * - "wr_bytes": bytes written
1590 * - "rd_operations": read operations
1591 * - "wr_operations": write operations
1592 * - "wr_highest_offset": Highest offset of a sector written since the
1593 * BlockDriverState has been opened
1594 * - "parent": A QDict recursively holding the statistics of the underlying
1595 * protocol (e.g. the host file for a qcow2 image). If there is no
1596 * underlying protocol, this field is omitted.
1600 * [ { "device": "ide0-hd0",
1601 * "stats": { "rd_bytes": 512,
1603 * "rd_operations": 1,
1604 * "wr_operations": 0,
1605 * "wr_highest_offset": 0 },
1607 * "stats": { "rd_bytes": 1024,
1609 * "rd_operations": 2,
1610 * "wr_operations": 0,
1611 * "wr_highest_offset": 0,
1613 * { "device": "ide1-cd0",
1614 * "stats": { "rd_bytes": 0,
1616 * "rd_operations": 0,
1617 * "wr_operations": 0,
1618 * "wr_highest_offset": 0 } },
1620 void bdrv_info_stats(Monitor
*mon
, QObject
**ret_data
)
1624 BlockDriverState
*bs
;
1626 devices
= qlist_new();
1628 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1629 obj
= bdrv_info_stats_bs(bs
);
1630 qlist_append_obj(devices
, obj
);
1633 *ret_data
= QOBJECT(devices
);
1636 const char *bdrv_get_encrypted_filename(BlockDriverState
*bs
)
1638 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1639 return bs
->backing_file
;
1640 else if (bs
->encrypted
)
1641 return bs
->filename
;
1646 void bdrv_get_backing_filename(BlockDriverState
*bs
,
1647 char *filename
, int filename_size
)
1649 if (!bs
->backing_file
) {
1650 pstrcpy(filename
, filename_size
, "");
1652 pstrcpy(filename
, filename_size
, bs
->backing_file
);
1656 int bdrv_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
1657 const uint8_t *buf
, int nb_sectors
)
1659 BlockDriver
*drv
= bs
->drv
;
1662 if (!drv
->bdrv_write_compressed
)
1664 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1667 if (bs
->dirty_bitmap
) {
1668 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1671 return drv
->bdrv_write_compressed(bs
, sector_num
, buf
, nb_sectors
);
1674 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1676 BlockDriver
*drv
= bs
->drv
;
1679 if (!drv
->bdrv_get_info
)
1681 memset(bdi
, 0, sizeof(*bdi
));
1682 return drv
->bdrv_get_info(bs
, bdi
);
1685 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
1686 int64_t pos
, int size
)
1688 BlockDriver
*drv
= bs
->drv
;
1691 if (!drv
->bdrv_save_vmstate
)
1693 return drv
->bdrv_save_vmstate(bs
, buf
, pos
, size
);
1696 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
1697 int64_t pos
, int size
)
1699 BlockDriver
*drv
= bs
->drv
;
1702 if (!drv
->bdrv_load_vmstate
)
1704 return drv
->bdrv_load_vmstate(bs
, buf
, pos
, size
);
1707 void bdrv_debug_event(BlockDriverState
*bs
, BlkDebugEvent event
)
1709 BlockDriver
*drv
= bs
->drv
;
1711 if (!drv
|| !drv
->bdrv_debug_event
) {
1715 return drv
->bdrv_debug_event(bs
, event
);
1719 /**************************************************************/
1720 /* handling of snapshots */
1722 int bdrv_snapshot_create(BlockDriverState
*bs
,
1723 QEMUSnapshotInfo
*sn_info
)
1725 BlockDriver
*drv
= bs
->drv
;
1728 if (!drv
->bdrv_snapshot_create
)
1730 return drv
->bdrv_snapshot_create(bs
, sn_info
);
1733 int bdrv_snapshot_goto(BlockDriverState
*bs
,
1734 const char *snapshot_id
)
1736 BlockDriver
*drv
= bs
->drv
;
1739 if (!drv
->bdrv_snapshot_goto
)
1741 return drv
->bdrv_snapshot_goto(bs
, snapshot_id
);
1744 int bdrv_snapshot_delete(BlockDriverState
*bs
, const char *snapshot_id
)
1746 BlockDriver
*drv
= bs
->drv
;
1749 if (!drv
->bdrv_snapshot_delete
)
1751 return drv
->bdrv_snapshot_delete(bs
, snapshot_id
);
1754 int bdrv_snapshot_list(BlockDriverState
*bs
,
1755 QEMUSnapshotInfo
**psn_info
)
1757 BlockDriver
*drv
= bs
->drv
;
1760 if (!drv
->bdrv_snapshot_list
)
1762 return drv
->bdrv_snapshot_list(bs
, psn_info
);
1765 #define NB_SUFFIXES 4
1767 char *get_human_readable_size(char *buf
, int buf_size
, int64_t size
)
1769 static const char suffixes
[NB_SUFFIXES
] = "KMGT";
1774 snprintf(buf
, buf_size
, "%" PRId64
, size
);
1777 for(i
= 0; i
< NB_SUFFIXES
; i
++) {
1778 if (size
< (10 * base
)) {
1779 snprintf(buf
, buf_size
, "%0.1f%c",
1780 (double)size
/ base
,
1783 } else if (size
< (1000 * base
) || i
== (NB_SUFFIXES
- 1)) {
1784 snprintf(buf
, buf_size
, "%" PRId64
"%c",
1785 ((size
+ (base
>> 1)) / base
),
1795 char *bdrv_snapshot_dump(char *buf
, int buf_size
, QEMUSnapshotInfo
*sn
)
1797 char buf1
[128], date_buf
[128], clock_buf
[128];
1807 snprintf(buf
, buf_size
,
1808 "%-10s%-20s%7s%20s%15s",
1809 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1813 ptm
= localtime(&ti
);
1814 strftime(date_buf
, sizeof(date_buf
),
1815 "%Y-%m-%d %H:%M:%S", ptm
);
1817 localtime_r(&ti
, &tm
);
1818 strftime(date_buf
, sizeof(date_buf
),
1819 "%Y-%m-%d %H:%M:%S", &tm
);
1821 secs
= sn
->vm_clock_nsec
/ 1000000000;
1822 snprintf(clock_buf
, sizeof(clock_buf
),
1823 "%02d:%02d:%02d.%03d",
1825 (int)((secs
/ 60) % 60),
1827 (int)((sn
->vm_clock_nsec
/ 1000000) % 1000));
1828 snprintf(buf
, buf_size
,
1829 "%-10s%-20s%7s%20s%15s",
1830 sn
->id_str
, sn
->name
,
1831 get_human_readable_size(buf1
, sizeof(buf1
), sn
->vm_state_size
),
1839 /**************************************************************/
1842 BlockDriverAIOCB
*bdrv_aio_readv(BlockDriverState
*bs
, int64_t sector_num
,
1843 QEMUIOVector
*qiov
, int nb_sectors
,
1844 BlockDriverCompletionFunc
*cb
, void *opaque
)
1846 BlockDriver
*drv
= bs
->drv
;
1847 BlockDriverAIOCB
*ret
;
1851 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1854 ret
= drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
1858 /* Update stats even though technically transfer has not happened. */
1859 bs
->rd_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
1866 BlockDriverAIOCB
*bdrv_aio_writev(BlockDriverState
*bs
, int64_t sector_num
,
1867 QEMUIOVector
*qiov
, int nb_sectors
,
1868 BlockDriverCompletionFunc
*cb
, void *opaque
)
1870 BlockDriver
*drv
= bs
->drv
;
1871 BlockDriverAIOCB
*ret
;
1877 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1880 if (bs
->dirty_bitmap
) {
1881 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1884 ret
= drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
1888 /* Update stats even though technically transfer has not happened. */
1889 bs
->wr_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
1891 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1892 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1900 typedef struct MultiwriteCB
{
1905 BlockDriverCompletionFunc
*cb
;
1907 QEMUIOVector
*free_qiov
;
1912 static void multiwrite_user_cb(MultiwriteCB
*mcb
)
1916 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
1917 mcb
->callbacks
[i
].cb(mcb
->callbacks
[i
].opaque
, mcb
->error
);
1918 if (mcb
->callbacks
[i
].free_qiov
) {
1919 qemu_iovec_destroy(mcb
->callbacks
[i
].free_qiov
);
1921 qemu_free(mcb
->callbacks
[i
].free_qiov
);
1922 qemu_vfree(mcb
->callbacks
[i
].free_buf
);
1926 static void multiwrite_cb(void *opaque
, int ret
)
1928 MultiwriteCB
*mcb
= opaque
;
1930 if (ret
< 0 && !mcb
->error
) {
1932 multiwrite_user_cb(mcb
);
1935 mcb
->num_requests
--;
1936 if (mcb
->num_requests
== 0) {
1937 if (mcb
->error
== 0) {
1938 multiwrite_user_cb(mcb
);
1944 static int multiwrite_req_compare(const void *a
, const void *b
)
1946 const BlockRequest
*req1
= a
, *req2
= b
;
1949 * Note that we can't simply subtract req2->sector from req1->sector
1950 * here as that could overflow the return value.
1952 if (req1
->sector
> req2
->sector
) {
1954 } else if (req1
->sector
< req2
->sector
) {
1962 * Takes a bunch of requests and tries to merge them. Returns the number of
1963 * requests that remain after merging.
1965 static int multiwrite_merge(BlockDriverState
*bs
, BlockRequest
*reqs
,
1966 int num_reqs
, MultiwriteCB
*mcb
)
1970 // Sort requests by start sector
1971 qsort(reqs
, num_reqs
, sizeof(*reqs
), &multiwrite_req_compare
);
1973 // Check if adjacent requests touch the same clusters. If so, combine them,
1974 // filling up gaps with zero sectors.
1976 for (i
= 1; i
< num_reqs
; i
++) {
1978 int64_t oldreq_last
= reqs
[outidx
].sector
+ reqs
[outidx
].nb_sectors
;
1980 // This handles the cases that are valid for all block drivers, namely
1981 // exactly sequential writes and overlapping writes.
1982 if (reqs
[i
].sector
<= oldreq_last
) {
1986 // The block driver may decide that it makes sense to combine requests
1987 // even if there is a gap of some sectors between them. In this case,
1988 // the gap is filled with zeros (therefore only applicable for yet
1989 // unused space in format like qcow2).
1990 if (!merge
&& bs
->drv
->bdrv_merge_requests
) {
1991 merge
= bs
->drv
->bdrv_merge_requests(bs
, &reqs
[outidx
], &reqs
[i
]);
1994 if (reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1 > IOV_MAX
) {
2000 QEMUIOVector
*qiov
= qemu_mallocz(sizeof(*qiov
));
2001 qemu_iovec_init(qiov
,
2002 reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1);
2004 // Add the first request to the merged one. If the requests are
2005 // overlapping, drop the last sectors of the first request.
2006 size
= (reqs
[i
].sector
- reqs
[outidx
].sector
) << 9;
2007 qemu_iovec_concat(qiov
, reqs
[outidx
].qiov
, size
);
2009 // We might need to add some zeros between the two requests
2010 if (reqs
[i
].sector
> oldreq_last
) {
2011 size_t zero_bytes
= (reqs
[i
].sector
- oldreq_last
) << 9;
2012 uint8_t *buf
= qemu_blockalign(bs
, zero_bytes
);
2013 memset(buf
, 0, zero_bytes
);
2014 qemu_iovec_add(qiov
, buf
, zero_bytes
);
2015 mcb
->callbacks
[i
].free_buf
= buf
;
2018 // Add the second request
2019 qemu_iovec_concat(qiov
, reqs
[i
].qiov
, reqs
[i
].qiov
->size
);
2021 reqs
[outidx
].nb_sectors
= qiov
->size
>> 9;
2022 reqs
[outidx
].qiov
= qiov
;
2024 mcb
->callbacks
[i
].free_qiov
= reqs
[outidx
].qiov
;
2027 reqs
[outidx
].sector
= reqs
[i
].sector
;
2028 reqs
[outidx
].nb_sectors
= reqs
[i
].nb_sectors
;
2029 reqs
[outidx
].qiov
= reqs
[i
].qiov
;
2037 * Submit multiple AIO write requests at once.
2039 * On success, the function returns 0 and all requests in the reqs array have
2040 * been submitted. In error case this function returns -1, and any of the
2041 * requests may or may not be submitted yet. In particular, this means that the
2042 * callback will be called for some of the requests, for others it won't. The
2043 * caller must check the error field of the BlockRequest to wait for the right
2044 * callbacks (if error != 0, no callback will be called).
2046 * The implementation may modify the contents of the reqs array, e.g. to merge
2047 * requests. However, the fields opaque and error are left unmodified as they
2048 * are used to signal failure for a single request to the caller.
2050 int bdrv_aio_multiwrite(BlockDriverState
*bs
, BlockRequest
*reqs
, int num_reqs
)
2052 BlockDriverAIOCB
*acb
;
2056 if (num_reqs
== 0) {
2060 // Create MultiwriteCB structure
2061 mcb
= qemu_mallocz(sizeof(*mcb
) + num_reqs
* sizeof(*mcb
->callbacks
));
2062 mcb
->num_requests
= 0;
2063 mcb
->num_callbacks
= num_reqs
;
2065 for (i
= 0; i
< num_reqs
; i
++) {
2066 mcb
->callbacks
[i
].cb
= reqs
[i
].cb
;
2067 mcb
->callbacks
[i
].opaque
= reqs
[i
].opaque
;
2070 // Check for mergable requests
2071 num_reqs
= multiwrite_merge(bs
, reqs
, num_reqs
, mcb
);
2073 // Run the aio requests
2074 for (i
= 0; i
< num_reqs
; i
++) {
2075 acb
= bdrv_aio_writev(bs
, reqs
[i
].sector
, reqs
[i
].qiov
,
2076 reqs
[i
].nb_sectors
, multiwrite_cb
, mcb
);
2079 // We can only fail the whole thing if no request has been
2080 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2081 // complete and report the error in the callback.
2082 if (mcb
->num_requests
== 0) {
2083 reqs
[i
].error
= -EIO
;
2086 mcb
->num_requests
++;
2087 multiwrite_cb(mcb
, -EIO
);
2091 mcb
->num_requests
++;
2102 BlockDriverAIOCB
*bdrv_aio_flush(BlockDriverState
*bs
,
2103 BlockDriverCompletionFunc
*cb
, void *opaque
)
2105 BlockDriver
*drv
= bs
->drv
;
2107 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2108 return bdrv_aio_noop_em(bs
, cb
, opaque
);
2113 return drv
->bdrv_aio_flush(bs
, cb
, opaque
);
2116 void bdrv_aio_cancel(BlockDriverAIOCB
*acb
)
2118 acb
->pool
->cancel(acb
);
2122 /**************************************************************/
2123 /* async block device emulation */
2125 typedef struct BlockDriverAIOCBSync
{
2126 BlockDriverAIOCB common
;
2129 /* vector translation state */
2133 } BlockDriverAIOCBSync
;
2135 static void bdrv_aio_cancel_em(BlockDriverAIOCB
*blockacb
)
2137 BlockDriverAIOCBSync
*acb
=
2138 container_of(blockacb
, BlockDriverAIOCBSync
, common
);
2139 qemu_bh_delete(acb
->bh
);
2141 qemu_aio_release(acb
);
2144 static AIOPool bdrv_em_aio_pool
= {
2145 .aiocb_size
= sizeof(BlockDriverAIOCBSync
),
2146 .cancel
= bdrv_aio_cancel_em
,
2149 static void bdrv_aio_bh_cb(void *opaque
)
2151 BlockDriverAIOCBSync
*acb
= opaque
;
2154 qemu_iovec_from_buffer(acb
->qiov
, acb
->bounce
, acb
->qiov
->size
);
2155 qemu_vfree(acb
->bounce
);
2156 acb
->common
.cb(acb
->common
.opaque
, acb
->ret
);
2157 qemu_bh_delete(acb
->bh
);
2159 qemu_aio_release(acb
);
2162 static BlockDriverAIOCB
*bdrv_aio_rw_vector(BlockDriverState
*bs
,
2166 BlockDriverCompletionFunc
*cb
,
2171 BlockDriverAIOCBSync
*acb
;
2173 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2174 acb
->is_write
= is_write
;
2176 acb
->bounce
= qemu_blockalign(bs
, qiov
->size
);
2179 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2182 qemu_iovec_to_buffer(acb
->qiov
, acb
->bounce
);
2183 acb
->ret
= bdrv_write(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2185 acb
->ret
= bdrv_read(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2188 qemu_bh_schedule(acb
->bh
);
2190 return &acb
->common
;
2193 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
2194 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2195 BlockDriverCompletionFunc
*cb
, void *opaque
)
2197 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 0);
2200 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
2201 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2202 BlockDriverCompletionFunc
*cb
, void *opaque
)
2204 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 1);
2207 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
2208 BlockDriverCompletionFunc
*cb
, void *opaque
)
2210 BlockDriverAIOCBSync
*acb
;
2212 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2213 acb
->is_write
= 1; /* don't bounce in the completion hadler */
2219 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2222 qemu_bh_schedule(acb
->bh
);
2223 return &acb
->common
;
2226 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
2227 BlockDriverCompletionFunc
*cb
, void *opaque
)
2229 BlockDriverAIOCBSync
*acb
;
2231 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2232 acb
->is_write
= 1; /* don't bounce in the completion handler */
2238 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2241 qemu_bh_schedule(acb
->bh
);
2242 return &acb
->common
;
2245 /**************************************************************/
2246 /* sync block device emulation */
2248 static void bdrv_rw_em_cb(void *opaque
, int ret
)
2250 *(int *)opaque
= ret
;
2253 #define NOT_DONE 0x7fffffff
2255 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
2256 uint8_t *buf
, int nb_sectors
)
2259 BlockDriverAIOCB
*acb
;
2263 async_context_push();
2265 async_ret
= NOT_DONE
;
2266 iov
.iov_base
= (void *)buf
;
2267 iov
.iov_len
= nb_sectors
* 512;
2268 qemu_iovec_init_external(&qiov
, &iov
, 1);
2269 acb
= bdrv_aio_readv(bs
, sector_num
, &qiov
, nb_sectors
,
2270 bdrv_rw_em_cb
, &async_ret
);
2276 while (async_ret
== NOT_DONE
) {
2282 async_context_pop();
2286 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
2287 const uint8_t *buf
, int nb_sectors
)
2290 BlockDriverAIOCB
*acb
;
2294 async_context_push();
2296 async_ret
= NOT_DONE
;
2297 iov
.iov_base
= (void *)buf
;
2298 iov
.iov_len
= nb_sectors
* 512;
2299 qemu_iovec_init_external(&qiov
, &iov
, 1);
2300 acb
= bdrv_aio_writev(bs
, sector_num
, &qiov
, nb_sectors
,
2301 bdrv_rw_em_cb
, &async_ret
);
2306 while (async_ret
== NOT_DONE
) {
2311 async_context_pop();
2315 void bdrv_init(void)
2317 module_call_init(MODULE_INIT_BLOCK
);
2320 void bdrv_init_with_whitelist(void)
2322 use_bdrv_whitelist
= 1;
2326 void *qemu_aio_get(AIOPool
*pool
, BlockDriverState
*bs
,
2327 BlockDriverCompletionFunc
*cb
, void *opaque
)
2329 BlockDriverAIOCB
*acb
;
2331 if (pool
->free_aiocb
) {
2332 acb
= pool
->free_aiocb
;
2333 pool
->free_aiocb
= acb
->next
;
2335 acb
= qemu_mallocz(pool
->aiocb_size
);
2340 acb
->opaque
= opaque
;
2344 void qemu_aio_release(void *p
)
2346 BlockDriverAIOCB
*acb
= (BlockDriverAIOCB
*)p
;
2347 AIOPool
*pool
= acb
->pool
;
2348 acb
->next
= pool
->free_aiocb
;
2349 pool
->free_aiocb
= acb
;
2352 /**************************************************************/
2353 /* removable device support */
2356 * Return TRUE if the media is present
2358 int bdrv_is_inserted(BlockDriverState
*bs
)
2360 BlockDriver
*drv
= bs
->drv
;
2364 if (!drv
->bdrv_is_inserted
)
2366 ret
= drv
->bdrv_is_inserted(bs
);
2371 * Return TRUE if the media changed since the last call to this
2372 * function. It is currently only used for floppy disks
2374 int bdrv_media_changed(BlockDriverState
*bs
)
2376 BlockDriver
*drv
= bs
->drv
;
2379 if (!drv
|| !drv
->bdrv_media_changed
)
2382 ret
= drv
->bdrv_media_changed(bs
);
2383 if (ret
== -ENOTSUP
)
2384 ret
= bs
->media_changed
;
2385 bs
->media_changed
= 0;
2390 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2392 int bdrv_eject(BlockDriverState
*bs
, int eject_flag
)
2394 BlockDriver
*drv
= bs
->drv
;
2401 if (!drv
|| !drv
->bdrv_eject
) {
2404 ret
= drv
->bdrv_eject(bs
, eject_flag
);
2406 if (ret
== -ENOTSUP
) {
2415 int bdrv_is_locked(BlockDriverState
*bs
)
2421 * Lock or unlock the media (if it is locked, the user won't be able
2422 * to eject it manually).
2424 void bdrv_set_locked(BlockDriverState
*bs
, int locked
)
2426 BlockDriver
*drv
= bs
->drv
;
2428 bs
->locked
= locked
;
2429 if (drv
&& drv
->bdrv_set_locked
) {
2430 drv
->bdrv_set_locked(bs
, locked
);
2434 /* needed for generic scsi interface */
2436 int bdrv_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
2438 BlockDriver
*drv
= bs
->drv
;
2440 if (drv
&& drv
->bdrv_ioctl
)
2441 return drv
->bdrv_ioctl(bs
, req
, buf
);
2445 BlockDriverAIOCB
*bdrv_aio_ioctl(BlockDriverState
*bs
,
2446 unsigned long int req
, void *buf
,
2447 BlockDriverCompletionFunc
*cb
, void *opaque
)
2449 BlockDriver
*drv
= bs
->drv
;
2451 if (drv
&& drv
->bdrv_aio_ioctl
)
2452 return drv
->bdrv_aio_ioctl(bs
, req
, buf
, cb
, opaque
);
2458 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
2460 return qemu_memalign((bs
&& bs
->buffer_alignment
) ? bs
->buffer_alignment
: 512, size
);
2463 void bdrv_set_dirty_tracking(BlockDriverState
*bs
, int enable
)
2465 int64_t bitmap_size
;
2467 bs
->dirty_count
= 0;
2469 if (!bs
->dirty_bitmap
) {
2470 bitmap_size
= (bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
) +
2471 BDRV_SECTORS_PER_DIRTY_CHUNK
* 8 - 1;
2472 bitmap_size
/= BDRV_SECTORS_PER_DIRTY_CHUNK
* 8;
2474 bs
->dirty_bitmap
= qemu_mallocz(bitmap_size
);
2477 if (bs
->dirty_bitmap
) {
2478 qemu_free(bs
->dirty_bitmap
);
2479 bs
->dirty_bitmap
= NULL
;
2484 int bdrv_get_dirty(BlockDriverState
*bs
, int64_t sector
)
2486 int64_t chunk
= sector
/ (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK
;
2488 if (bs
->dirty_bitmap
&&
2489 (sector
<< BDRV_SECTOR_BITS
) < bdrv_getlength(bs
)) {
2490 return bs
->dirty_bitmap
[chunk
/ (sizeof(unsigned long) * 8)] &
2491 (1 << (chunk
% (sizeof(unsigned long) * 8)));
2497 void bdrv_reset_dirty(BlockDriverState
*bs
, int64_t cur_sector
,
2500 set_dirty_bitmap(bs
, cur_sector
, nr_sectors
, 0);
2503 int64_t bdrv_get_dirty_count(BlockDriverState
*bs
)
2505 return bs
->dirty_count
;