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
)
292 /* TODO Drivers without bdrv_file_open must be specified explicitly */
295 * XXX(hch): we really should not let host device detection
296 * override an explicit protocol specification, but moving this
297 * later breaks access to device names with colons in them.
298 * Thanks to the brain-dead persistent naming schemes on udev-
299 * based Linux systems those actually are quite common.
301 drv1
= find_hdev_driver(filename
);
307 if (is_windows_drive(filename
) ||
308 is_windows_drive_prefix(filename
))
309 return bdrv_find_format("file");
312 p
= strchr(filename
, ':');
314 return bdrv_find_format("file");
317 if (len
> sizeof(protocol
) - 1)
318 len
= sizeof(protocol
) - 1;
319 memcpy(protocol
, filename
, len
);
320 protocol
[len
] = '\0';
321 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
322 if (drv1
->protocol_name
&&
323 !strcmp(drv1
->protocol_name
, protocol
)) {
330 static BlockDriver
*find_image_format(const char *filename
)
332 int ret
, score
, score_max
;
333 BlockDriver
*drv1
, *drv
;
335 BlockDriverState
*bs
;
337 ret
= bdrv_file_open(&bs
, filename
, 0);
341 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
342 if (bs
->sg
|| !bdrv_is_inserted(bs
)) {
344 return bdrv_find_format("raw");
347 ret
= bdrv_pread(bs
, 0, buf
, sizeof(buf
));
355 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
356 if (drv1
->bdrv_probe
) {
357 score
= drv1
->bdrv_probe(buf
, ret
, filename
);
358 if (score
> score_max
) {
368 * Set the current 'total_sectors' value
370 static int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
372 BlockDriver
*drv
= bs
->drv
;
374 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
378 /* query actual device if possible, otherwise just trust the hint */
379 if (drv
->bdrv_getlength
) {
380 int64_t length
= drv
->bdrv_getlength(bs
);
384 hint
= length
>> BDRV_SECTOR_BITS
;
387 bs
->total_sectors
= hint
;
392 * Common part for opening disk images and files
394 static int bdrv_open_common(BlockDriverState
*bs
, const char *filename
,
395 int flags
, BlockDriver
*drv
)
402 bs
->total_sectors
= 0;
405 bs
->open_flags
= flags
;
406 /* buffer_alignment defaulted to 512, drivers can change this value */
407 bs
->buffer_alignment
= 512;
409 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
411 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
)) {
416 bs
->opaque
= qemu_mallocz(drv
->instance_size
);
419 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
420 * write cache to the guest. We do need the fdatasync to flush
421 * out transactions for block allocations, and we maybe have a
422 * volatile write cache in our backing device to deal with.
424 if (flags
& (BDRV_O_CACHE_WB
|BDRV_O_NOCACHE
))
425 bs
->enable_write_cache
= 1;
428 * Clear flags that are internal to the block layer before opening the
431 open_flags
= flags
& ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
434 * Snapshots should be writeable.
436 if (bs
->is_temporary
) {
437 open_flags
|= BDRV_O_RDWR
;
440 /* Open the image, either directly or using a protocol */
441 if (drv
->bdrv_file_open
) {
442 ret
= drv
->bdrv_file_open(bs
, filename
, open_flags
);
444 ret
= bdrv_file_open(&bs
->file
, filename
, open_flags
);
446 ret
= drv
->bdrv_open(bs
, open_flags
);
454 bs
->keep_read_only
= bs
->read_only
= !(open_flags
& BDRV_O_RDWR
);
456 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
462 if (bs
->is_temporary
) {
470 bdrv_delete(bs
->file
);
473 qemu_free(bs
->opaque
);
480 * Opens a file using a protocol (file, host_device, nbd, ...)
482 int bdrv_file_open(BlockDriverState
**pbs
, const char *filename
, int flags
)
484 BlockDriverState
*bs
;
488 drv
= bdrv_find_protocol(filename
);
494 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
505 * Opens a disk image (raw, qcow2, vmdk, ...)
507 int bdrv_open(BlockDriverState
*bs
, const char *filename
, int flags
,
512 if (flags
& BDRV_O_SNAPSHOT
) {
513 BlockDriverState
*bs1
;
516 BlockDriver
*bdrv_qcow2
;
517 QEMUOptionParameter
*options
;
518 char tmp_filename
[PATH_MAX
];
519 char backing_filename
[PATH_MAX
];
521 /* if snapshot, we create a temporary backing file and open it
522 instead of opening 'filename' directly */
524 /* if there is a backing file, use it */
526 ret
= bdrv_open(bs1
, filename
, 0, drv
);
531 total_size
= bdrv_getlength(bs1
) & BDRV_SECTOR_MASK
;
533 if (bs1
->drv
&& bs1
->drv
->protocol_name
)
538 get_tmp_filename(tmp_filename
, sizeof(tmp_filename
));
540 /* Real path is meaningless for protocols */
542 snprintf(backing_filename
, sizeof(backing_filename
),
544 else if (!realpath(filename
, backing_filename
))
547 bdrv_qcow2
= bdrv_find_format("qcow2");
548 options
= parse_option_parameters("", bdrv_qcow2
->create_options
, NULL
);
550 set_option_parameter_int(options
, BLOCK_OPT_SIZE
, total_size
);
551 set_option_parameter(options
, BLOCK_OPT_BACKING_FILE
, backing_filename
);
553 set_option_parameter(options
, BLOCK_OPT_BACKING_FMT
,
557 ret
= bdrv_create(bdrv_qcow2
, tmp_filename
, options
);
558 free_option_parameters(options
);
563 filename
= tmp_filename
;
565 bs
->is_temporary
= 1;
568 /* Find the right image format driver */
570 drv
= find_image_format(filename
);
575 goto unlink_and_fail
;
579 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
581 goto unlink_and_fail
;
584 /* If there is a backing file, use it */
585 if ((flags
& BDRV_O_NO_BACKING
) == 0 && bs
->backing_file
[0] != '\0') {
586 char backing_filename
[PATH_MAX
];
588 BlockDriver
*back_drv
= NULL
;
590 bs
->backing_hd
= bdrv_new("");
591 path_combine(backing_filename
, sizeof(backing_filename
),
592 filename
, bs
->backing_file
);
593 if (bs
->backing_format
[0] != '\0')
594 back_drv
= bdrv_find_format(bs
->backing_format
);
596 /* backing files always opened read-only */
598 flags
& ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
600 ret
= bdrv_open(bs
->backing_hd
, backing_filename
, back_flags
, back_drv
);
605 if (bs
->is_temporary
) {
606 bs
->backing_hd
->keep_read_only
= !(flags
& BDRV_O_RDWR
);
608 /* base image inherits from "parent" */
609 bs
->backing_hd
->keep_read_only
= bs
->keep_read_only
;
613 if (!bdrv_key_required(bs
)) {
614 /* call the change callback */
615 bs
->media_changed
= 1;
617 bs
->change_cb(bs
->change_opaque
);
623 if (bs
->is_temporary
) {
629 void bdrv_close(BlockDriverState
*bs
)
632 if (bs
->backing_hd
) {
633 bdrv_delete(bs
->backing_hd
);
634 bs
->backing_hd
= NULL
;
636 bs
->drv
->bdrv_close(bs
);
637 qemu_free(bs
->opaque
);
639 if (bs
->is_temporary
) {
640 unlink(bs
->filename
);
646 if (bs
->file
!= NULL
) {
647 bdrv_close(bs
->file
);
650 /* call the change callback */
651 bs
->media_changed
= 1;
653 bs
->change_cb(bs
->change_opaque
);
657 void bdrv_close_all(void)
659 BlockDriverState
*bs
;
661 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
666 void bdrv_delete(BlockDriverState
*bs
)
670 /* remove from list, if necessary */
671 if (bs
->device_name
[0] != '\0') {
672 QTAILQ_REMOVE(&bdrv_states
, bs
, list
);
676 if (bs
->file
!= NULL
) {
677 bdrv_delete(bs
->file
);
683 int bdrv_attach(BlockDriverState
*bs
, DeviceState
*qdev
)
692 void bdrv_detach(BlockDriverState
*bs
, DeviceState
*qdev
)
694 assert(bs
->peer
== qdev
);
698 DeviceState
*bdrv_get_attached(BlockDriverState
*bs
)
704 * Run consistency checks on an image
706 * Returns the number of errors or -errno when an internal error occurs
708 int bdrv_check(BlockDriverState
*bs
)
710 if (bs
->drv
->bdrv_check
== NULL
) {
714 return bs
->drv
->bdrv_check(bs
);
717 /* commit COW file into the raw image */
718 int bdrv_commit(BlockDriverState
*bs
)
720 BlockDriver
*drv
= bs
->drv
;
721 int64_t i
, total_sectors
;
722 int n
, j
, ro
, open_flags
;
723 int ret
= 0, rw_ret
= 0;
724 unsigned char sector
[BDRV_SECTOR_SIZE
];
726 BlockDriverState
*bs_rw
, *bs_ro
;
731 if (!bs
->backing_hd
) {
735 if (bs
->backing_hd
->keep_read_only
) {
739 ro
= bs
->backing_hd
->read_only
;
740 strncpy(filename
, bs
->backing_hd
->filename
, sizeof(filename
));
741 open_flags
= bs
->backing_hd
->open_flags
;
745 bdrv_delete(bs
->backing_hd
);
746 bs
->backing_hd
= NULL
;
747 bs_rw
= bdrv_new("");
748 rw_ret
= bdrv_open(bs_rw
, filename
, open_flags
| BDRV_O_RDWR
, drv
);
751 /* try to re-open read-only */
752 bs_ro
= bdrv_new("");
753 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
, drv
);
756 /* drive not functional anymore */
760 bs
->backing_hd
= bs_ro
;
763 bs
->backing_hd
= bs_rw
;
766 total_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
767 for (i
= 0; i
< total_sectors
;) {
768 if (drv
->bdrv_is_allocated(bs
, i
, 65536, &n
)) {
769 for(j
= 0; j
< n
; j
++) {
770 if (bdrv_read(bs
, i
, sector
, 1) != 0) {
775 if (bdrv_write(bs
->backing_hd
, i
, sector
, 1) != 0) {
786 if (drv
->bdrv_make_empty
) {
787 ret
= drv
->bdrv_make_empty(bs
);
792 * Make sure all data we wrote to the backing device is actually
796 bdrv_flush(bs
->backing_hd
);
802 bdrv_delete(bs
->backing_hd
);
803 bs
->backing_hd
= NULL
;
804 bs_ro
= bdrv_new("");
805 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
, drv
);
808 /* drive not functional anymore */
812 bs
->backing_hd
= bs_ro
;
813 bs
->backing_hd
->keep_read_only
= 0;
819 void bdrv_commit_all(void)
821 BlockDriverState
*bs
;
823 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
831 * -EINVAL - backing format specified, but no file
832 * -ENOSPC - can't update the backing file because no space is left in the
834 * -ENOTSUP - format driver doesn't support changing the backing file
836 int bdrv_change_backing_file(BlockDriverState
*bs
,
837 const char *backing_file
, const char *backing_fmt
)
839 BlockDriver
*drv
= bs
->drv
;
841 if (drv
->bdrv_change_backing_file
!= NULL
) {
842 return drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
848 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
853 if (!bdrv_is_inserted(bs
))
859 len
= bdrv_getlength(bs
);
864 if ((offset
> len
) || (len
- offset
< size
))
870 static int bdrv_check_request(BlockDriverState
*bs
, int64_t sector_num
,
873 return bdrv_check_byte_request(bs
, sector_num
* BDRV_SECTOR_SIZE
,
874 nb_sectors
* BDRV_SECTOR_SIZE
);
877 /* return < 0 if error. See bdrv_write() for the return codes */
878 int bdrv_read(BlockDriverState
*bs
, int64_t sector_num
,
879 uint8_t *buf
, int nb_sectors
)
881 BlockDriver
*drv
= bs
->drv
;
885 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
888 return drv
->bdrv_read(bs
, sector_num
, buf
, nb_sectors
);
891 static void set_dirty_bitmap(BlockDriverState
*bs
, int64_t sector_num
,
892 int nb_sectors
, int dirty
)
895 unsigned long val
, idx
, bit
;
897 start
= sector_num
/ BDRV_SECTORS_PER_DIRTY_CHUNK
;
898 end
= (sector_num
+ nb_sectors
- 1) / BDRV_SECTORS_PER_DIRTY_CHUNK
;
900 for (; start
<= end
; start
++) {
901 idx
= start
/ (sizeof(unsigned long) * 8);
902 bit
= start
% (sizeof(unsigned long) * 8);
903 val
= bs
->dirty_bitmap
[idx
];
905 if (!(val
& (1 << bit
))) {
910 if (val
& (1 << bit
)) {
915 bs
->dirty_bitmap
[idx
] = val
;
919 /* Return < 0 if error. Important errors are:
920 -EIO generic I/O error (may happen for all errors)
921 -ENOMEDIUM No media inserted.
922 -EINVAL Invalid sector number or nb_sectors
923 -EACCES Trying to write a read-only device
925 int bdrv_write(BlockDriverState
*bs
, int64_t sector_num
,
926 const uint8_t *buf
, int nb_sectors
)
928 BlockDriver
*drv
= bs
->drv
;
933 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
936 if (bs
->dirty_bitmap
) {
937 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
940 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
941 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
944 return drv
->bdrv_write(bs
, sector_num
, buf
, nb_sectors
);
947 int bdrv_pread(BlockDriverState
*bs
, int64_t offset
,
948 void *buf
, int count1
)
950 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
951 int len
, nb_sectors
, count
;
956 /* first read to align to sector start */
957 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
960 sector_num
= offset
>> BDRV_SECTOR_BITS
;
962 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
964 memcpy(buf
, tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), len
);
972 /* read the sectors "in place" */
973 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
974 if (nb_sectors
> 0) {
975 if ((ret
= bdrv_read(bs
, sector_num
, buf
, nb_sectors
)) < 0)
977 sector_num
+= nb_sectors
;
978 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
983 /* add data from the last sector */
985 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
987 memcpy(buf
, tmp_buf
, count
);
992 int bdrv_pwrite(BlockDriverState
*bs
, int64_t offset
,
993 const void *buf
, int count1
)
995 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
996 int len
, nb_sectors
, count
;
1001 /* first write to align to sector start */
1002 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1005 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1007 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1009 memcpy(tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), buf
, len
);
1010 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1019 /* write the sectors "in place" */
1020 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1021 if (nb_sectors
> 0) {
1022 if ((ret
= bdrv_write(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1024 sector_num
+= nb_sectors
;
1025 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1030 /* add data from the last sector */
1032 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1034 memcpy(tmp_buf
, buf
, count
);
1035 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1042 * Writes to the file and ensures that no writes are reordered across this
1043 * request (acts as a barrier)
1045 * Returns 0 on success, -errno in error cases.
1047 int bdrv_pwrite_sync(BlockDriverState
*bs
, int64_t offset
,
1048 const void *buf
, int count
)
1052 ret
= bdrv_pwrite(bs
, offset
, buf
, count
);
1057 /* No flush needed for cache=writethrough, it uses O_DSYNC */
1058 if ((bs
->open_flags
& BDRV_O_CACHE_MASK
) != 0) {
1066 * Writes to the file and ensures that no writes are reordered across this
1067 * request (acts as a barrier)
1069 * Returns 0 on success, -errno in error cases.
1071 int bdrv_write_sync(BlockDriverState
*bs
, int64_t sector_num
,
1072 const uint8_t *buf
, int nb_sectors
)
1074 return bdrv_pwrite_sync(bs
, BDRV_SECTOR_SIZE
* sector_num
,
1075 buf
, BDRV_SECTOR_SIZE
* nb_sectors
);
1079 * Truncate file to 'offset' bytes (needed only for file protocols)
1081 int bdrv_truncate(BlockDriverState
*bs
, int64_t offset
)
1083 BlockDriver
*drv
= bs
->drv
;
1087 if (!drv
->bdrv_truncate
)
1091 ret
= drv
->bdrv_truncate(bs
, offset
);
1093 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
1099 * Length of a file in bytes. Return < 0 if error or unknown.
1101 int64_t bdrv_getlength(BlockDriverState
*bs
)
1103 BlockDriver
*drv
= bs
->drv
;
1107 /* Fixed size devices use the total_sectors value for speed instead of
1108 issuing a length query (like lseek) on each call. Also, legacy block
1109 drivers don't provide a bdrv_getlength function and must use
1111 if (!bs
->growable
|| !drv
->bdrv_getlength
) {
1112 return bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1114 return drv
->bdrv_getlength(bs
);
1117 /* return 0 as number of sectors if no device present or error */
1118 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
1121 length
= bdrv_getlength(bs
);
1125 length
= length
>> BDRV_SECTOR_BITS
;
1126 *nb_sectors_ptr
= length
;
1130 uint8_t boot_ind
; /* 0x80 - active */
1131 uint8_t head
; /* starting head */
1132 uint8_t sector
; /* starting sector */
1133 uint8_t cyl
; /* starting cylinder */
1134 uint8_t sys_ind
; /* What partition type */
1135 uint8_t end_head
; /* end head */
1136 uint8_t end_sector
; /* end sector */
1137 uint8_t end_cyl
; /* end cylinder */
1138 uint32_t start_sect
; /* starting sector counting from 0 */
1139 uint32_t nr_sects
; /* nr of sectors in partition */
1140 } __attribute__((packed
));
1142 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1143 static int guess_disk_lchs(BlockDriverState
*bs
,
1144 int *pcylinders
, int *pheads
, int *psectors
)
1146 uint8_t buf
[BDRV_SECTOR_SIZE
];
1147 int ret
, i
, heads
, sectors
, cylinders
;
1148 struct partition
*p
;
1150 uint64_t nb_sectors
;
1152 bdrv_get_geometry(bs
, &nb_sectors
);
1154 ret
= bdrv_read(bs
, 0, buf
, 1);
1157 /* test msdos magic */
1158 if (buf
[510] != 0x55 || buf
[511] != 0xaa)
1160 for(i
= 0; i
< 4; i
++) {
1161 p
= ((struct partition
*)(buf
+ 0x1be)) + i
;
1162 nr_sects
= le32_to_cpu(p
->nr_sects
);
1163 if (nr_sects
&& p
->end_head
) {
1164 /* We make the assumption that the partition terminates on
1165 a cylinder boundary */
1166 heads
= p
->end_head
+ 1;
1167 sectors
= p
->end_sector
& 63;
1170 cylinders
= nb_sectors
/ (heads
* sectors
);
1171 if (cylinders
< 1 || cylinders
> 16383)
1174 *psectors
= sectors
;
1175 *pcylinders
= cylinders
;
1177 printf("guessed geometry: LCHS=%d %d %d\n",
1178 cylinders
, heads
, sectors
);
1186 void bdrv_guess_geometry(BlockDriverState
*bs
, int *pcyls
, int *pheads
, int *psecs
)
1188 int translation
, lba_detected
= 0;
1189 int cylinders
, heads
, secs
;
1190 uint64_t nb_sectors
;
1192 /* if a geometry hint is available, use it */
1193 bdrv_get_geometry(bs
, &nb_sectors
);
1194 bdrv_get_geometry_hint(bs
, &cylinders
, &heads
, &secs
);
1195 translation
= bdrv_get_translation_hint(bs
);
1196 if (cylinders
!= 0) {
1201 if (guess_disk_lchs(bs
, &cylinders
, &heads
, &secs
) == 0) {
1203 /* if heads > 16, it means that a BIOS LBA
1204 translation was active, so the default
1205 hardware geometry is OK */
1207 goto default_geometry
;
1212 /* disable any translation to be in sync with
1213 the logical geometry */
1214 if (translation
== BIOS_ATA_TRANSLATION_AUTO
) {
1215 bdrv_set_translation_hint(bs
,
1216 BIOS_ATA_TRANSLATION_NONE
);
1221 /* if no geometry, use a standard physical disk geometry */
1222 cylinders
= nb_sectors
/ (16 * 63);
1224 if (cylinders
> 16383)
1226 else if (cylinders
< 2)
1231 if ((lba_detected
== 1) && (translation
== BIOS_ATA_TRANSLATION_AUTO
)) {
1232 if ((*pcyls
* *pheads
) <= 131072) {
1233 bdrv_set_translation_hint(bs
,
1234 BIOS_ATA_TRANSLATION_LARGE
);
1236 bdrv_set_translation_hint(bs
,
1237 BIOS_ATA_TRANSLATION_LBA
);
1241 bdrv_set_geometry_hint(bs
, *pcyls
, *pheads
, *psecs
);
1245 void bdrv_set_geometry_hint(BlockDriverState
*bs
,
1246 int cyls
, int heads
, int secs
)
1253 void bdrv_set_type_hint(BlockDriverState
*bs
, int type
)
1256 bs
->removable
= ((type
== BDRV_TYPE_CDROM
||
1257 type
== BDRV_TYPE_FLOPPY
));
1260 void bdrv_set_translation_hint(BlockDriverState
*bs
, int translation
)
1262 bs
->translation
= translation
;
1265 void bdrv_get_geometry_hint(BlockDriverState
*bs
,
1266 int *pcyls
, int *pheads
, int *psecs
)
1269 *pheads
= bs
->heads
;
1273 int bdrv_get_type_hint(BlockDriverState
*bs
)
1278 int bdrv_get_translation_hint(BlockDriverState
*bs
)
1280 return bs
->translation
;
1283 void bdrv_set_on_error(BlockDriverState
*bs
, BlockErrorAction on_read_error
,
1284 BlockErrorAction on_write_error
)
1286 bs
->on_read_error
= on_read_error
;
1287 bs
->on_write_error
= on_write_error
;
1290 BlockErrorAction
bdrv_get_on_error(BlockDriverState
*bs
, int is_read
)
1292 return is_read
? bs
->on_read_error
: bs
->on_write_error
;
1295 int bdrv_is_removable(BlockDriverState
*bs
)
1297 return bs
->removable
;
1300 int bdrv_is_read_only(BlockDriverState
*bs
)
1302 return bs
->read_only
;
1305 int bdrv_is_sg(BlockDriverState
*bs
)
1310 int bdrv_enable_write_cache(BlockDriverState
*bs
)
1312 return bs
->enable_write_cache
;
1315 /* XXX: no longer used */
1316 void bdrv_set_change_cb(BlockDriverState
*bs
,
1317 void (*change_cb
)(void *opaque
), void *opaque
)
1319 bs
->change_cb
= change_cb
;
1320 bs
->change_opaque
= opaque
;
1323 int bdrv_is_encrypted(BlockDriverState
*bs
)
1325 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1327 return bs
->encrypted
;
1330 int bdrv_key_required(BlockDriverState
*bs
)
1332 BlockDriverState
*backing_hd
= bs
->backing_hd
;
1334 if (backing_hd
&& backing_hd
->encrypted
&& !backing_hd
->valid_key
)
1336 return (bs
->encrypted
&& !bs
->valid_key
);
1339 int bdrv_set_key(BlockDriverState
*bs
, const char *key
)
1342 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
) {
1343 ret
= bdrv_set_key(bs
->backing_hd
, key
);
1349 if (!bs
->encrypted
) {
1351 } else if (!bs
->drv
|| !bs
->drv
->bdrv_set_key
) {
1354 ret
= bs
->drv
->bdrv_set_key(bs
, key
);
1357 } else if (!bs
->valid_key
) {
1359 /* call the change callback now, we skipped it on open */
1360 bs
->media_changed
= 1;
1362 bs
->change_cb(bs
->change_opaque
);
1367 void bdrv_get_format(BlockDriverState
*bs
, char *buf
, int buf_size
)
1372 pstrcpy(buf
, buf_size
, bs
->drv
->format_name
);
1376 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
1381 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
1382 it(opaque
, drv
->format_name
);
1386 BlockDriverState
*bdrv_find(const char *name
)
1388 BlockDriverState
*bs
;
1390 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1391 if (!strcmp(name
, bs
->device_name
)) {
1398 BlockDriverState
*bdrv_next(BlockDriverState
*bs
)
1401 return QTAILQ_FIRST(&bdrv_states
);
1403 return QTAILQ_NEXT(bs
, list
);
1406 void bdrv_iterate(void (*it
)(void *opaque
, BlockDriverState
*bs
), void *opaque
)
1408 BlockDriverState
*bs
;
1410 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1415 const char *bdrv_get_device_name(BlockDriverState
*bs
)
1417 return bs
->device_name
;
1420 void bdrv_flush(BlockDriverState
*bs
)
1422 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
1426 if (bs
->drv
&& bs
->drv
->bdrv_flush
)
1427 bs
->drv
->bdrv_flush(bs
);
1430 void bdrv_flush_all(void)
1432 BlockDriverState
*bs
;
1434 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1435 if (bs
->drv
&& !bdrv_is_read_only(bs
) &&
1436 (!bdrv_is_removable(bs
) || bdrv_is_inserted(bs
))) {
1442 int bdrv_has_zero_init(BlockDriverState
*bs
)
1446 if (bs
->drv
->no_zero_init
) {
1448 } else if (bs
->file
) {
1449 return bdrv_has_zero_init(bs
->file
);
1456 * Returns true iff the specified sector is present in the disk image. Drivers
1457 * not implementing the functionality are assumed to not support backing files,
1458 * hence all their sectors are reported as allocated.
1460 * 'pnum' is set to the number of sectors (including and immediately following
1461 * the specified sector) that are known to be in the same
1462 * allocated/unallocated state.
1464 * 'nb_sectors' is the max value 'pnum' should be set to.
1466 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
,
1470 if (!bs
->drv
->bdrv_is_allocated
) {
1471 if (sector_num
>= bs
->total_sectors
) {
1475 n
= bs
->total_sectors
- sector_num
;
1476 *pnum
= (n
< nb_sectors
) ? (n
) : (nb_sectors
);
1479 return bs
->drv
->bdrv_is_allocated(bs
, sector_num
, nb_sectors
, pnum
);
1482 void bdrv_mon_event(const BlockDriverState
*bdrv
,
1483 BlockMonEventAction action
, int is_read
)
1486 const char *action_str
;
1489 case BDRV_ACTION_REPORT
:
1490 action_str
= "report";
1492 case BDRV_ACTION_IGNORE
:
1493 action_str
= "ignore";
1495 case BDRV_ACTION_STOP
:
1496 action_str
= "stop";
1502 data
= qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1505 is_read
? "read" : "write");
1506 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR
, data
);
1508 qobject_decref(data
);
1511 static void bdrv_print_dict(QObject
*obj
, void *opaque
)
1514 Monitor
*mon
= opaque
;
1516 bs_dict
= qobject_to_qdict(obj
);
1518 monitor_printf(mon
, "%s: type=%s removable=%d",
1519 qdict_get_str(bs_dict
, "device"),
1520 qdict_get_str(bs_dict
, "type"),
1521 qdict_get_bool(bs_dict
, "removable"));
1523 if (qdict_get_bool(bs_dict
, "removable")) {
1524 monitor_printf(mon
, " locked=%d", qdict_get_bool(bs_dict
, "locked"));
1527 if (qdict_haskey(bs_dict
, "inserted")) {
1528 QDict
*qdict
= qobject_to_qdict(qdict_get(bs_dict
, "inserted"));
1530 monitor_printf(mon
, " file=");
1531 monitor_print_filename(mon
, qdict_get_str(qdict
, "file"));
1532 if (qdict_haskey(qdict
, "backing_file")) {
1533 monitor_printf(mon
, " backing_file=");
1534 monitor_print_filename(mon
, qdict_get_str(qdict
, "backing_file"));
1536 monitor_printf(mon
, " ro=%d drv=%s encrypted=%d",
1537 qdict_get_bool(qdict
, "ro"),
1538 qdict_get_str(qdict
, "drv"),
1539 qdict_get_bool(qdict
, "encrypted"));
1541 monitor_printf(mon
, " [not inserted]");
1544 monitor_printf(mon
, "\n");
1547 void bdrv_info_print(Monitor
*mon
, const QObject
*data
)
1549 qlist_iter(qobject_to_qlist(data
), bdrv_print_dict
, mon
);
1552 void bdrv_info(Monitor
*mon
, QObject
**ret_data
)
1555 BlockDriverState
*bs
;
1557 bs_list
= qlist_new();
1559 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1561 const char *type
= "unknown";
1567 case BDRV_TYPE_CDROM
:
1570 case BDRV_TYPE_FLOPPY
:
1575 bs_obj
= qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1576 "'removable': %i, 'locked': %i }",
1577 bs
->device_name
, type
, bs
->removable
,
1582 QDict
*bs_dict
= qobject_to_qdict(bs_obj
);
1584 obj
= qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1585 "'encrypted': %i }",
1586 bs
->filename
, bs
->read_only
,
1587 bs
->drv
->format_name
,
1588 bdrv_is_encrypted(bs
));
1589 if (bs
->backing_file
[0] != '\0') {
1590 QDict
*qdict
= qobject_to_qdict(obj
);
1591 qdict_put(qdict
, "backing_file",
1592 qstring_from_str(bs
->backing_file
));
1595 qdict_put_obj(bs_dict
, "inserted", obj
);
1597 qlist_append_obj(bs_list
, bs_obj
);
1600 *ret_data
= QOBJECT(bs_list
);
1603 static void bdrv_stats_iter(QObject
*data
, void *opaque
)
1606 Monitor
*mon
= opaque
;
1608 qdict
= qobject_to_qdict(data
);
1609 monitor_printf(mon
, "%s:", qdict_get_str(qdict
, "device"));
1611 qdict
= qobject_to_qdict(qdict_get(qdict
, "stats"));
1612 monitor_printf(mon
, " rd_bytes=%" PRId64
1613 " wr_bytes=%" PRId64
1614 " rd_operations=%" PRId64
1615 " wr_operations=%" PRId64
1617 qdict_get_int(qdict
, "rd_bytes"),
1618 qdict_get_int(qdict
, "wr_bytes"),
1619 qdict_get_int(qdict
, "rd_operations"),
1620 qdict_get_int(qdict
, "wr_operations"));
1623 void bdrv_stats_print(Monitor
*mon
, const QObject
*data
)
1625 qlist_iter(qobject_to_qlist(data
), bdrv_stats_iter
, mon
);
1628 static QObject
* bdrv_info_stats_bs(BlockDriverState
*bs
)
1633 res
= qobject_from_jsonf("{ 'stats': {"
1634 "'rd_bytes': %" PRId64
","
1635 "'wr_bytes': %" PRId64
","
1636 "'rd_operations': %" PRId64
","
1637 "'wr_operations': %" PRId64
","
1638 "'wr_highest_offset': %" PRId64
1640 bs
->rd_bytes
, bs
->wr_bytes
,
1641 bs
->rd_ops
, bs
->wr_ops
,
1642 bs
->wr_highest_sector
*
1643 (uint64_t)BDRV_SECTOR_SIZE
);
1644 dict
= qobject_to_qdict(res
);
1646 if (*bs
->device_name
) {
1647 qdict_put(dict
, "device", qstring_from_str(bs
->device_name
));
1651 QObject
*parent
= bdrv_info_stats_bs(bs
->file
);
1652 qdict_put_obj(dict
, "parent", parent
);
1658 void bdrv_info_stats(Monitor
*mon
, QObject
**ret_data
)
1662 BlockDriverState
*bs
;
1664 devices
= qlist_new();
1666 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1667 obj
= bdrv_info_stats_bs(bs
);
1668 qlist_append_obj(devices
, obj
);
1671 *ret_data
= QOBJECT(devices
);
1674 const char *bdrv_get_encrypted_filename(BlockDriverState
*bs
)
1676 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1677 return bs
->backing_file
;
1678 else if (bs
->encrypted
)
1679 return bs
->filename
;
1684 void bdrv_get_backing_filename(BlockDriverState
*bs
,
1685 char *filename
, int filename_size
)
1687 if (!bs
->backing_file
) {
1688 pstrcpy(filename
, filename_size
, "");
1690 pstrcpy(filename
, filename_size
, bs
->backing_file
);
1694 int bdrv_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
1695 const uint8_t *buf
, int nb_sectors
)
1697 BlockDriver
*drv
= bs
->drv
;
1700 if (!drv
->bdrv_write_compressed
)
1702 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1705 if (bs
->dirty_bitmap
) {
1706 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1709 return drv
->bdrv_write_compressed(bs
, sector_num
, buf
, nb_sectors
);
1712 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1714 BlockDriver
*drv
= bs
->drv
;
1717 if (!drv
->bdrv_get_info
)
1719 memset(bdi
, 0, sizeof(*bdi
));
1720 return drv
->bdrv_get_info(bs
, bdi
);
1723 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
1724 int64_t pos
, int size
)
1726 BlockDriver
*drv
= bs
->drv
;
1729 if (drv
->bdrv_save_vmstate
)
1730 return drv
->bdrv_save_vmstate(bs
, buf
, pos
, size
);
1732 return bdrv_save_vmstate(bs
->file
, buf
, pos
, size
);
1736 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
1737 int64_t pos
, int size
)
1739 BlockDriver
*drv
= bs
->drv
;
1742 if (drv
->bdrv_load_vmstate
)
1743 return drv
->bdrv_load_vmstate(bs
, buf
, pos
, size
);
1745 return bdrv_load_vmstate(bs
->file
, buf
, pos
, size
);
1749 void bdrv_debug_event(BlockDriverState
*bs
, BlkDebugEvent event
)
1751 BlockDriver
*drv
= bs
->drv
;
1753 if (!drv
|| !drv
->bdrv_debug_event
) {
1757 return drv
->bdrv_debug_event(bs
, event
);
1761 /**************************************************************/
1762 /* handling of snapshots */
1764 int bdrv_can_snapshot(BlockDriverState
*bs
)
1766 BlockDriver
*drv
= bs
->drv
;
1767 if (!drv
|| bdrv_is_removable(bs
) || bdrv_is_read_only(bs
)) {
1771 if (!drv
->bdrv_snapshot_create
) {
1772 if (bs
->file
!= NULL
) {
1773 return bdrv_can_snapshot(bs
->file
);
1781 int bdrv_snapshot_create(BlockDriverState
*bs
,
1782 QEMUSnapshotInfo
*sn_info
)
1784 BlockDriver
*drv
= bs
->drv
;
1787 if (drv
->bdrv_snapshot_create
)
1788 return drv
->bdrv_snapshot_create(bs
, sn_info
);
1790 return bdrv_snapshot_create(bs
->file
, sn_info
);
1794 int bdrv_snapshot_goto(BlockDriverState
*bs
,
1795 const char *snapshot_id
)
1797 BlockDriver
*drv
= bs
->drv
;
1802 if (drv
->bdrv_snapshot_goto
)
1803 return drv
->bdrv_snapshot_goto(bs
, snapshot_id
);
1806 drv
->bdrv_close(bs
);
1807 ret
= bdrv_snapshot_goto(bs
->file
, snapshot_id
);
1808 open_ret
= drv
->bdrv_open(bs
, bs
->open_flags
);
1810 bdrv_delete(bs
->file
);
1820 int bdrv_snapshot_delete(BlockDriverState
*bs
, const char *snapshot_id
)
1822 BlockDriver
*drv
= bs
->drv
;
1825 if (drv
->bdrv_snapshot_delete
)
1826 return drv
->bdrv_snapshot_delete(bs
, snapshot_id
);
1828 return bdrv_snapshot_delete(bs
->file
, snapshot_id
);
1832 int bdrv_snapshot_list(BlockDriverState
*bs
,
1833 QEMUSnapshotInfo
**psn_info
)
1835 BlockDriver
*drv
= bs
->drv
;
1838 if (drv
->bdrv_snapshot_list
)
1839 return drv
->bdrv_snapshot_list(bs
, psn_info
);
1841 return bdrv_snapshot_list(bs
->file
, psn_info
);
1845 #define NB_SUFFIXES 4
1847 char *get_human_readable_size(char *buf
, int buf_size
, int64_t size
)
1849 static const char suffixes
[NB_SUFFIXES
] = "KMGT";
1854 snprintf(buf
, buf_size
, "%" PRId64
, size
);
1857 for(i
= 0; i
< NB_SUFFIXES
; i
++) {
1858 if (size
< (10 * base
)) {
1859 snprintf(buf
, buf_size
, "%0.1f%c",
1860 (double)size
/ base
,
1863 } else if (size
< (1000 * base
) || i
== (NB_SUFFIXES
- 1)) {
1864 snprintf(buf
, buf_size
, "%" PRId64
"%c",
1865 ((size
+ (base
>> 1)) / base
),
1875 char *bdrv_snapshot_dump(char *buf
, int buf_size
, QEMUSnapshotInfo
*sn
)
1877 char buf1
[128], date_buf
[128], clock_buf
[128];
1887 snprintf(buf
, buf_size
,
1888 "%-10s%-20s%7s%20s%15s",
1889 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1893 ptm
= localtime(&ti
);
1894 strftime(date_buf
, sizeof(date_buf
),
1895 "%Y-%m-%d %H:%M:%S", ptm
);
1897 localtime_r(&ti
, &tm
);
1898 strftime(date_buf
, sizeof(date_buf
),
1899 "%Y-%m-%d %H:%M:%S", &tm
);
1901 secs
= sn
->vm_clock_nsec
/ 1000000000;
1902 snprintf(clock_buf
, sizeof(clock_buf
),
1903 "%02d:%02d:%02d.%03d",
1905 (int)((secs
/ 60) % 60),
1907 (int)((sn
->vm_clock_nsec
/ 1000000) % 1000));
1908 snprintf(buf
, buf_size
,
1909 "%-10s%-20s%7s%20s%15s",
1910 sn
->id_str
, sn
->name
,
1911 get_human_readable_size(buf1
, sizeof(buf1
), sn
->vm_state_size
),
1919 /**************************************************************/
1922 BlockDriverAIOCB
*bdrv_aio_readv(BlockDriverState
*bs
, int64_t sector_num
,
1923 QEMUIOVector
*qiov
, int nb_sectors
,
1924 BlockDriverCompletionFunc
*cb
, void *opaque
)
1926 BlockDriver
*drv
= bs
->drv
;
1927 BlockDriverAIOCB
*ret
;
1931 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1934 ret
= drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
1938 /* Update stats even though technically transfer has not happened. */
1939 bs
->rd_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
1946 BlockDriverAIOCB
*bdrv_aio_writev(BlockDriverState
*bs
, int64_t sector_num
,
1947 QEMUIOVector
*qiov
, int nb_sectors
,
1948 BlockDriverCompletionFunc
*cb
, void *opaque
)
1950 BlockDriver
*drv
= bs
->drv
;
1951 BlockDriverAIOCB
*ret
;
1957 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1960 if (bs
->dirty_bitmap
) {
1961 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1964 ret
= drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
1968 /* Update stats even though technically transfer has not happened. */
1969 bs
->wr_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
1971 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1972 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1980 typedef struct MultiwriteCB
{
1985 BlockDriverCompletionFunc
*cb
;
1987 QEMUIOVector
*free_qiov
;
1992 static void multiwrite_user_cb(MultiwriteCB
*mcb
)
1996 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
1997 mcb
->callbacks
[i
].cb(mcb
->callbacks
[i
].opaque
, mcb
->error
);
1998 if (mcb
->callbacks
[i
].free_qiov
) {
1999 qemu_iovec_destroy(mcb
->callbacks
[i
].free_qiov
);
2001 qemu_free(mcb
->callbacks
[i
].free_qiov
);
2002 qemu_vfree(mcb
->callbacks
[i
].free_buf
);
2006 static void multiwrite_cb(void *opaque
, int ret
)
2008 MultiwriteCB
*mcb
= opaque
;
2010 if (ret
< 0 && !mcb
->error
) {
2012 multiwrite_user_cb(mcb
);
2015 mcb
->num_requests
--;
2016 if (mcb
->num_requests
== 0) {
2017 if (mcb
->error
== 0) {
2018 multiwrite_user_cb(mcb
);
2024 static int multiwrite_req_compare(const void *a
, const void *b
)
2026 const BlockRequest
*req1
= a
, *req2
= b
;
2029 * Note that we can't simply subtract req2->sector from req1->sector
2030 * here as that could overflow the return value.
2032 if (req1
->sector
> req2
->sector
) {
2034 } else if (req1
->sector
< req2
->sector
) {
2042 * Takes a bunch of requests and tries to merge them. Returns the number of
2043 * requests that remain after merging.
2045 static int multiwrite_merge(BlockDriverState
*bs
, BlockRequest
*reqs
,
2046 int num_reqs
, MultiwriteCB
*mcb
)
2050 // Sort requests by start sector
2051 qsort(reqs
, num_reqs
, sizeof(*reqs
), &multiwrite_req_compare
);
2053 // Check if adjacent requests touch the same clusters. If so, combine them,
2054 // filling up gaps with zero sectors.
2056 for (i
= 1; i
< num_reqs
; i
++) {
2058 int64_t oldreq_last
= reqs
[outidx
].sector
+ reqs
[outidx
].nb_sectors
;
2060 // This handles the cases that are valid for all block drivers, namely
2061 // exactly sequential writes and overlapping writes.
2062 if (reqs
[i
].sector
<= oldreq_last
) {
2066 // The block driver may decide that it makes sense to combine requests
2067 // even if there is a gap of some sectors between them. In this case,
2068 // the gap is filled with zeros (therefore only applicable for yet
2069 // unused space in format like qcow2).
2070 if (!merge
&& bs
->drv
->bdrv_merge_requests
) {
2071 merge
= bs
->drv
->bdrv_merge_requests(bs
, &reqs
[outidx
], &reqs
[i
]);
2074 if (reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1 > IOV_MAX
) {
2080 QEMUIOVector
*qiov
= qemu_mallocz(sizeof(*qiov
));
2081 qemu_iovec_init(qiov
,
2082 reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1);
2084 // Add the first request to the merged one. If the requests are
2085 // overlapping, drop the last sectors of the first request.
2086 size
= (reqs
[i
].sector
- reqs
[outidx
].sector
) << 9;
2087 qemu_iovec_concat(qiov
, reqs
[outidx
].qiov
, size
);
2089 // We might need to add some zeros between the two requests
2090 if (reqs
[i
].sector
> oldreq_last
) {
2091 size_t zero_bytes
= (reqs
[i
].sector
- oldreq_last
) << 9;
2092 uint8_t *buf
= qemu_blockalign(bs
, zero_bytes
);
2093 memset(buf
, 0, zero_bytes
);
2094 qemu_iovec_add(qiov
, buf
, zero_bytes
);
2095 mcb
->callbacks
[i
].free_buf
= buf
;
2098 // Add the second request
2099 qemu_iovec_concat(qiov
, reqs
[i
].qiov
, reqs
[i
].qiov
->size
);
2101 reqs
[outidx
].nb_sectors
= qiov
->size
>> 9;
2102 reqs
[outidx
].qiov
= qiov
;
2104 mcb
->callbacks
[i
].free_qiov
= reqs
[outidx
].qiov
;
2107 reqs
[outidx
].sector
= reqs
[i
].sector
;
2108 reqs
[outidx
].nb_sectors
= reqs
[i
].nb_sectors
;
2109 reqs
[outidx
].qiov
= reqs
[i
].qiov
;
2117 * Submit multiple AIO write requests at once.
2119 * On success, the function returns 0 and all requests in the reqs array have
2120 * been submitted. In error case this function returns -1, and any of the
2121 * requests may or may not be submitted yet. In particular, this means that the
2122 * callback will be called for some of the requests, for others it won't. The
2123 * caller must check the error field of the BlockRequest to wait for the right
2124 * callbacks (if error != 0, no callback will be called).
2126 * The implementation may modify the contents of the reqs array, e.g. to merge
2127 * requests. However, the fields opaque and error are left unmodified as they
2128 * are used to signal failure for a single request to the caller.
2130 int bdrv_aio_multiwrite(BlockDriverState
*bs
, BlockRequest
*reqs
, int num_reqs
)
2132 BlockDriverAIOCB
*acb
;
2136 if (num_reqs
== 0) {
2140 // Create MultiwriteCB structure
2141 mcb
= qemu_mallocz(sizeof(*mcb
) + num_reqs
* sizeof(*mcb
->callbacks
));
2142 mcb
->num_requests
= 0;
2143 mcb
->num_callbacks
= num_reqs
;
2145 for (i
= 0; i
< num_reqs
; i
++) {
2146 mcb
->callbacks
[i
].cb
= reqs
[i
].cb
;
2147 mcb
->callbacks
[i
].opaque
= reqs
[i
].opaque
;
2150 // Check for mergable requests
2151 num_reqs
= multiwrite_merge(bs
, reqs
, num_reqs
, mcb
);
2153 // Run the aio requests
2154 for (i
= 0; i
< num_reqs
; i
++) {
2155 acb
= bdrv_aio_writev(bs
, reqs
[i
].sector
, reqs
[i
].qiov
,
2156 reqs
[i
].nb_sectors
, multiwrite_cb
, mcb
);
2159 // We can only fail the whole thing if no request has been
2160 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2161 // complete and report the error in the callback.
2162 if (mcb
->num_requests
== 0) {
2163 reqs
[i
].error
= -EIO
;
2166 mcb
->num_requests
++;
2167 multiwrite_cb(mcb
, -EIO
);
2171 mcb
->num_requests
++;
2182 BlockDriverAIOCB
*bdrv_aio_flush(BlockDriverState
*bs
,
2183 BlockDriverCompletionFunc
*cb
, void *opaque
)
2185 BlockDriver
*drv
= bs
->drv
;
2187 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2188 return bdrv_aio_noop_em(bs
, cb
, opaque
);
2193 return drv
->bdrv_aio_flush(bs
, cb
, opaque
);
2196 void bdrv_aio_cancel(BlockDriverAIOCB
*acb
)
2198 acb
->pool
->cancel(acb
);
2202 /**************************************************************/
2203 /* async block device emulation */
2205 typedef struct BlockDriverAIOCBSync
{
2206 BlockDriverAIOCB common
;
2209 /* vector translation state */
2213 } BlockDriverAIOCBSync
;
2215 static void bdrv_aio_cancel_em(BlockDriverAIOCB
*blockacb
)
2217 BlockDriverAIOCBSync
*acb
=
2218 container_of(blockacb
, BlockDriverAIOCBSync
, common
);
2219 qemu_bh_delete(acb
->bh
);
2221 qemu_aio_release(acb
);
2224 static AIOPool bdrv_em_aio_pool
= {
2225 .aiocb_size
= sizeof(BlockDriverAIOCBSync
),
2226 .cancel
= bdrv_aio_cancel_em
,
2229 static void bdrv_aio_bh_cb(void *opaque
)
2231 BlockDriverAIOCBSync
*acb
= opaque
;
2234 qemu_iovec_from_buffer(acb
->qiov
, acb
->bounce
, acb
->qiov
->size
);
2235 qemu_vfree(acb
->bounce
);
2236 acb
->common
.cb(acb
->common
.opaque
, acb
->ret
);
2237 qemu_bh_delete(acb
->bh
);
2239 qemu_aio_release(acb
);
2242 static BlockDriverAIOCB
*bdrv_aio_rw_vector(BlockDriverState
*bs
,
2246 BlockDriverCompletionFunc
*cb
,
2251 BlockDriverAIOCBSync
*acb
;
2253 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2254 acb
->is_write
= is_write
;
2256 acb
->bounce
= qemu_blockalign(bs
, qiov
->size
);
2259 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2262 qemu_iovec_to_buffer(acb
->qiov
, acb
->bounce
);
2263 acb
->ret
= bdrv_write(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2265 acb
->ret
= bdrv_read(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2268 qemu_bh_schedule(acb
->bh
);
2270 return &acb
->common
;
2273 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
2274 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2275 BlockDriverCompletionFunc
*cb
, void *opaque
)
2277 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 0);
2280 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
2281 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2282 BlockDriverCompletionFunc
*cb
, void *opaque
)
2284 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 1);
2287 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
2288 BlockDriverCompletionFunc
*cb
, void *opaque
)
2290 BlockDriverAIOCBSync
*acb
;
2292 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2293 acb
->is_write
= 1; /* don't bounce in the completion hadler */
2299 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2302 qemu_bh_schedule(acb
->bh
);
2303 return &acb
->common
;
2306 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
2307 BlockDriverCompletionFunc
*cb
, void *opaque
)
2309 BlockDriverAIOCBSync
*acb
;
2311 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2312 acb
->is_write
= 1; /* don't bounce in the completion handler */
2318 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2321 qemu_bh_schedule(acb
->bh
);
2322 return &acb
->common
;
2325 /**************************************************************/
2326 /* sync block device emulation */
2328 static void bdrv_rw_em_cb(void *opaque
, int ret
)
2330 *(int *)opaque
= ret
;
2333 #define NOT_DONE 0x7fffffff
2335 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
2336 uint8_t *buf
, int nb_sectors
)
2339 BlockDriverAIOCB
*acb
;
2343 async_context_push();
2345 async_ret
= NOT_DONE
;
2346 iov
.iov_base
= (void *)buf
;
2347 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2348 qemu_iovec_init_external(&qiov
, &iov
, 1);
2349 acb
= bdrv_aio_readv(bs
, sector_num
, &qiov
, nb_sectors
,
2350 bdrv_rw_em_cb
, &async_ret
);
2356 while (async_ret
== NOT_DONE
) {
2362 async_context_pop();
2366 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
2367 const uint8_t *buf
, int nb_sectors
)
2370 BlockDriverAIOCB
*acb
;
2374 async_context_push();
2376 async_ret
= NOT_DONE
;
2377 iov
.iov_base
= (void *)buf
;
2378 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2379 qemu_iovec_init_external(&qiov
, &iov
, 1);
2380 acb
= bdrv_aio_writev(bs
, sector_num
, &qiov
, nb_sectors
,
2381 bdrv_rw_em_cb
, &async_ret
);
2386 while (async_ret
== NOT_DONE
) {
2391 async_context_pop();
2395 void bdrv_init(void)
2397 module_call_init(MODULE_INIT_BLOCK
);
2400 void bdrv_init_with_whitelist(void)
2402 use_bdrv_whitelist
= 1;
2406 void *qemu_aio_get(AIOPool
*pool
, BlockDriverState
*bs
,
2407 BlockDriverCompletionFunc
*cb
, void *opaque
)
2409 BlockDriverAIOCB
*acb
;
2411 if (pool
->free_aiocb
) {
2412 acb
= pool
->free_aiocb
;
2413 pool
->free_aiocb
= acb
->next
;
2415 acb
= qemu_mallocz(pool
->aiocb_size
);
2420 acb
->opaque
= opaque
;
2424 void qemu_aio_release(void *p
)
2426 BlockDriverAIOCB
*acb
= (BlockDriverAIOCB
*)p
;
2427 AIOPool
*pool
= acb
->pool
;
2428 acb
->next
= pool
->free_aiocb
;
2429 pool
->free_aiocb
= acb
;
2432 /**************************************************************/
2433 /* removable device support */
2436 * Return TRUE if the media is present
2438 int bdrv_is_inserted(BlockDriverState
*bs
)
2440 BlockDriver
*drv
= bs
->drv
;
2444 if (!drv
->bdrv_is_inserted
)
2446 ret
= drv
->bdrv_is_inserted(bs
);
2451 * Return TRUE if the media changed since the last call to this
2452 * function. It is currently only used for floppy disks
2454 int bdrv_media_changed(BlockDriverState
*bs
)
2456 BlockDriver
*drv
= bs
->drv
;
2459 if (!drv
|| !drv
->bdrv_media_changed
)
2462 ret
= drv
->bdrv_media_changed(bs
);
2463 if (ret
== -ENOTSUP
)
2464 ret
= bs
->media_changed
;
2465 bs
->media_changed
= 0;
2470 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2472 int bdrv_eject(BlockDriverState
*bs
, int eject_flag
)
2474 BlockDriver
*drv
= bs
->drv
;
2481 if (!drv
|| !drv
->bdrv_eject
) {
2484 ret
= drv
->bdrv_eject(bs
, eject_flag
);
2486 if (ret
== -ENOTSUP
) {
2495 int bdrv_is_locked(BlockDriverState
*bs
)
2501 * Lock or unlock the media (if it is locked, the user won't be able
2502 * to eject it manually).
2504 void bdrv_set_locked(BlockDriverState
*bs
, int locked
)
2506 BlockDriver
*drv
= bs
->drv
;
2508 bs
->locked
= locked
;
2509 if (drv
&& drv
->bdrv_set_locked
) {
2510 drv
->bdrv_set_locked(bs
, locked
);
2514 /* needed for generic scsi interface */
2516 int bdrv_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
2518 BlockDriver
*drv
= bs
->drv
;
2520 if (drv
&& drv
->bdrv_ioctl
)
2521 return drv
->bdrv_ioctl(bs
, req
, buf
);
2525 BlockDriverAIOCB
*bdrv_aio_ioctl(BlockDriverState
*bs
,
2526 unsigned long int req
, void *buf
,
2527 BlockDriverCompletionFunc
*cb
, void *opaque
)
2529 BlockDriver
*drv
= bs
->drv
;
2531 if (drv
&& drv
->bdrv_aio_ioctl
)
2532 return drv
->bdrv_aio_ioctl(bs
, req
, buf
, cb
, opaque
);
2538 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
2540 return qemu_memalign((bs
&& bs
->buffer_alignment
) ? bs
->buffer_alignment
: 512, size
);
2543 void bdrv_set_dirty_tracking(BlockDriverState
*bs
, int enable
)
2545 int64_t bitmap_size
;
2547 bs
->dirty_count
= 0;
2549 if (!bs
->dirty_bitmap
) {
2550 bitmap_size
= (bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
) +
2551 BDRV_SECTORS_PER_DIRTY_CHUNK
* 8 - 1;
2552 bitmap_size
/= BDRV_SECTORS_PER_DIRTY_CHUNK
* 8;
2554 bs
->dirty_bitmap
= qemu_mallocz(bitmap_size
);
2557 if (bs
->dirty_bitmap
) {
2558 qemu_free(bs
->dirty_bitmap
);
2559 bs
->dirty_bitmap
= NULL
;
2564 int bdrv_get_dirty(BlockDriverState
*bs
, int64_t sector
)
2566 int64_t chunk
= sector
/ (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK
;
2568 if (bs
->dirty_bitmap
&&
2569 (sector
<< BDRV_SECTOR_BITS
) < bdrv_getlength(bs
)) {
2570 return bs
->dirty_bitmap
[chunk
/ (sizeof(unsigned long) * 8)] &
2571 (1 << (chunk
% (sizeof(unsigned long) * 8)));
2577 void bdrv_reset_dirty(BlockDriverState
*bs
, int64_t cur_sector
,
2580 set_dirty_bitmap(bs
, cur_sector
, nr_sectors
, 0);
2583 int64_t bdrv_get_dirty_count(BlockDriverState
*bs
)
2585 return bs
->dirty_count
;