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 /* The device to use for VM snapshots */
67 static BlockDriverState
*bs_snapshots
;
69 /* If non-zero, use only whitelisted block drivers */
70 static int use_bdrv_whitelist
;
72 int path_is_absolute(const char *path
)
76 /* specific case for names like: "\\.\d:" */
77 if (*path
== '/' || *path
== '\\')
80 p
= strchr(path
, ':');
86 return (*p
== '/' || *p
== '\\');
92 /* if filename is absolute, just copy it to dest. Otherwise, build a
93 path to it by considering it is relative to base_path. URL are
95 void path_combine(char *dest
, int dest_size
,
96 const char *base_path
,
104 if (path_is_absolute(filename
)) {
105 pstrcpy(dest
, dest_size
, filename
);
107 p
= strchr(base_path
, ':');
112 p1
= strrchr(base_path
, '/');
116 p2
= strrchr(base_path
, '\\');
128 if (len
> dest_size
- 1)
130 memcpy(dest
, base_path
, len
);
132 pstrcat(dest
, dest_size
, filename
);
136 void bdrv_register(BlockDriver
*bdrv
)
138 if (!bdrv
->bdrv_aio_readv
) {
139 /* add AIO emulation layer */
140 bdrv
->bdrv_aio_readv
= bdrv_aio_readv_em
;
141 bdrv
->bdrv_aio_writev
= bdrv_aio_writev_em
;
142 } else if (!bdrv
->bdrv_read
) {
143 /* add synchronous IO emulation layer */
144 bdrv
->bdrv_read
= bdrv_read_em
;
145 bdrv
->bdrv_write
= bdrv_write_em
;
148 if (!bdrv
->bdrv_aio_flush
)
149 bdrv
->bdrv_aio_flush
= bdrv_aio_flush_em
;
151 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
154 /* create a new block device (by default it is empty) */
155 BlockDriverState
*bdrv_new(const char *device_name
)
157 BlockDriverState
*bs
;
159 bs
= qemu_mallocz(sizeof(BlockDriverState
));
160 pstrcpy(bs
->device_name
, sizeof(bs
->device_name
), device_name
);
161 if (device_name
[0] != '\0') {
162 QTAILQ_INSERT_TAIL(&bdrv_states
, bs
, list
);
167 BlockDriver
*bdrv_find_format(const char *format_name
)
170 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
171 if (!strcmp(drv1
->format_name
, format_name
)) {
178 static int bdrv_is_whitelisted(BlockDriver
*drv
)
180 static const char *whitelist
[] = {
181 CONFIG_BDRV_WHITELIST
186 return 1; /* no whitelist, anything goes */
188 for (p
= whitelist
; *p
; p
++) {
189 if (!strcmp(drv
->format_name
, *p
)) {
196 BlockDriver
*bdrv_find_whitelisted_format(const char *format_name
)
198 BlockDriver
*drv
= bdrv_find_format(format_name
);
199 return drv
&& bdrv_is_whitelisted(drv
) ? drv
: NULL
;
202 int bdrv_create(BlockDriver
*drv
, const char* filename
,
203 QEMUOptionParameter
*options
)
205 if (!drv
->bdrv_create
)
208 return drv
->bdrv_create(filename
, options
);
211 int bdrv_create_file(const char* filename
, QEMUOptionParameter
*options
)
215 drv
= bdrv_find_protocol(filename
);
217 drv
= bdrv_find_format("file");
220 return bdrv_create(drv
, filename
, options
);
224 void get_tmp_filename(char *filename
, int size
)
226 char temp_dir
[MAX_PATH
];
228 GetTempPath(MAX_PATH
, temp_dir
);
229 GetTempFileName(temp_dir
, "qem", 0, filename
);
232 void get_tmp_filename(char *filename
, int size
)
236 /* XXX: race condition possible */
237 tmpdir
= getenv("TMPDIR");
240 snprintf(filename
, size
, "%s/vl.XXXXXX", tmpdir
);
241 fd
= mkstemp(filename
);
247 static int is_windows_drive_prefix(const char *filename
)
249 return (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
250 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
254 int is_windows_drive(const char *filename
)
256 if (is_windows_drive_prefix(filename
) &&
259 if (strstart(filename
, "\\\\.\\", NULL
) ||
260 strstart(filename
, "//./", NULL
))
267 * Detect host devices. By convention, /dev/cdrom[N] is always
268 * recognized as a host CDROM.
270 static BlockDriver
*find_hdev_driver(const char *filename
)
272 int score_max
= 0, score
;
273 BlockDriver
*drv
= NULL
, *d
;
275 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
276 if (d
->bdrv_probe_device
) {
277 score
= d
->bdrv_probe_device(filename
);
278 if (score
> score_max
) {
288 BlockDriver
*bdrv_find_protocol(const char *filename
)
295 /* TODO Drivers without bdrv_file_open must be specified explicitly */
298 * XXX(hch): we really should not let host device detection
299 * override an explicit protocol specification, but moving this
300 * later breaks access to device names with colons in them.
301 * Thanks to the brain-dead persistent naming schemes on udev-
302 * based Linux systems those actually are quite common.
304 drv1
= find_hdev_driver(filename
);
310 if (is_windows_drive(filename
) ||
311 is_windows_drive_prefix(filename
))
312 return bdrv_find_format("file");
315 p
= strchr(filename
, ':');
317 return bdrv_find_format("file");
320 if (len
> sizeof(protocol
) - 1)
321 len
= sizeof(protocol
) - 1;
322 memcpy(protocol
, filename
, len
);
323 protocol
[len
] = '\0';
324 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
325 if (drv1
->protocol_name
&&
326 !strcmp(drv1
->protocol_name
, protocol
)) {
333 static int find_image_format(const char *filename
, BlockDriver
**pdrv
)
335 int ret
, score
, score_max
;
336 BlockDriver
*drv1
, *drv
;
338 BlockDriverState
*bs
;
340 ret
= bdrv_file_open(&bs
, filename
, 0);
346 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
347 if (bs
->sg
|| !bdrv_is_inserted(bs
)) {
349 drv
= bdrv_find_format("raw");
357 ret
= bdrv_pread(bs
, 0, buf
, sizeof(buf
));
366 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
367 if (drv1
->bdrv_probe
) {
368 score
= drv1
->bdrv_probe(buf
, ret
, filename
);
369 if (score
> score_max
) {
383 * Set the current 'total_sectors' value
385 static int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
387 BlockDriver
*drv
= bs
->drv
;
389 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
393 /* query actual device if possible, otherwise just trust the hint */
394 if (drv
->bdrv_getlength
) {
395 int64_t length
= drv
->bdrv_getlength(bs
);
399 hint
= length
>> BDRV_SECTOR_BITS
;
402 bs
->total_sectors
= hint
;
407 * Common part for opening disk images and files
409 static int bdrv_open_common(BlockDriverState
*bs
, const char *filename
,
410 int flags
, BlockDriver
*drv
)
417 bs
->total_sectors
= 0;
420 bs
->open_flags
= flags
;
421 /* buffer_alignment defaulted to 512, drivers can change this value */
422 bs
->buffer_alignment
= 512;
424 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
426 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
)) {
431 bs
->opaque
= qemu_mallocz(drv
->instance_size
);
434 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
435 * write cache to the guest. We do need the fdatasync to flush
436 * out transactions for block allocations, and we maybe have a
437 * volatile write cache in our backing device to deal with.
439 if (flags
& (BDRV_O_CACHE_WB
|BDRV_O_NOCACHE
))
440 bs
->enable_write_cache
= 1;
443 * Clear flags that are internal to the block layer before opening the
446 open_flags
= flags
& ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
449 * Snapshots should be writeable.
451 if (bs
->is_temporary
) {
452 open_flags
|= BDRV_O_RDWR
;
455 /* Open the image, either directly or using a protocol */
456 if (drv
->bdrv_file_open
) {
457 ret
= drv
->bdrv_file_open(bs
, filename
, open_flags
);
459 ret
= bdrv_file_open(&bs
->file
, filename
, open_flags
);
461 ret
= drv
->bdrv_open(bs
, open_flags
);
469 bs
->keep_read_only
= bs
->read_only
= !(open_flags
& BDRV_O_RDWR
);
471 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
477 if (bs
->is_temporary
) {
485 bdrv_delete(bs
->file
);
488 qemu_free(bs
->opaque
);
495 * Opens a file using a protocol (file, host_device, nbd, ...)
497 int bdrv_file_open(BlockDriverState
**pbs
, const char *filename
, int flags
)
499 BlockDriverState
*bs
;
503 drv
= bdrv_find_protocol(filename
);
509 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
520 * Opens a disk image (raw, qcow2, vmdk, ...)
522 int bdrv_open(BlockDriverState
*bs
, const char *filename
, int flags
,
528 if (flags
& BDRV_O_SNAPSHOT
) {
529 BlockDriverState
*bs1
;
532 BlockDriver
*bdrv_qcow2
;
533 QEMUOptionParameter
*options
;
534 char tmp_filename
[PATH_MAX
];
535 char backing_filename
[PATH_MAX
];
537 /* if snapshot, we create a temporary backing file and open it
538 instead of opening 'filename' directly */
540 /* if there is a backing file, use it */
542 ret
= bdrv_open(bs1
, filename
, 0, drv
);
547 total_size
= bdrv_getlength(bs1
) & BDRV_SECTOR_MASK
;
549 if (bs1
->drv
&& bs1
->drv
->protocol_name
)
554 get_tmp_filename(tmp_filename
, sizeof(tmp_filename
));
556 /* Real path is meaningless for protocols */
558 snprintf(backing_filename
, sizeof(backing_filename
),
560 else if (!realpath(filename
, backing_filename
))
563 bdrv_qcow2
= bdrv_find_format("qcow2");
564 options
= parse_option_parameters("", bdrv_qcow2
->create_options
, NULL
);
566 set_option_parameter_int(options
, BLOCK_OPT_SIZE
, total_size
);
567 set_option_parameter(options
, BLOCK_OPT_BACKING_FILE
, backing_filename
);
569 set_option_parameter(options
, BLOCK_OPT_BACKING_FMT
,
573 ret
= bdrv_create(bdrv_qcow2
, tmp_filename
, options
);
574 free_option_parameters(options
);
579 filename
= tmp_filename
;
581 bs
->is_temporary
= 1;
584 /* Find the right image format driver */
586 ret
= find_image_format(filename
, &drv
);
591 goto unlink_and_fail
;
595 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
597 goto unlink_and_fail
;
602 /* If there is a backing file, use it */
603 if ((flags
& BDRV_O_NO_BACKING
) == 0 && bs
->backing_file
[0] != '\0') {
604 char backing_filename
[PATH_MAX
];
606 BlockDriver
*back_drv
= NULL
;
608 bs
->backing_hd
= bdrv_new("");
609 path_combine(backing_filename
, sizeof(backing_filename
),
610 filename
, bs
->backing_file
);
611 if (bs
->backing_format
[0] != '\0')
612 back_drv
= bdrv_find_format(bs
->backing_format
);
614 /* backing files always opened read-only */
616 flags
& ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
618 ret
= bdrv_open(bs
->backing_hd
, backing_filename
, back_flags
, back_drv
);
623 if (bs
->is_temporary
) {
624 bs
->backing_hd
->keep_read_only
= !(flags
& BDRV_O_RDWR
);
626 /* base image inherits from "parent" */
627 bs
->backing_hd
->keep_read_only
= bs
->keep_read_only
;
631 if (!bdrv_key_required(bs
)) {
632 /* call the change callback */
633 bs
->media_changed
= 1;
635 bs
->change_cb(bs
->change_opaque
);
641 if (bs
->is_temporary
) {
647 void bdrv_close(BlockDriverState
*bs
)
650 if (bs
== bs_snapshots
) {
653 if (bs
->backing_hd
) {
654 bdrv_delete(bs
->backing_hd
);
655 bs
->backing_hd
= NULL
;
657 bs
->drv
->bdrv_close(bs
);
658 qemu_free(bs
->opaque
);
660 if (bs
->is_temporary
) {
661 unlink(bs
->filename
);
667 if (bs
->file
!= NULL
) {
668 bdrv_close(bs
->file
);
671 /* call the change callback */
672 bs
->media_changed
= 1;
674 bs
->change_cb(bs
->change_opaque
);
678 void bdrv_close_all(void)
680 BlockDriverState
*bs
;
682 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
687 void bdrv_delete(BlockDriverState
*bs
)
691 /* remove from list, if necessary */
692 if (bs
->device_name
[0] != '\0') {
693 QTAILQ_REMOVE(&bdrv_states
, bs
, list
);
697 if (bs
->file
!= NULL
) {
698 bdrv_delete(bs
->file
);
701 assert(bs
!= bs_snapshots
);
705 int bdrv_attach(BlockDriverState
*bs
, DeviceState
*qdev
)
714 void bdrv_detach(BlockDriverState
*bs
, DeviceState
*qdev
)
716 assert(bs
->peer
== qdev
);
720 DeviceState
*bdrv_get_attached(BlockDriverState
*bs
)
726 * Run consistency checks on an image
728 * Returns 0 if the check could be completed (it doesn't mean that the image is
729 * free of errors) or -errno when an internal error occured. The results of the
730 * check are stored in res.
732 int bdrv_check(BlockDriverState
*bs
, BdrvCheckResult
*res
)
734 if (bs
->drv
->bdrv_check
== NULL
) {
738 memset(res
, 0, sizeof(*res
));
739 return bs
->drv
->bdrv_check(bs
, res
);
742 #define COMMIT_BUF_SECTORS 2048
744 /* commit COW file into the raw image */
745 int bdrv_commit(BlockDriverState
*bs
)
747 BlockDriver
*drv
= bs
->drv
;
748 int64_t sector
, total_sectors
;
749 int n
, ro
, open_flags
;
750 int ret
= 0, rw_ret
= 0;
753 BlockDriverState
*bs_rw
, *bs_ro
;
758 if (!bs
->backing_hd
) {
762 if (bs
->backing_hd
->keep_read_only
) {
766 ro
= bs
->backing_hd
->read_only
;
767 strncpy(filename
, bs
->backing_hd
->filename
, sizeof(filename
));
768 open_flags
= bs
->backing_hd
->open_flags
;
772 bdrv_delete(bs
->backing_hd
);
773 bs
->backing_hd
= NULL
;
774 bs_rw
= bdrv_new("");
775 rw_ret
= bdrv_open(bs_rw
, filename
, open_flags
| BDRV_O_RDWR
, drv
);
778 /* try to re-open read-only */
779 bs_ro
= bdrv_new("");
780 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
, drv
);
783 /* drive not functional anymore */
787 bs
->backing_hd
= bs_ro
;
790 bs
->backing_hd
= bs_rw
;
793 total_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
794 buf
= qemu_malloc(COMMIT_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
796 for (sector
= 0; sector
< total_sectors
; sector
+= n
) {
797 if (drv
->bdrv_is_allocated(bs
, sector
, COMMIT_BUF_SECTORS
, &n
)) {
799 if (bdrv_read(bs
, sector
, buf
, n
) != 0) {
804 if (bdrv_write(bs
->backing_hd
, sector
, buf
, n
) != 0) {
811 if (drv
->bdrv_make_empty
) {
812 ret
= drv
->bdrv_make_empty(bs
);
817 * Make sure all data we wrote to the backing device is actually
821 bdrv_flush(bs
->backing_hd
);
828 bdrv_delete(bs
->backing_hd
);
829 bs
->backing_hd
= NULL
;
830 bs_ro
= bdrv_new("");
831 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
, drv
);
834 /* drive not functional anymore */
838 bs
->backing_hd
= bs_ro
;
839 bs
->backing_hd
->keep_read_only
= 0;
845 void bdrv_commit_all(void)
847 BlockDriverState
*bs
;
849 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
857 * -EINVAL - backing format specified, but no file
858 * -ENOSPC - can't update the backing file because no space is left in the
860 * -ENOTSUP - format driver doesn't support changing the backing file
862 int bdrv_change_backing_file(BlockDriverState
*bs
,
863 const char *backing_file
, const char *backing_fmt
)
865 BlockDriver
*drv
= bs
->drv
;
867 if (drv
->bdrv_change_backing_file
!= NULL
) {
868 return drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
874 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
879 if (!bdrv_is_inserted(bs
))
885 len
= bdrv_getlength(bs
);
890 if ((offset
> len
) || (len
- offset
< size
))
896 static int bdrv_check_request(BlockDriverState
*bs
, int64_t sector_num
,
899 return bdrv_check_byte_request(bs
, sector_num
* BDRV_SECTOR_SIZE
,
900 nb_sectors
* BDRV_SECTOR_SIZE
);
903 /* return < 0 if error. See bdrv_write() for the return codes */
904 int bdrv_read(BlockDriverState
*bs
, int64_t sector_num
,
905 uint8_t *buf
, int nb_sectors
)
907 BlockDriver
*drv
= bs
->drv
;
911 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
914 return drv
->bdrv_read(bs
, sector_num
, buf
, nb_sectors
);
917 static void set_dirty_bitmap(BlockDriverState
*bs
, int64_t sector_num
,
918 int nb_sectors
, int dirty
)
921 unsigned long val
, idx
, bit
;
923 start
= sector_num
/ BDRV_SECTORS_PER_DIRTY_CHUNK
;
924 end
= (sector_num
+ nb_sectors
- 1) / BDRV_SECTORS_PER_DIRTY_CHUNK
;
926 for (; start
<= end
; start
++) {
927 idx
= start
/ (sizeof(unsigned long) * 8);
928 bit
= start
% (sizeof(unsigned long) * 8);
929 val
= bs
->dirty_bitmap
[idx
];
931 if (!(val
& (1 << bit
))) {
936 if (val
& (1 << bit
)) {
941 bs
->dirty_bitmap
[idx
] = val
;
945 /* Return < 0 if error. Important errors are:
946 -EIO generic I/O error (may happen for all errors)
947 -ENOMEDIUM No media inserted.
948 -EINVAL Invalid sector number or nb_sectors
949 -EACCES Trying to write a read-only device
951 int bdrv_write(BlockDriverState
*bs
, int64_t sector_num
,
952 const uint8_t *buf
, int nb_sectors
)
954 BlockDriver
*drv
= bs
->drv
;
959 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
962 if (bs
->dirty_bitmap
) {
963 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
966 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
967 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
970 return drv
->bdrv_write(bs
, sector_num
, buf
, nb_sectors
);
973 int bdrv_pread(BlockDriverState
*bs
, int64_t offset
,
974 void *buf
, int count1
)
976 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
977 int len
, nb_sectors
, count
;
982 /* first read to align to sector start */
983 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
986 sector_num
= offset
>> BDRV_SECTOR_BITS
;
988 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
990 memcpy(buf
, tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), len
);
998 /* read the sectors "in place" */
999 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1000 if (nb_sectors
> 0) {
1001 if ((ret
= bdrv_read(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1003 sector_num
+= nb_sectors
;
1004 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1009 /* add data from the last sector */
1011 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1013 memcpy(buf
, tmp_buf
, count
);
1018 int bdrv_pwrite(BlockDriverState
*bs
, int64_t offset
,
1019 const void *buf
, int count1
)
1021 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1022 int len
, nb_sectors
, count
;
1027 /* first write to align to sector start */
1028 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1031 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1033 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1035 memcpy(tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), buf
, len
);
1036 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1045 /* write the sectors "in place" */
1046 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1047 if (nb_sectors
> 0) {
1048 if ((ret
= bdrv_write(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1050 sector_num
+= nb_sectors
;
1051 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1056 /* add data from the last sector */
1058 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1060 memcpy(tmp_buf
, buf
, count
);
1061 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1068 * Writes to the file and ensures that no writes are reordered across this
1069 * request (acts as a barrier)
1071 * Returns 0 on success, -errno in error cases.
1073 int bdrv_pwrite_sync(BlockDriverState
*bs
, int64_t offset
,
1074 const void *buf
, int count
)
1078 ret
= bdrv_pwrite(bs
, offset
, buf
, count
);
1083 /* No flush needed for cache=writethrough, it uses O_DSYNC */
1084 if ((bs
->open_flags
& BDRV_O_CACHE_MASK
) != 0) {
1092 * Writes to the file and ensures that no writes are reordered across this
1093 * request (acts as a barrier)
1095 * Returns 0 on success, -errno in error cases.
1097 int bdrv_write_sync(BlockDriverState
*bs
, int64_t sector_num
,
1098 const uint8_t *buf
, int nb_sectors
)
1100 return bdrv_pwrite_sync(bs
, BDRV_SECTOR_SIZE
* sector_num
,
1101 buf
, BDRV_SECTOR_SIZE
* nb_sectors
);
1105 * Truncate file to 'offset' bytes (needed only for file protocols)
1107 int bdrv_truncate(BlockDriverState
*bs
, int64_t offset
)
1109 BlockDriver
*drv
= bs
->drv
;
1113 if (!drv
->bdrv_truncate
)
1117 ret
= drv
->bdrv_truncate(bs
, offset
);
1119 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
1125 * Length of a file in bytes. Return < 0 if error or unknown.
1127 int64_t bdrv_getlength(BlockDriverState
*bs
)
1129 BlockDriver
*drv
= bs
->drv
;
1133 /* Fixed size devices use the total_sectors value for speed instead of
1134 issuing a length query (like lseek) on each call. Also, legacy block
1135 drivers don't provide a bdrv_getlength function and must use
1137 if (!bs
->growable
|| !drv
->bdrv_getlength
) {
1138 return bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1140 return drv
->bdrv_getlength(bs
);
1143 /* return 0 as number of sectors if no device present or error */
1144 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
1147 length
= bdrv_getlength(bs
);
1151 length
= length
>> BDRV_SECTOR_BITS
;
1152 *nb_sectors_ptr
= length
;
1156 uint8_t boot_ind
; /* 0x80 - active */
1157 uint8_t head
; /* starting head */
1158 uint8_t sector
; /* starting sector */
1159 uint8_t cyl
; /* starting cylinder */
1160 uint8_t sys_ind
; /* What partition type */
1161 uint8_t end_head
; /* end head */
1162 uint8_t end_sector
; /* end sector */
1163 uint8_t end_cyl
; /* end cylinder */
1164 uint32_t start_sect
; /* starting sector counting from 0 */
1165 uint32_t nr_sects
; /* nr of sectors in partition */
1166 } __attribute__((packed
));
1168 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1169 static int guess_disk_lchs(BlockDriverState
*bs
,
1170 int *pcylinders
, int *pheads
, int *psectors
)
1172 uint8_t buf
[BDRV_SECTOR_SIZE
];
1173 int ret
, i
, heads
, sectors
, cylinders
;
1174 struct partition
*p
;
1176 uint64_t nb_sectors
;
1178 bdrv_get_geometry(bs
, &nb_sectors
);
1180 ret
= bdrv_read(bs
, 0, buf
, 1);
1183 /* test msdos magic */
1184 if (buf
[510] != 0x55 || buf
[511] != 0xaa)
1186 for(i
= 0; i
< 4; i
++) {
1187 p
= ((struct partition
*)(buf
+ 0x1be)) + i
;
1188 nr_sects
= le32_to_cpu(p
->nr_sects
);
1189 if (nr_sects
&& p
->end_head
) {
1190 /* We make the assumption that the partition terminates on
1191 a cylinder boundary */
1192 heads
= p
->end_head
+ 1;
1193 sectors
= p
->end_sector
& 63;
1196 cylinders
= nb_sectors
/ (heads
* sectors
);
1197 if (cylinders
< 1 || cylinders
> 16383)
1200 *psectors
= sectors
;
1201 *pcylinders
= cylinders
;
1203 printf("guessed geometry: LCHS=%d %d %d\n",
1204 cylinders
, heads
, sectors
);
1212 void bdrv_guess_geometry(BlockDriverState
*bs
, int *pcyls
, int *pheads
, int *psecs
)
1214 int translation
, lba_detected
= 0;
1215 int cylinders
, heads
, secs
;
1216 uint64_t nb_sectors
;
1218 /* if a geometry hint is available, use it */
1219 bdrv_get_geometry(bs
, &nb_sectors
);
1220 bdrv_get_geometry_hint(bs
, &cylinders
, &heads
, &secs
);
1221 translation
= bdrv_get_translation_hint(bs
);
1222 if (cylinders
!= 0) {
1227 if (guess_disk_lchs(bs
, &cylinders
, &heads
, &secs
) == 0) {
1229 /* if heads > 16, it means that a BIOS LBA
1230 translation was active, so the default
1231 hardware geometry is OK */
1233 goto default_geometry
;
1238 /* disable any translation to be in sync with
1239 the logical geometry */
1240 if (translation
== BIOS_ATA_TRANSLATION_AUTO
) {
1241 bdrv_set_translation_hint(bs
,
1242 BIOS_ATA_TRANSLATION_NONE
);
1247 /* if no geometry, use a standard physical disk geometry */
1248 cylinders
= nb_sectors
/ (16 * 63);
1250 if (cylinders
> 16383)
1252 else if (cylinders
< 2)
1257 if ((lba_detected
== 1) && (translation
== BIOS_ATA_TRANSLATION_AUTO
)) {
1258 if ((*pcyls
* *pheads
) <= 131072) {
1259 bdrv_set_translation_hint(bs
,
1260 BIOS_ATA_TRANSLATION_LARGE
);
1262 bdrv_set_translation_hint(bs
,
1263 BIOS_ATA_TRANSLATION_LBA
);
1267 bdrv_set_geometry_hint(bs
, *pcyls
, *pheads
, *psecs
);
1271 void bdrv_set_geometry_hint(BlockDriverState
*bs
,
1272 int cyls
, int heads
, int secs
)
1279 void bdrv_set_type_hint(BlockDriverState
*bs
, int type
)
1282 bs
->removable
= ((type
== BDRV_TYPE_CDROM
||
1283 type
== BDRV_TYPE_FLOPPY
));
1286 void bdrv_set_translation_hint(BlockDriverState
*bs
, int translation
)
1288 bs
->translation
= translation
;
1291 void bdrv_get_geometry_hint(BlockDriverState
*bs
,
1292 int *pcyls
, int *pheads
, int *psecs
)
1295 *pheads
= bs
->heads
;
1299 int bdrv_get_type_hint(BlockDriverState
*bs
)
1304 int bdrv_get_translation_hint(BlockDriverState
*bs
)
1306 return bs
->translation
;
1309 void bdrv_set_on_error(BlockDriverState
*bs
, BlockErrorAction on_read_error
,
1310 BlockErrorAction on_write_error
)
1312 bs
->on_read_error
= on_read_error
;
1313 bs
->on_write_error
= on_write_error
;
1316 BlockErrorAction
bdrv_get_on_error(BlockDriverState
*bs
, int is_read
)
1318 return is_read
? bs
->on_read_error
: bs
->on_write_error
;
1321 void bdrv_set_removable(BlockDriverState
*bs
, int removable
)
1323 bs
->removable
= removable
;
1324 if (removable
&& bs
== bs_snapshots
) {
1325 bs_snapshots
= NULL
;
1329 int bdrv_is_removable(BlockDriverState
*bs
)
1331 return bs
->removable
;
1334 int bdrv_is_read_only(BlockDriverState
*bs
)
1336 return bs
->read_only
;
1339 int bdrv_is_sg(BlockDriverState
*bs
)
1344 int bdrv_enable_write_cache(BlockDriverState
*bs
)
1346 return bs
->enable_write_cache
;
1349 /* XXX: no longer used */
1350 void bdrv_set_change_cb(BlockDriverState
*bs
,
1351 void (*change_cb
)(void *opaque
), void *opaque
)
1353 bs
->change_cb
= change_cb
;
1354 bs
->change_opaque
= opaque
;
1357 int bdrv_is_encrypted(BlockDriverState
*bs
)
1359 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1361 return bs
->encrypted
;
1364 int bdrv_key_required(BlockDriverState
*bs
)
1366 BlockDriverState
*backing_hd
= bs
->backing_hd
;
1368 if (backing_hd
&& backing_hd
->encrypted
&& !backing_hd
->valid_key
)
1370 return (bs
->encrypted
&& !bs
->valid_key
);
1373 int bdrv_set_key(BlockDriverState
*bs
, const char *key
)
1376 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
) {
1377 ret
= bdrv_set_key(bs
->backing_hd
, key
);
1383 if (!bs
->encrypted
) {
1385 } else if (!bs
->drv
|| !bs
->drv
->bdrv_set_key
) {
1388 ret
= bs
->drv
->bdrv_set_key(bs
, key
);
1391 } else if (!bs
->valid_key
) {
1393 /* call the change callback now, we skipped it on open */
1394 bs
->media_changed
= 1;
1396 bs
->change_cb(bs
->change_opaque
);
1401 void bdrv_get_format(BlockDriverState
*bs
, char *buf
, int buf_size
)
1406 pstrcpy(buf
, buf_size
, bs
->drv
->format_name
);
1410 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
1415 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
1416 it(opaque
, drv
->format_name
);
1420 BlockDriverState
*bdrv_find(const char *name
)
1422 BlockDriverState
*bs
;
1424 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1425 if (!strcmp(name
, bs
->device_name
)) {
1432 BlockDriverState
*bdrv_next(BlockDriverState
*bs
)
1435 return QTAILQ_FIRST(&bdrv_states
);
1437 return QTAILQ_NEXT(bs
, list
);
1440 void bdrv_iterate(void (*it
)(void *opaque
, BlockDriverState
*bs
), void *opaque
)
1442 BlockDriverState
*bs
;
1444 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1449 const char *bdrv_get_device_name(BlockDriverState
*bs
)
1451 return bs
->device_name
;
1454 void bdrv_flush(BlockDriverState
*bs
)
1456 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
1460 if (bs
->drv
&& bs
->drv
->bdrv_flush
)
1461 bs
->drv
->bdrv_flush(bs
);
1464 void bdrv_flush_all(void)
1466 BlockDriverState
*bs
;
1468 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1469 if (bs
->drv
&& !bdrv_is_read_only(bs
) &&
1470 (!bdrv_is_removable(bs
) || bdrv_is_inserted(bs
))) {
1476 int bdrv_has_zero_init(BlockDriverState
*bs
)
1480 if (bs
->drv
->bdrv_has_zero_init
) {
1481 return bs
->drv
->bdrv_has_zero_init(bs
);
1488 * Returns true iff the specified sector is present in the disk image. Drivers
1489 * not implementing the functionality are assumed to not support backing files,
1490 * hence all their sectors are reported as allocated.
1492 * 'pnum' is set to the number of sectors (including and immediately following
1493 * the specified sector) that are known to be in the same
1494 * allocated/unallocated state.
1496 * 'nb_sectors' is the max value 'pnum' should be set to.
1498 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
,
1502 if (!bs
->drv
->bdrv_is_allocated
) {
1503 if (sector_num
>= bs
->total_sectors
) {
1507 n
= bs
->total_sectors
- sector_num
;
1508 *pnum
= (n
< nb_sectors
) ? (n
) : (nb_sectors
);
1511 return bs
->drv
->bdrv_is_allocated(bs
, sector_num
, nb_sectors
, pnum
);
1514 void bdrv_mon_event(const BlockDriverState
*bdrv
,
1515 BlockMonEventAction action
, int is_read
)
1518 const char *action_str
;
1521 case BDRV_ACTION_REPORT
:
1522 action_str
= "report";
1524 case BDRV_ACTION_IGNORE
:
1525 action_str
= "ignore";
1527 case BDRV_ACTION_STOP
:
1528 action_str
= "stop";
1534 data
= qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1537 is_read
? "read" : "write");
1538 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR
, data
);
1540 qobject_decref(data
);
1543 static void bdrv_print_dict(QObject
*obj
, void *opaque
)
1546 Monitor
*mon
= opaque
;
1548 bs_dict
= qobject_to_qdict(obj
);
1550 monitor_printf(mon
, "%s: type=%s removable=%d",
1551 qdict_get_str(bs_dict
, "device"),
1552 qdict_get_str(bs_dict
, "type"),
1553 qdict_get_bool(bs_dict
, "removable"));
1555 if (qdict_get_bool(bs_dict
, "removable")) {
1556 monitor_printf(mon
, " locked=%d", qdict_get_bool(bs_dict
, "locked"));
1559 if (qdict_haskey(bs_dict
, "inserted")) {
1560 QDict
*qdict
= qobject_to_qdict(qdict_get(bs_dict
, "inserted"));
1562 monitor_printf(mon
, " file=");
1563 monitor_print_filename(mon
, qdict_get_str(qdict
, "file"));
1564 if (qdict_haskey(qdict
, "backing_file")) {
1565 monitor_printf(mon
, " backing_file=");
1566 monitor_print_filename(mon
, qdict_get_str(qdict
, "backing_file"));
1568 monitor_printf(mon
, " ro=%d drv=%s encrypted=%d",
1569 qdict_get_bool(qdict
, "ro"),
1570 qdict_get_str(qdict
, "drv"),
1571 qdict_get_bool(qdict
, "encrypted"));
1573 monitor_printf(mon
, " [not inserted]");
1576 monitor_printf(mon
, "\n");
1579 void bdrv_info_print(Monitor
*mon
, const QObject
*data
)
1581 qlist_iter(qobject_to_qlist(data
), bdrv_print_dict
, mon
);
1584 void bdrv_info(Monitor
*mon
, QObject
**ret_data
)
1587 BlockDriverState
*bs
;
1589 bs_list
= qlist_new();
1591 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1593 const char *type
= "unknown";
1599 case BDRV_TYPE_CDROM
:
1602 case BDRV_TYPE_FLOPPY
:
1607 bs_obj
= qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1608 "'removable': %i, 'locked': %i }",
1609 bs
->device_name
, type
, bs
->removable
,
1614 QDict
*bs_dict
= qobject_to_qdict(bs_obj
);
1616 obj
= qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1617 "'encrypted': %i }",
1618 bs
->filename
, bs
->read_only
,
1619 bs
->drv
->format_name
,
1620 bdrv_is_encrypted(bs
));
1621 if (bs
->backing_file
[0] != '\0') {
1622 QDict
*qdict
= qobject_to_qdict(obj
);
1623 qdict_put(qdict
, "backing_file",
1624 qstring_from_str(bs
->backing_file
));
1627 qdict_put_obj(bs_dict
, "inserted", obj
);
1629 qlist_append_obj(bs_list
, bs_obj
);
1632 *ret_data
= QOBJECT(bs_list
);
1635 static void bdrv_stats_iter(QObject
*data
, void *opaque
)
1638 Monitor
*mon
= opaque
;
1640 qdict
= qobject_to_qdict(data
);
1641 monitor_printf(mon
, "%s:", qdict_get_str(qdict
, "device"));
1643 qdict
= qobject_to_qdict(qdict_get(qdict
, "stats"));
1644 monitor_printf(mon
, " rd_bytes=%" PRId64
1645 " wr_bytes=%" PRId64
1646 " rd_operations=%" PRId64
1647 " wr_operations=%" PRId64
1649 qdict_get_int(qdict
, "rd_bytes"),
1650 qdict_get_int(qdict
, "wr_bytes"),
1651 qdict_get_int(qdict
, "rd_operations"),
1652 qdict_get_int(qdict
, "wr_operations"));
1655 void bdrv_stats_print(Monitor
*mon
, const QObject
*data
)
1657 qlist_iter(qobject_to_qlist(data
), bdrv_stats_iter
, mon
);
1660 static QObject
* bdrv_info_stats_bs(BlockDriverState
*bs
)
1665 res
= qobject_from_jsonf("{ 'stats': {"
1666 "'rd_bytes': %" PRId64
","
1667 "'wr_bytes': %" PRId64
","
1668 "'rd_operations': %" PRId64
","
1669 "'wr_operations': %" PRId64
","
1670 "'wr_highest_offset': %" PRId64
1672 bs
->rd_bytes
, bs
->wr_bytes
,
1673 bs
->rd_ops
, bs
->wr_ops
,
1674 bs
->wr_highest_sector
*
1675 (uint64_t)BDRV_SECTOR_SIZE
);
1676 dict
= qobject_to_qdict(res
);
1678 if (*bs
->device_name
) {
1679 qdict_put(dict
, "device", qstring_from_str(bs
->device_name
));
1683 QObject
*parent
= bdrv_info_stats_bs(bs
->file
);
1684 qdict_put_obj(dict
, "parent", parent
);
1690 void bdrv_info_stats(Monitor
*mon
, QObject
**ret_data
)
1694 BlockDriverState
*bs
;
1696 devices
= qlist_new();
1698 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1699 obj
= bdrv_info_stats_bs(bs
);
1700 qlist_append_obj(devices
, obj
);
1703 *ret_data
= QOBJECT(devices
);
1706 const char *bdrv_get_encrypted_filename(BlockDriverState
*bs
)
1708 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1709 return bs
->backing_file
;
1710 else if (bs
->encrypted
)
1711 return bs
->filename
;
1716 void bdrv_get_backing_filename(BlockDriverState
*bs
,
1717 char *filename
, int filename_size
)
1719 if (!bs
->backing_file
) {
1720 pstrcpy(filename
, filename_size
, "");
1722 pstrcpy(filename
, filename_size
, bs
->backing_file
);
1726 int bdrv_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
1727 const uint8_t *buf
, int nb_sectors
)
1729 BlockDriver
*drv
= bs
->drv
;
1732 if (!drv
->bdrv_write_compressed
)
1734 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1737 if (bs
->dirty_bitmap
) {
1738 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1741 return drv
->bdrv_write_compressed(bs
, sector_num
, buf
, nb_sectors
);
1744 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1746 BlockDriver
*drv
= bs
->drv
;
1749 if (!drv
->bdrv_get_info
)
1751 memset(bdi
, 0, sizeof(*bdi
));
1752 return drv
->bdrv_get_info(bs
, bdi
);
1755 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
1756 int64_t pos
, int size
)
1758 BlockDriver
*drv
= bs
->drv
;
1761 if (drv
->bdrv_save_vmstate
)
1762 return drv
->bdrv_save_vmstate(bs
, buf
, pos
, size
);
1764 return bdrv_save_vmstate(bs
->file
, buf
, pos
, size
);
1768 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
1769 int64_t pos
, int size
)
1771 BlockDriver
*drv
= bs
->drv
;
1774 if (drv
->bdrv_load_vmstate
)
1775 return drv
->bdrv_load_vmstate(bs
, buf
, pos
, size
);
1777 return bdrv_load_vmstate(bs
->file
, buf
, pos
, size
);
1781 void bdrv_debug_event(BlockDriverState
*bs
, BlkDebugEvent event
)
1783 BlockDriver
*drv
= bs
->drv
;
1785 if (!drv
|| !drv
->bdrv_debug_event
) {
1789 return drv
->bdrv_debug_event(bs
, event
);
1793 /**************************************************************/
1794 /* handling of snapshots */
1796 int bdrv_can_snapshot(BlockDriverState
*bs
)
1798 BlockDriver
*drv
= bs
->drv
;
1799 if (!drv
|| bdrv_is_removable(bs
) || bdrv_is_read_only(bs
)) {
1803 if (!drv
->bdrv_snapshot_create
) {
1804 if (bs
->file
!= NULL
) {
1805 return bdrv_can_snapshot(bs
->file
);
1813 int bdrv_is_snapshot(BlockDriverState
*bs
)
1815 return !!(bs
->open_flags
& BDRV_O_SNAPSHOT
);
1818 BlockDriverState
*bdrv_snapshots(void)
1820 BlockDriverState
*bs
;
1823 return bs_snapshots
;
1827 while ((bs
= bdrv_next(bs
))) {
1828 if (bdrv_can_snapshot(bs
)) {
1836 int bdrv_snapshot_create(BlockDriverState
*bs
,
1837 QEMUSnapshotInfo
*sn_info
)
1839 BlockDriver
*drv
= bs
->drv
;
1842 if (drv
->bdrv_snapshot_create
)
1843 return drv
->bdrv_snapshot_create(bs
, sn_info
);
1845 return bdrv_snapshot_create(bs
->file
, sn_info
);
1849 int bdrv_snapshot_goto(BlockDriverState
*bs
,
1850 const char *snapshot_id
)
1852 BlockDriver
*drv
= bs
->drv
;
1857 if (drv
->bdrv_snapshot_goto
)
1858 return drv
->bdrv_snapshot_goto(bs
, snapshot_id
);
1861 drv
->bdrv_close(bs
);
1862 ret
= bdrv_snapshot_goto(bs
->file
, snapshot_id
);
1863 open_ret
= drv
->bdrv_open(bs
, bs
->open_flags
);
1865 bdrv_delete(bs
->file
);
1875 int bdrv_snapshot_delete(BlockDriverState
*bs
, const char *snapshot_id
)
1877 BlockDriver
*drv
= bs
->drv
;
1880 if (drv
->bdrv_snapshot_delete
)
1881 return drv
->bdrv_snapshot_delete(bs
, snapshot_id
);
1883 return bdrv_snapshot_delete(bs
->file
, snapshot_id
);
1887 int bdrv_snapshot_list(BlockDriverState
*bs
,
1888 QEMUSnapshotInfo
**psn_info
)
1890 BlockDriver
*drv
= bs
->drv
;
1893 if (drv
->bdrv_snapshot_list
)
1894 return drv
->bdrv_snapshot_list(bs
, psn_info
);
1896 return bdrv_snapshot_list(bs
->file
, psn_info
);
1900 #define NB_SUFFIXES 4
1902 char *get_human_readable_size(char *buf
, int buf_size
, int64_t size
)
1904 static const char suffixes
[NB_SUFFIXES
] = "KMGT";
1909 snprintf(buf
, buf_size
, "%" PRId64
, size
);
1912 for(i
= 0; i
< NB_SUFFIXES
; i
++) {
1913 if (size
< (10 * base
)) {
1914 snprintf(buf
, buf_size
, "%0.1f%c",
1915 (double)size
/ base
,
1918 } else if (size
< (1000 * base
) || i
== (NB_SUFFIXES
- 1)) {
1919 snprintf(buf
, buf_size
, "%" PRId64
"%c",
1920 ((size
+ (base
>> 1)) / base
),
1930 char *bdrv_snapshot_dump(char *buf
, int buf_size
, QEMUSnapshotInfo
*sn
)
1932 char buf1
[128], date_buf
[128], clock_buf
[128];
1942 snprintf(buf
, buf_size
,
1943 "%-10s%-20s%7s%20s%15s",
1944 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1948 ptm
= localtime(&ti
);
1949 strftime(date_buf
, sizeof(date_buf
),
1950 "%Y-%m-%d %H:%M:%S", ptm
);
1952 localtime_r(&ti
, &tm
);
1953 strftime(date_buf
, sizeof(date_buf
),
1954 "%Y-%m-%d %H:%M:%S", &tm
);
1956 secs
= sn
->vm_clock_nsec
/ 1000000000;
1957 snprintf(clock_buf
, sizeof(clock_buf
),
1958 "%02d:%02d:%02d.%03d",
1960 (int)((secs
/ 60) % 60),
1962 (int)((sn
->vm_clock_nsec
/ 1000000) % 1000));
1963 snprintf(buf
, buf_size
,
1964 "%-10s%-20s%7s%20s%15s",
1965 sn
->id_str
, sn
->name
,
1966 get_human_readable_size(buf1
, sizeof(buf1
), sn
->vm_state_size
),
1974 /**************************************************************/
1977 BlockDriverAIOCB
*bdrv_aio_readv(BlockDriverState
*bs
, int64_t sector_num
,
1978 QEMUIOVector
*qiov
, int nb_sectors
,
1979 BlockDriverCompletionFunc
*cb
, void *opaque
)
1981 BlockDriver
*drv
= bs
->drv
;
1982 BlockDriverAIOCB
*ret
;
1986 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1989 ret
= drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
1993 /* Update stats even though technically transfer has not happened. */
1994 bs
->rd_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
2001 BlockDriverAIOCB
*bdrv_aio_writev(BlockDriverState
*bs
, int64_t sector_num
,
2002 QEMUIOVector
*qiov
, int nb_sectors
,
2003 BlockDriverCompletionFunc
*cb
, void *opaque
)
2005 BlockDriver
*drv
= bs
->drv
;
2006 BlockDriverAIOCB
*ret
;
2012 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2015 if (bs
->dirty_bitmap
) {
2016 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
2019 ret
= drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
2023 /* Update stats even though technically transfer has not happened. */
2024 bs
->wr_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
2026 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
2027 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
2035 typedef struct MultiwriteCB
{
2040 BlockDriverCompletionFunc
*cb
;
2042 QEMUIOVector
*free_qiov
;
2047 static void multiwrite_user_cb(MultiwriteCB
*mcb
)
2051 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2052 mcb
->callbacks
[i
].cb(mcb
->callbacks
[i
].opaque
, mcb
->error
);
2053 if (mcb
->callbacks
[i
].free_qiov
) {
2054 qemu_iovec_destroy(mcb
->callbacks
[i
].free_qiov
);
2056 qemu_free(mcb
->callbacks
[i
].free_qiov
);
2057 qemu_vfree(mcb
->callbacks
[i
].free_buf
);
2061 static void multiwrite_cb(void *opaque
, int ret
)
2063 MultiwriteCB
*mcb
= opaque
;
2065 if (ret
< 0 && !mcb
->error
) {
2069 mcb
->num_requests
--;
2070 if (mcb
->num_requests
== 0) {
2071 multiwrite_user_cb(mcb
);
2076 static int multiwrite_req_compare(const void *a
, const void *b
)
2078 const BlockRequest
*req1
= a
, *req2
= b
;
2081 * Note that we can't simply subtract req2->sector from req1->sector
2082 * here as that could overflow the return value.
2084 if (req1
->sector
> req2
->sector
) {
2086 } else if (req1
->sector
< req2
->sector
) {
2094 * Takes a bunch of requests and tries to merge them. Returns the number of
2095 * requests that remain after merging.
2097 static int multiwrite_merge(BlockDriverState
*bs
, BlockRequest
*reqs
,
2098 int num_reqs
, MultiwriteCB
*mcb
)
2102 // Sort requests by start sector
2103 qsort(reqs
, num_reqs
, sizeof(*reqs
), &multiwrite_req_compare
);
2105 // Check if adjacent requests touch the same clusters. If so, combine them,
2106 // filling up gaps with zero sectors.
2108 for (i
= 1; i
< num_reqs
; i
++) {
2110 int64_t oldreq_last
= reqs
[outidx
].sector
+ reqs
[outidx
].nb_sectors
;
2112 // This handles the cases that are valid for all block drivers, namely
2113 // exactly sequential writes and overlapping writes.
2114 if (reqs
[i
].sector
<= oldreq_last
) {
2118 // The block driver may decide that it makes sense to combine requests
2119 // even if there is a gap of some sectors between them. In this case,
2120 // the gap is filled with zeros (therefore only applicable for yet
2121 // unused space in format like qcow2).
2122 if (!merge
&& bs
->drv
->bdrv_merge_requests
) {
2123 merge
= bs
->drv
->bdrv_merge_requests(bs
, &reqs
[outidx
], &reqs
[i
]);
2126 if (reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1 > IOV_MAX
) {
2132 QEMUIOVector
*qiov
= qemu_mallocz(sizeof(*qiov
));
2133 qemu_iovec_init(qiov
,
2134 reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1);
2136 // Add the first request to the merged one. If the requests are
2137 // overlapping, drop the last sectors of the first request.
2138 size
= (reqs
[i
].sector
- reqs
[outidx
].sector
) << 9;
2139 qemu_iovec_concat(qiov
, reqs
[outidx
].qiov
, size
);
2141 // We might need to add some zeros between the two requests
2142 if (reqs
[i
].sector
> oldreq_last
) {
2143 size_t zero_bytes
= (reqs
[i
].sector
- oldreq_last
) << 9;
2144 uint8_t *buf
= qemu_blockalign(bs
, zero_bytes
);
2145 memset(buf
, 0, zero_bytes
);
2146 qemu_iovec_add(qiov
, buf
, zero_bytes
);
2147 mcb
->callbacks
[i
].free_buf
= buf
;
2150 // Add the second request
2151 qemu_iovec_concat(qiov
, reqs
[i
].qiov
, reqs
[i
].qiov
->size
);
2153 reqs
[outidx
].nb_sectors
= qiov
->size
>> 9;
2154 reqs
[outidx
].qiov
= qiov
;
2156 mcb
->callbacks
[i
].free_qiov
= reqs
[outidx
].qiov
;
2159 reqs
[outidx
].sector
= reqs
[i
].sector
;
2160 reqs
[outidx
].nb_sectors
= reqs
[i
].nb_sectors
;
2161 reqs
[outidx
].qiov
= reqs
[i
].qiov
;
2169 * Submit multiple AIO write requests at once.
2171 * On success, the function returns 0 and all requests in the reqs array have
2172 * been submitted. In error case this function returns -1, and any of the
2173 * requests may or may not be submitted yet. In particular, this means that the
2174 * callback will be called for some of the requests, for others it won't. The
2175 * caller must check the error field of the BlockRequest to wait for the right
2176 * callbacks (if error != 0, no callback will be called).
2178 * The implementation may modify the contents of the reqs array, e.g. to merge
2179 * requests. However, the fields opaque and error are left unmodified as they
2180 * are used to signal failure for a single request to the caller.
2182 int bdrv_aio_multiwrite(BlockDriverState
*bs
, BlockRequest
*reqs
, int num_reqs
)
2184 BlockDriverAIOCB
*acb
;
2188 if (num_reqs
== 0) {
2192 // Create MultiwriteCB structure
2193 mcb
= qemu_mallocz(sizeof(*mcb
) + num_reqs
* sizeof(*mcb
->callbacks
));
2194 mcb
->num_requests
= 0;
2195 mcb
->num_callbacks
= num_reqs
;
2197 for (i
= 0; i
< num_reqs
; i
++) {
2198 mcb
->callbacks
[i
].cb
= reqs
[i
].cb
;
2199 mcb
->callbacks
[i
].opaque
= reqs
[i
].opaque
;
2202 // Check for mergable requests
2203 num_reqs
= multiwrite_merge(bs
, reqs
, num_reqs
, mcb
);
2206 * Run the aio requests. As soon as one request can't be submitted
2207 * successfully, fail all requests that are not yet submitted (we must
2208 * return failure for all requests anyway)
2210 * num_requests cannot be set to the right value immediately: If
2211 * bdrv_aio_writev fails for some request, num_requests would be too high
2212 * and therefore multiwrite_cb() would never recognize the multiwrite
2213 * request as completed. We also cannot use the loop variable i to set it
2214 * when the first request fails because the callback may already have been
2215 * called for previously submitted requests. Thus, num_requests must be
2216 * incremented for each request that is submitted.
2218 * The problem that callbacks may be called early also means that we need
2219 * to take care that num_requests doesn't become 0 before all requests are
2220 * submitted - multiwrite_cb() would consider the multiwrite request
2221 * completed. A dummy request that is "completed" by a manual call to
2222 * multiwrite_cb() takes care of this.
2224 mcb
->num_requests
= 1;
2226 for (i
= 0; i
< num_reqs
; i
++) {
2227 mcb
->num_requests
++;
2228 acb
= bdrv_aio_writev(bs
, reqs
[i
].sector
, reqs
[i
].qiov
,
2229 reqs
[i
].nb_sectors
, multiwrite_cb
, mcb
);
2232 // We can only fail the whole thing if no request has been
2233 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2234 // complete and report the error in the callback.
2238 multiwrite_cb(mcb
, -EIO
);
2244 /* Complete the dummy request */
2245 multiwrite_cb(mcb
, 0);
2250 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2251 reqs
[i
].error
= -EIO
;
2257 BlockDriverAIOCB
*bdrv_aio_flush(BlockDriverState
*bs
,
2258 BlockDriverCompletionFunc
*cb
, void *opaque
)
2260 BlockDriver
*drv
= bs
->drv
;
2262 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2263 return bdrv_aio_noop_em(bs
, cb
, opaque
);
2268 return drv
->bdrv_aio_flush(bs
, cb
, opaque
);
2271 void bdrv_aio_cancel(BlockDriverAIOCB
*acb
)
2273 acb
->pool
->cancel(acb
);
2277 /**************************************************************/
2278 /* async block device emulation */
2280 typedef struct BlockDriverAIOCBSync
{
2281 BlockDriverAIOCB common
;
2284 /* vector translation state */
2288 } BlockDriverAIOCBSync
;
2290 static void bdrv_aio_cancel_em(BlockDriverAIOCB
*blockacb
)
2292 BlockDriverAIOCBSync
*acb
=
2293 container_of(blockacb
, BlockDriverAIOCBSync
, common
);
2294 qemu_bh_delete(acb
->bh
);
2296 qemu_aio_release(acb
);
2299 static AIOPool bdrv_em_aio_pool
= {
2300 .aiocb_size
= sizeof(BlockDriverAIOCBSync
),
2301 .cancel
= bdrv_aio_cancel_em
,
2304 static void bdrv_aio_bh_cb(void *opaque
)
2306 BlockDriverAIOCBSync
*acb
= opaque
;
2309 qemu_iovec_from_buffer(acb
->qiov
, acb
->bounce
, acb
->qiov
->size
);
2310 qemu_vfree(acb
->bounce
);
2311 acb
->common
.cb(acb
->common
.opaque
, acb
->ret
);
2312 qemu_bh_delete(acb
->bh
);
2314 qemu_aio_release(acb
);
2317 static BlockDriverAIOCB
*bdrv_aio_rw_vector(BlockDriverState
*bs
,
2321 BlockDriverCompletionFunc
*cb
,
2326 BlockDriverAIOCBSync
*acb
;
2328 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2329 acb
->is_write
= is_write
;
2331 acb
->bounce
= qemu_blockalign(bs
, qiov
->size
);
2334 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2337 qemu_iovec_to_buffer(acb
->qiov
, acb
->bounce
);
2338 acb
->ret
= bdrv_write(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2340 acb
->ret
= bdrv_read(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2343 qemu_bh_schedule(acb
->bh
);
2345 return &acb
->common
;
2348 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
2349 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2350 BlockDriverCompletionFunc
*cb
, void *opaque
)
2352 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 0);
2355 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
2356 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2357 BlockDriverCompletionFunc
*cb
, void *opaque
)
2359 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 1);
2362 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
2363 BlockDriverCompletionFunc
*cb
, void *opaque
)
2365 BlockDriverAIOCBSync
*acb
;
2367 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2368 acb
->is_write
= 1; /* don't bounce in the completion hadler */
2374 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2377 qemu_bh_schedule(acb
->bh
);
2378 return &acb
->common
;
2381 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
2382 BlockDriverCompletionFunc
*cb
, void *opaque
)
2384 BlockDriverAIOCBSync
*acb
;
2386 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2387 acb
->is_write
= 1; /* don't bounce in the completion handler */
2393 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2396 qemu_bh_schedule(acb
->bh
);
2397 return &acb
->common
;
2400 /**************************************************************/
2401 /* sync block device emulation */
2403 static void bdrv_rw_em_cb(void *opaque
, int ret
)
2405 *(int *)opaque
= ret
;
2408 #define NOT_DONE 0x7fffffff
2410 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
2411 uint8_t *buf
, int nb_sectors
)
2414 BlockDriverAIOCB
*acb
;
2418 async_context_push();
2420 async_ret
= NOT_DONE
;
2421 iov
.iov_base
= (void *)buf
;
2422 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2423 qemu_iovec_init_external(&qiov
, &iov
, 1);
2424 acb
= bdrv_aio_readv(bs
, sector_num
, &qiov
, nb_sectors
,
2425 bdrv_rw_em_cb
, &async_ret
);
2431 while (async_ret
== NOT_DONE
) {
2437 async_context_pop();
2441 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
2442 const uint8_t *buf
, int nb_sectors
)
2445 BlockDriverAIOCB
*acb
;
2449 async_context_push();
2451 async_ret
= NOT_DONE
;
2452 iov
.iov_base
= (void *)buf
;
2453 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2454 qemu_iovec_init_external(&qiov
, &iov
, 1);
2455 acb
= bdrv_aio_writev(bs
, sector_num
, &qiov
, nb_sectors
,
2456 bdrv_rw_em_cb
, &async_ret
);
2461 while (async_ret
== NOT_DONE
) {
2466 async_context_pop();
2470 void bdrv_init(void)
2472 module_call_init(MODULE_INIT_BLOCK
);
2475 void bdrv_init_with_whitelist(void)
2477 use_bdrv_whitelist
= 1;
2481 void *qemu_aio_get(AIOPool
*pool
, BlockDriverState
*bs
,
2482 BlockDriverCompletionFunc
*cb
, void *opaque
)
2484 BlockDriverAIOCB
*acb
;
2486 if (pool
->free_aiocb
) {
2487 acb
= pool
->free_aiocb
;
2488 pool
->free_aiocb
= acb
->next
;
2490 acb
= qemu_mallocz(pool
->aiocb_size
);
2495 acb
->opaque
= opaque
;
2499 void qemu_aio_release(void *p
)
2501 BlockDriverAIOCB
*acb
= (BlockDriverAIOCB
*)p
;
2502 AIOPool
*pool
= acb
->pool
;
2503 acb
->next
= pool
->free_aiocb
;
2504 pool
->free_aiocb
= acb
;
2507 /**************************************************************/
2508 /* removable device support */
2511 * Return TRUE if the media is present
2513 int bdrv_is_inserted(BlockDriverState
*bs
)
2515 BlockDriver
*drv
= bs
->drv
;
2519 if (!drv
->bdrv_is_inserted
)
2520 return !bs
->tray_open
;
2521 ret
= drv
->bdrv_is_inserted(bs
);
2526 * Return TRUE if the media changed since the last call to this
2527 * function. It is currently only used for floppy disks
2529 int bdrv_media_changed(BlockDriverState
*bs
)
2531 BlockDriver
*drv
= bs
->drv
;
2534 if (!drv
|| !drv
->bdrv_media_changed
)
2537 ret
= drv
->bdrv_media_changed(bs
);
2538 if (ret
== -ENOTSUP
)
2539 ret
= bs
->media_changed
;
2540 bs
->media_changed
= 0;
2545 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2547 int bdrv_eject(BlockDriverState
*bs
, int eject_flag
)
2549 BlockDriver
*drv
= bs
->drv
;
2556 if (!drv
|| !drv
->bdrv_eject
) {
2559 ret
= drv
->bdrv_eject(bs
, eject_flag
);
2561 if (ret
== -ENOTSUP
) {
2565 bs
->tray_open
= eject_flag
;
2571 int bdrv_is_locked(BlockDriverState
*bs
)
2577 * Lock or unlock the media (if it is locked, the user won't be able
2578 * to eject it manually).
2580 void bdrv_set_locked(BlockDriverState
*bs
, int locked
)
2582 BlockDriver
*drv
= bs
->drv
;
2584 bs
->locked
= locked
;
2585 if (drv
&& drv
->bdrv_set_locked
) {
2586 drv
->bdrv_set_locked(bs
, locked
);
2590 /* needed for generic scsi interface */
2592 int bdrv_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
2594 BlockDriver
*drv
= bs
->drv
;
2596 if (drv
&& drv
->bdrv_ioctl
)
2597 return drv
->bdrv_ioctl(bs
, req
, buf
);
2601 BlockDriverAIOCB
*bdrv_aio_ioctl(BlockDriverState
*bs
,
2602 unsigned long int req
, void *buf
,
2603 BlockDriverCompletionFunc
*cb
, void *opaque
)
2605 BlockDriver
*drv
= bs
->drv
;
2607 if (drv
&& drv
->bdrv_aio_ioctl
)
2608 return drv
->bdrv_aio_ioctl(bs
, req
, buf
, cb
, opaque
);
2614 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
2616 return qemu_memalign((bs
&& bs
->buffer_alignment
) ? bs
->buffer_alignment
: 512, size
);
2619 void bdrv_set_dirty_tracking(BlockDriverState
*bs
, int enable
)
2621 int64_t bitmap_size
;
2623 bs
->dirty_count
= 0;
2625 if (!bs
->dirty_bitmap
) {
2626 bitmap_size
= (bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
) +
2627 BDRV_SECTORS_PER_DIRTY_CHUNK
* 8 - 1;
2628 bitmap_size
/= BDRV_SECTORS_PER_DIRTY_CHUNK
* 8;
2630 bs
->dirty_bitmap
= qemu_mallocz(bitmap_size
);
2633 if (bs
->dirty_bitmap
) {
2634 qemu_free(bs
->dirty_bitmap
);
2635 bs
->dirty_bitmap
= NULL
;
2640 int bdrv_get_dirty(BlockDriverState
*bs
, int64_t sector
)
2642 int64_t chunk
= sector
/ (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK
;
2644 if (bs
->dirty_bitmap
&&
2645 (sector
<< BDRV_SECTOR_BITS
) < bdrv_getlength(bs
)) {
2646 return bs
->dirty_bitmap
[chunk
/ (sizeof(unsigned long) * 8)] &
2647 (1 << (chunk
% (sizeof(unsigned long) * 8)));
2653 void bdrv_reset_dirty(BlockDriverState
*bs
, int64_t cur_sector
,
2656 set_dirty_bitmap(bs
, cur_sector
, nr_sectors
, 0);
2659 int64_t bdrv_get_dirty_count(BlockDriverState
*bs
)
2661 return bs
->dirty_count
;