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 BlockDriver
*find_image_format(const char *filename
)
335 int ret
, score
, score_max
;
336 BlockDriver
*drv1
, *drv
;
338 BlockDriverState
*bs
;
340 ret
= bdrv_file_open(&bs
, filename
, 0);
344 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
345 if (bs
->sg
|| !bdrv_is_inserted(bs
)) {
347 return bdrv_find_format("raw");
350 ret
= bdrv_pread(bs
, 0, buf
, sizeof(buf
));
358 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
359 if (drv1
->bdrv_probe
) {
360 score
= drv1
->bdrv_probe(buf
, ret
, filename
);
361 if (score
> score_max
) {
371 * Set the current 'total_sectors' value
373 static int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
375 BlockDriver
*drv
= bs
->drv
;
377 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
381 /* query actual device if possible, otherwise just trust the hint */
382 if (drv
->bdrv_getlength
) {
383 int64_t length
= drv
->bdrv_getlength(bs
);
387 hint
= length
>> BDRV_SECTOR_BITS
;
390 bs
->total_sectors
= hint
;
395 * Common part for opening disk images and files
397 static int bdrv_open_common(BlockDriverState
*bs
, const char *filename
,
398 int flags
, BlockDriver
*drv
)
405 bs
->total_sectors
= 0;
408 bs
->open_flags
= flags
;
409 /* buffer_alignment defaulted to 512, drivers can change this value */
410 bs
->buffer_alignment
= 512;
412 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
414 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
)) {
419 bs
->opaque
= qemu_mallocz(drv
->instance_size
);
422 * Yes, BDRV_O_NOCACHE aka O_DIRECT means we have to present a
423 * write cache to the guest. We do need the fdatasync to flush
424 * out transactions for block allocations, and we maybe have a
425 * volatile write cache in our backing device to deal with.
427 if (flags
& (BDRV_O_CACHE_WB
|BDRV_O_NOCACHE
))
428 bs
->enable_write_cache
= 1;
431 * Clear flags that are internal to the block layer before opening the
434 open_flags
= flags
& ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
437 * Snapshots should be writeable.
439 if (bs
->is_temporary
) {
440 open_flags
|= BDRV_O_RDWR
;
443 /* Open the image, either directly or using a protocol */
444 if (drv
->bdrv_file_open
) {
445 ret
= drv
->bdrv_file_open(bs
, filename
, open_flags
);
447 ret
= bdrv_file_open(&bs
->file
, filename
, open_flags
);
449 ret
= drv
->bdrv_open(bs
, open_flags
);
457 bs
->keep_read_only
= bs
->read_only
= !(open_flags
& BDRV_O_RDWR
);
459 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
465 if (bs
->is_temporary
) {
473 bdrv_delete(bs
->file
);
476 qemu_free(bs
->opaque
);
483 * Opens a file using a protocol (file, host_device, nbd, ...)
485 int bdrv_file_open(BlockDriverState
**pbs
, const char *filename
, int flags
)
487 BlockDriverState
*bs
;
491 drv
= bdrv_find_protocol(filename
);
497 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
508 * Opens a disk image (raw, qcow2, vmdk, ...)
510 int bdrv_open(BlockDriverState
*bs
, const char *filename
, int flags
,
515 if (flags
& BDRV_O_SNAPSHOT
) {
516 BlockDriverState
*bs1
;
519 BlockDriver
*bdrv_qcow2
;
520 QEMUOptionParameter
*options
;
521 char tmp_filename
[PATH_MAX
];
522 char backing_filename
[PATH_MAX
];
524 /* if snapshot, we create a temporary backing file and open it
525 instead of opening 'filename' directly */
527 /* if there is a backing file, use it */
529 ret
= bdrv_open(bs1
, filename
, 0, drv
);
534 total_size
= bdrv_getlength(bs1
) & BDRV_SECTOR_MASK
;
536 if (bs1
->drv
&& bs1
->drv
->protocol_name
)
541 get_tmp_filename(tmp_filename
, sizeof(tmp_filename
));
543 /* Real path is meaningless for protocols */
545 snprintf(backing_filename
, sizeof(backing_filename
),
547 else if (!realpath(filename
, backing_filename
))
550 bdrv_qcow2
= bdrv_find_format("qcow2");
551 options
= parse_option_parameters("", bdrv_qcow2
->create_options
, NULL
);
553 set_option_parameter_int(options
, BLOCK_OPT_SIZE
, total_size
);
554 set_option_parameter(options
, BLOCK_OPT_BACKING_FILE
, backing_filename
);
556 set_option_parameter(options
, BLOCK_OPT_BACKING_FMT
,
560 ret
= bdrv_create(bdrv_qcow2
, tmp_filename
, options
);
561 free_option_parameters(options
);
566 filename
= tmp_filename
;
568 bs
->is_temporary
= 1;
571 /* Find the right image format driver */
573 drv
= find_image_format(filename
);
578 goto unlink_and_fail
;
582 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
584 goto unlink_and_fail
;
587 /* If there is a backing file, use it */
588 if ((flags
& BDRV_O_NO_BACKING
) == 0 && bs
->backing_file
[0] != '\0') {
589 char backing_filename
[PATH_MAX
];
591 BlockDriver
*back_drv
= NULL
;
593 bs
->backing_hd
= bdrv_new("");
594 path_combine(backing_filename
, sizeof(backing_filename
),
595 filename
, bs
->backing_file
);
596 if (bs
->backing_format
[0] != '\0')
597 back_drv
= bdrv_find_format(bs
->backing_format
);
599 /* backing files always opened read-only */
601 flags
& ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
603 ret
= bdrv_open(bs
->backing_hd
, backing_filename
, back_flags
, back_drv
);
608 if (bs
->is_temporary
) {
609 bs
->backing_hd
->keep_read_only
= !(flags
& BDRV_O_RDWR
);
611 /* base image inherits from "parent" */
612 bs
->backing_hd
->keep_read_only
= bs
->keep_read_only
;
616 if (!bdrv_key_required(bs
)) {
617 /* call the change callback */
618 bs
->media_changed
= 1;
620 bs
->change_cb(bs
->change_opaque
);
626 if (bs
->is_temporary
) {
632 void bdrv_close(BlockDriverState
*bs
)
635 if (bs
== bs_snapshots
) {
638 if (bs
->backing_hd
) {
639 bdrv_delete(bs
->backing_hd
);
640 bs
->backing_hd
= NULL
;
642 bs
->drv
->bdrv_close(bs
);
643 qemu_free(bs
->opaque
);
645 if (bs
->is_temporary
) {
646 unlink(bs
->filename
);
652 if (bs
->file
!= NULL
) {
653 bdrv_close(bs
->file
);
656 /* call the change callback */
657 bs
->media_changed
= 1;
659 bs
->change_cb(bs
->change_opaque
);
663 void bdrv_close_all(void)
665 BlockDriverState
*bs
;
667 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
672 void bdrv_delete(BlockDriverState
*bs
)
676 /* remove from list, if necessary */
677 if (bs
->device_name
[0] != '\0') {
678 QTAILQ_REMOVE(&bdrv_states
, bs
, list
);
682 if (bs
->file
!= NULL
) {
683 bdrv_delete(bs
->file
);
686 assert(bs
!= bs_snapshots
);
690 int bdrv_attach(BlockDriverState
*bs
, DeviceState
*qdev
)
699 void bdrv_detach(BlockDriverState
*bs
, DeviceState
*qdev
)
701 assert(bs
->peer
== qdev
);
705 DeviceState
*bdrv_get_attached(BlockDriverState
*bs
)
711 * Run consistency checks on an image
713 * Returns the number of errors or -errno when an internal error occurs
715 int bdrv_check(BlockDriverState
*bs
)
717 if (bs
->drv
->bdrv_check
== NULL
) {
721 return bs
->drv
->bdrv_check(bs
);
724 /* commit COW file into the raw image */
725 int bdrv_commit(BlockDriverState
*bs
)
727 BlockDriver
*drv
= bs
->drv
;
728 int64_t i
, total_sectors
;
729 int n
, j
, ro
, open_flags
;
730 int ret
= 0, rw_ret
= 0;
731 unsigned char sector
[BDRV_SECTOR_SIZE
];
733 BlockDriverState
*bs_rw
, *bs_ro
;
738 if (!bs
->backing_hd
) {
742 if (bs
->backing_hd
->keep_read_only
) {
746 ro
= bs
->backing_hd
->read_only
;
747 strncpy(filename
, bs
->backing_hd
->filename
, sizeof(filename
));
748 open_flags
= bs
->backing_hd
->open_flags
;
752 bdrv_delete(bs
->backing_hd
);
753 bs
->backing_hd
= NULL
;
754 bs_rw
= bdrv_new("");
755 rw_ret
= bdrv_open(bs_rw
, filename
, open_flags
| BDRV_O_RDWR
, drv
);
758 /* try to re-open read-only */
759 bs_ro
= bdrv_new("");
760 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
, drv
);
763 /* drive not functional anymore */
767 bs
->backing_hd
= bs_ro
;
770 bs
->backing_hd
= bs_rw
;
773 total_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
774 for (i
= 0; i
< total_sectors
;) {
775 if (drv
->bdrv_is_allocated(bs
, i
, 65536, &n
)) {
776 for(j
= 0; j
< n
; j
++) {
777 if (bdrv_read(bs
, i
, sector
, 1) != 0) {
782 if (bdrv_write(bs
->backing_hd
, i
, sector
, 1) != 0) {
793 if (drv
->bdrv_make_empty
) {
794 ret
= drv
->bdrv_make_empty(bs
);
799 * Make sure all data we wrote to the backing device is actually
803 bdrv_flush(bs
->backing_hd
);
809 bdrv_delete(bs
->backing_hd
);
810 bs
->backing_hd
= NULL
;
811 bs_ro
= bdrv_new("");
812 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
, drv
);
815 /* drive not functional anymore */
819 bs
->backing_hd
= bs_ro
;
820 bs
->backing_hd
->keep_read_only
= 0;
826 void bdrv_commit_all(void)
828 BlockDriverState
*bs
;
830 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
838 * -EINVAL - backing format specified, but no file
839 * -ENOSPC - can't update the backing file because no space is left in the
841 * -ENOTSUP - format driver doesn't support changing the backing file
843 int bdrv_change_backing_file(BlockDriverState
*bs
,
844 const char *backing_file
, const char *backing_fmt
)
846 BlockDriver
*drv
= bs
->drv
;
848 if (drv
->bdrv_change_backing_file
!= NULL
) {
849 return drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
855 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
860 if (!bdrv_is_inserted(bs
))
866 len
= bdrv_getlength(bs
);
871 if ((offset
> len
) || (len
- offset
< size
))
877 static int bdrv_check_request(BlockDriverState
*bs
, int64_t sector_num
,
880 return bdrv_check_byte_request(bs
, sector_num
* BDRV_SECTOR_SIZE
,
881 nb_sectors
* BDRV_SECTOR_SIZE
);
884 /* return < 0 if error. See bdrv_write() for the return codes */
885 int bdrv_read(BlockDriverState
*bs
, int64_t sector_num
,
886 uint8_t *buf
, int nb_sectors
)
888 BlockDriver
*drv
= bs
->drv
;
892 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
895 return drv
->bdrv_read(bs
, sector_num
, buf
, nb_sectors
);
898 static void set_dirty_bitmap(BlockDriverState
*bs
, int64_t sector_num
,
899 int nb_sectors
, int dirty
)
902 unsigned long val
, idx
, bit
;
904 start
= sector_num
/ BDRV_SECTORS_PER_DIRTY_CHUNK
;
905 end
= (sector_num
+ nb_sectors
- 1) / BDRV_SECTORS_PER_DIRTY_CHUNK
;
907 for (; start
<= end
; start
++) {
908 idx
= start
/ (sizeof(unsigned long) * 8);
909 bit
= start
% (sizeof(unsigned long) * 8);
910 val
= bs
->dirty_bitmap
[idx
];
912 if (!(val
& (1 << bit
))) {
917 if (val
& (1 << bit
)) {
922 bs
->dirty_bitmap
[idx
] = val
;
926 /* Return < 0 if error. Important errors are:
927 -EIO generic I/O error (may happen for all errors)
928 -ENOMEDIUM No media inserted.
929 -EINVAL Invalid sector number or nb_sectors
930 -EACCES Trying to write a read-only device
932 int bdrv_write(BlockDriverState
*bs
, int64_t sector_num
,
933 const uint8_t *buf
, int nb_sectors
)
935 BlockDriver
*drv
= bs
->drv
;
940 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
943 if (bs
->dirty_bitmap
) {
944 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
947 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
948 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
951 return drv
->bdrv_write(bs
, sector_num
, buf
, nb_sectors
);
954 int bdrv_pread(BlockDriverState
*bs
, int64_t offset
,
955 void *buf
, int count1
)
957 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
958 int len
, nb_sectors
, count
;
963 /* first read to align to sector start */
964 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
967 sector_num
= offset
>> BDRV_SECTOR_BITS
;
969 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
971 memcpy(buf
, tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), len
);
979 /* read the sectors "in place" */
980 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
981 if (nb_sectors
> 0) {
982 if ((ret
= bdrv_read(bs
, sector_num
, buf
, nb_sectors
)) < 0)
984 sector_num
+= nb_sectors
;
985 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
990 /* add data from the last sector */
992 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
994 memcpy(buf
, tmp_buf
, count
);
999 int bdrv_pwrite(BlockDriverState
*bs
, int64_t offset
,
1000 const void *buf
, int count1
)
1002 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1003 int len
, nb_sectors
, count
;
1008 /* first write to align to sector start */
1009 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1012 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1014 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1016 memcpy(tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), buf
, len
);
1017 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1026 /* write the sectors "in place" */
1027 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1028 if (nb_sectors
> 0) {
1029 if ((ret
= bdrv_write(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1031 sector_num
+= nb_sectors
;
1032 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1037 /* add data from the last sector */
1039 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1041 memcpy(tmp_buf
, buf
, count
);
1042 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1049 * Writes to the file and ensures that no writes are reordered across this
1050 * request (acts as a barrier)
1052 * Returns 0 on success, -errno in error cases.
1054 int bdrv_pwrite_sync(BlockDriverState
*bs
, int64_t offset
,
1055 const void *buf
, int count
)
1059 ret
= bdrv_pwrite(bs
, offset
, buf
, count
);
1064 /* No flush needed for cache=writethrough, it uses O_DSYNC */
1065 if ((bs
->open_flags
& BDRV_O_CACHE_MASK
) != 0) {
1073 * Writes to the file and ensures that no writes are reordered across this
1074 * request (acts as a barrier)
1076 * Returns 0 on success, -errno in error cases.
1078 int bdrv_write_sync(BlockDriverState
*bs
, int64_t sector_num
,
1079 const uint8_t *buf
, int nb_sectors
)
1081 return bdrv_pwrite_sync(bs
, BDRV_SECTOR_SIZE
* sector_num
,
1082 buf
, BDRV_SECTOR_SIZE
* nb_sectors
);
1086 * Truncate file to 'offset' bytes (needed only for file protocols)
1088 int bdrv_truncate(BlockDriverState
*bs
, int64_t offset
)
1090 BlockDriver
*drv
= bs
->drv
;
1094 if (!drv
->bdrv_truncate
)
1098 ret
= drv
->bdrv_truncate(bs
, offset
);
1100 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
1106 * Length of a file in bytes. Return < 0 if error or unknown.
1108 int64_t bdrv_getlength(BlockDriverState
*bs
)
1110 BlockDriver
*drv
= bs
->drv
;
1114 /* Fixed size devices use the total_sectors value for speed instead of
1115 issuing a length query (like lseek) on each call. Also, legacy block
1116 drivers don't provide a bdrv_getlength function and must use
1118 if (!bs
->growable
|| !drv
->bdrv_getlength
) {
1119 return bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1121 return drv
->bdrv_getlength(bs
);
1124 /* return 0 as number of sectors if no device present or error */
1125 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
1128 length
= bdrv_getlength(bs
);
1132 length
= length
>> BDRV_SECTOR_BITS
;
1133 *nb_sectors_ptr
= length
;
1137 uint8_t boot_ind
; /* 0x80 - active */
1138 uint8_t head
; /* starting head */
1139 uint8_t sector
; /* starting sector */
1140 uint8_t cyl
; /* starting cylinder */
1141 uint8_t sys_ind
; /* What partition type */
1142 uint8_t end_head
; /* end head */
1143 uint8_t end_sector
; /* end sector */
1144 uint8_t end_cyl
; /* end cylinder */
1145 uint32_t start_sect
; /* starting sector counting from 0 */
1146 uint32_t nr_sects
; /* nr of sectors in partition */
1147 } __attribute__((packed
));
1149 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1150 static int guess_disk_lchs(BlockDriverState
*bs
,
1151 int *pcylinders
, int *pheads
, int *psectors
)
1153 uint8_t buf
[BDRV_SECTOR_SIZE
];
1154 int ret
, i
, heads
, sectors
, cylinders
;
1155 struct partition
*p
;
1157 uint64_t nb_sectors
;
1159 bdrv_get_geometry(bs
, &nb_sectors
);
1161 ret
= bdrv_read(bs
, 0, buf
, 1);
1164 /* test msdos magic */
1165 if (buf
[510] != 0x55 || buf
[511] != 0xaa)
1167 for(i
= 0; i
< 4; i
++) {
1168 p
= ((struct partition
*)(buf
+ 0x1be)) + i
;
1169 nr_sects
= le32_to_cpu(p
->nr_sects
);
1170 if (nr_sects
&& p
->end_head
) {
1171 /* We make the assumption that the partition terminates on
1172 a cylinder boundary */
1173 heads
= p
->end_head
+ 1;
1174 sectors
= p
->end_sector
& 63;
1177 cylinders
= nb_sectors
/ (heads
* sectors
);
1178 if (cylinders
< 1 || cylinders
> 16383)
1181 *psectors
= sectors
;
1182 *pcylinders
= cylinders
;
1184 printf("guessed geometry: LCHS=%d %d %d\n",
1185 cylinders
, heads
, sectors
);
1193 void bdrv_guess_geometry(BlockDriverState
*bs
, int *pcyls
, int *pheads
, int *psecs
)
1195 int translation
, lba_detected
= 0;
1196 int cylinders
, heads
, secs
;
1197 uint64_t nb_sectors
;
1199 /* if a geometry hint is available, use it */
1200 bdrv_get_geometry(bs
, &nb_sectors
);
1201 bdrv_get_geometry_hint(bs
, &cylinders
, &heads
, &secs
);
1202 translation
= bdrv_get_translation_hint(bs
);
1203 if (cylinders
!= 0) {
1208 if (guess_disk_lchs(bs
, &cylinders
, &heads
, &secs
) == 0) {
1210 /* if heads > 16, it means that a BIOS LBA
1211 translation was active, so the default
1212 hardware geometry is OK */
1214 goto default_geometry
;
1219 /* disable any translation to be in sync with
1220 the logical geometry */
1221 if (translation
== BIOS_ATA_TRANSLATION_AUTO
) {
1222 bdrv_set_translation_hint(bs
,
1223 BIOS_ATA_TRANSLATION_NONE
);
1228 /* if no geometry, use a standard physical disk geometry */
1229 cylinders
= nb_sectors
/ (16 * 63);
1231 if (cylinders
> 16383)
1233 else if (cylinders
< 2)
1238 if ((lba_detected
== 1) && (translation
== BIOS_ATA_TRANSLATION_AUTO
)) {
1239 if ((*pcyls
* *pheads
) <= 131072) {
1240 bdrv_set_translation_hint(bs
,
1241 BIOS_ATA_TRANSLATION_LARGE
);
1243 bdrv_set_translation_hint(bs
,
1244 BIOS_ATA_TRANSLATION_LBA
);
1248 bdrv_set_geometry_hint(bs
, *pcyls
, *pheads
, *psecs
);
1252 void bdrv_set_geometry_hint(BlockDriverState
*bs
,
1253 int cyls
, int heads
, int secs
)
1260 void bdrv_set_type_hint(BlockDriverState
*bs
, int type
)
1263 bs
->removable
= ((type
== BDRV_TYPE_CDROM
||
1264 type
== BDRV_TYPE_FLOPPY
));
1267 void bdrv_set_translation_hint(BlockDriverState
*bs
, int translation
)
1269 bs
->translation
= translation
;
1272 void bdrv_get_geometry_hint(BlockDriverState
*bs
,
1273 int *pcyls
, int *pheads
, int *psecs
)
1276 *pheads
= bs
->heads
;
1280 int bdrv_get_type_hint(BlockDriverState
*bs
)
1285 int bdrv_get_translation_hint(BlockDriverState
*bs
)
1287 return bs
->translation
;
1290 void bdrv_set_on_error(BlockDriverState
*bs
, BlockErrorAction on_read_error
,
1291 BlockErrorAction on_write_error
)
1293 bs
->on_read_error
= on_read_error
;
1294 bs
->on_write_error
= on_write_error
;
1297 BlockErrorAction
bdrv_get_on_error(BlockDriverState
*bs
, int is_read
)
1299 return is_read
? bs
->on_read_error
: bs
->on_write_error
;
1302 int bdrv_is_removable(BlockDriverState
*bs
)
1304 return bs
->removable
;
1307 int bdrv_is_read_only(BlockDriverState
*bs
)
1309 return bs
->read_only
;
1312 int bdrv_is_sg(BlockDriverState
*bs
)
1317 int bdrv_enable_write_cache(BlockDriverState
*bs
)
1319 return bs
->enable_write_cache
;
1322 /* XXX: no longer used */
1323 void bdrv_set_change_cb(BlockDriverState
*bs
,
1324 void (*change_cb
)(void *opaque
), void *opaque
)
1326 bs
->change_cb
= change_cb
;
1327 bs
->change_opaque
= opaque
;
1330 int bdrv_is_encrypted(BlockDriverState
*bs
)
1332 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1334 return bs
->encrypted
;
1337 int bdrv_key_required(BlockDriverState
*bs
)
1339 BlockDriverState
*backing_hd
= bs
->backing_hd
;
1341 if (backing_hd
&& backing_hd
->encrypted
&& !backing_hd
->valid_key
)
1343 return (bs
->encrypted
&& !bs
->valid_key
);
1346 int bdrv_set_key(BlockDriverState
*bs
, const char *key
)
1349 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
) {
1350 ret
= bdrv_set_key(bs
->backing_hd
, key
);
1356 if (!bs
->encrypted
) {
1358 } else if (!bs
->drv
|| !bs
->drv
->bdrv_set_key
) {
1361 ret
= bs
->drv
->bdrv_set_key(bs
, key
);
1364 } else if (!bs
->valid_key
) {
1366 /* call the change callback now, we skipped it on open */
1367 bs
->media_changed
= 1;
1369 bs
->change_cb(bs
->change_opaque
);
1374 void bdrv_get_format(BlockDriverState
*bs
, char *buf
, int buf_size
)
1379 pstrcpy(buf
, buf_size
, bs
->drv
->format_name
);
1383 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
1388 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
1389 it(opaque
, drv
->format_name
);
1393 BlockDriverState
*bdrv_find(const char *name
)
1395 BlockDriverState
*bs
;
1397 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1398 if (!strcmp(name
, bs
->device_name
)) {
1405 BlockDriverState
*bdrv_next(BlockDriverState
*bs
)
1408 return QTAILQ_FIRST(&bdrv_states
);
1410 return QTAILQ_NEXT(bs
, list
);
1413 void bdrv_iterate(void (*it
)(void *opaque
, BlockDriverState
*bs
), void *opaque
)
1415 BlockDriverState
*bs
;
1417 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1422 const char *bdrv_get_device_name(BlockDriverState
*bs
)
1424 return bs
->device_name
;
1427 void bdrv_flush(BlockDriverState
*bs
)
1429 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
1433 if (bs
->drv
&& bs
->drv
->bdrv_flush
)
1434 bs
->drv
->bdrv_flush(bs
);
1437 void bdrv_flush_all(void)
1439 BlockDriverState
*bs
;
1441 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1442 if (bs
->drv
&& !bdrv_is_read_only(bs
) &&
1443 (!bdrv_is_removable(bs
) || bdrv_is_inserted(bs
))) {
1449 int bdrv_has_zero_init(BlockDriverState
*bs
)
1453 if (bs
->drv
->no_zero_init
) {
1455 } else if (bs
->file
) {
1456 return bdrv_has_zero_init(bs
->file
);
1463 * Returns true iff the specified sector is present in the disk image. Drivers
1464 * not implementing the functionality are assumed to not support backing files,
1465 * hence all their sectors are reported as allocated.
1467 * 'pnum' is set to the number of sectors (including and immediately following
1468 * the specified sector) that are known to be in the same
1469 * allocated/unallocated state.
1471 * 'nb_sectors' is the max value 'pnum' should be set to.
1473 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
,
1477 if (!bs
->drv
->bdrv_is_allocated
) {
1478 if (sector_num
>= bs
->total_sectors
) {
1482 n
= bs
->total_sectors
- sector_num
;
1483 *pnum
= (n
< nb_sectors
) ? (n
) : (nb_sectors
);
1486 return bs
->drv
->bdrv_is_allocated(bs
, sector_num
, nb_sectors
, pnum
);
1489 void bdrv_mon_event(const BlockDriverState
*bdrv
,
1490 BlockMonEventAction action
, int is_read
)
1493 const char *action_str
;
1496 case BDRV_ACTION_REPORT
:
1497 action_str
= "report";
1499 case BDRV_ACTION_IGNORE
:
1500 action_str
= "ignore";
1502 case BDRV_ACTION_STOP
:
1503 action_str
= "stop";
1509 data
= qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1512 is_read
? "read" : "write");
1513 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR
, data
);
1515 qobject_decref(data
);
1518 static void bdrv_print_dict(QObject
*obj
, void *opaque
)
1521 Monitor
*mon
= opaque
;
1523 bs_dict
= qobject_to_qdict(obj
);
1525 monitor_printf(mon
, "%s: type=%s removable=%d",
1526 qdict_get_str(bs_dict
, "device"),
1527 qdict_get_str(bs_dict
, "type"),
1528 qdict_get_bool(bs_dict
, "removable"));
1530 if (qdict_get_bool(bs_dict
, "removable")) {
1531 monitor_printf(mon
, " locked=%d", qdict_get_bool(bs_dict
, "locked"));
1534 if (qdict_haskey(bs_dict
, "inserted")) {
1535 QDict
*qdict
= qobject_to_qdict(qdict_get(bs_dict
, "inserted"));
1537 monitor_printf(mon
, " file=");
1538 monitor_print_filename(mon
, qdict_get_str(qdict
, "file"));
1539 if (qdict_haskey(qdict
, "backing_file")) {
1540 monitor_printf(mon
, " backing_file=");
1541 monitor_print_filename(mon
, qdict_get_str(qdict
, "backing_file"));
1543 monitor_printf(mon
, " ro=%d drv=%s encrypted=%d",
1544 qdict_get_bool(qdict
, "ro"),
1545 qdict_get_str(qdict
, "drv"),
1546 qdict_get_bool(qdict
, "encrypted"));
1548 monitor_printf(mon
, " [not inserted]");
1551 monitor_printf(mon
, "\n");
1554 void bdrv_info_print(Monitor
*mon
, const QObject
*data
)
1556 qlist_iter(qobject_to_qlist(data
), bdrv_print_dict
, mon
);
1559 void bdrv_info(Monitor
*mon
, QObject
**ret_data
)
1562 BlockDriverState
*bs
;
1564 bs_list
= qlist_new();
1566 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1568 const char *type
= "unknown";
1574 case BDRV_TYPE_CDROM
:
1577 case BDRV_TYPE_FLOPPY
:
1582 bs_obj
= qobject_from_jsonf("{ 'device': %s, 'type': %s, "
1583 "'removable': %i, 'locked': %i }",
1584 bs
->device_name
, type
, bs
->removable
,
1589 QDict
*bs_dict
= qobject_to_qdict(bs_obj
);
1591 obj
= qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1592 "'encrypted': %i }",
1593 bs
->filename
, bs
->read_only
,
1594 bs
->drv
->format_name
,
1595 bdrv_is_encrypted(bs
));
1596 if (bs
->backing_file
[0] != '\0') {
1597 QDict
*qdict
= qobject_to_qdict(obj
);
1598 qdict_put(qdict
, "backing_file",
1599 qstring_from_str(bs
->backing_file
));
1602 qdict_put_obj(bs_dict
, "inserted", obj
);
1604 qlist_append_obj(bs_list
, bs_obj
);
1607 *ret_data
= QOBJECT(bs_list
);
1610 static void bdrv_stats_iter(QObject
*data
, void *opaque
)
1613 Monitor
*mon
= opaque
;
1615 qdict
= qobject_to_qdict(data
);
1616 monitor_printf(mon
, "%s:", qdict_get_str(qdict
, "device"));
1618 qdict
= qobject_to_qdict(qdict_get(qdict
, "stats"));
1619 monitor_printf(mon
, " rd_bytes=%" PRId64
1620 " wr_bytes=%" PRId64
1621 " rd_operations=%" PRId64
1622 " wr_operations=%" PRId64
1624 qdict_get_int(qdict
, "rd_bytes"),
1625 qdict_get_int(qdict
, "wr_bytes"),
1626 qdict_get_int(qdict
, "rd_operations"),
1627 qdict_get_int(qdict
, "wr_operations"));
1630 void bdrv_stats_print(Monitor
*mon
, const QObject
*data
)
1632 qlist_iter(qobject_to_qlist(data
), bdrv_stats_iter
, mon
);
1635 static QObject
* bdrv_info_stats_bs(BlockDriverState
*bs
)
1640 res
= qobject_from_jsonf("{ 'stats': {"
1641 "'rd_bytes': %" PRId64
","
1642 "'wr_bytes': %" PRId64
","
1643 "'rd_operations': %" PRId64
","
1644 "'wr_operations': %" PRId64
","
1645 "'wr_highest_offset': %" PRId64
1647 bs
->rd_bytes
, bs
->wr_bytes
,
1648 bs
->rd_ops
, bs
->wr_ops
,
1649 bs
->wr_highest_sector
*
1650 (uint64_t)BDRV_SECTOR_SIZE
);
1651 dict
= qobject_to_qdict(res
);
1653 if (*bs
->device_name
) {
1654 qdict_put(dict
, "device", qstring_from_str(bs
->device_name
));
1658 QObject
*parent
= bdrv_info_stats_bs(bs
->file
);
1659 qdict_put_obj(dict
, "parent", parent
);
1665 void bdrv_info_stats(Monitor
*mon
, QObject
**ret_data
)
1669 BlockDriverState
*bs
;
1671 devices
= qlist_new();
1673 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1674 obj
= bdrv_info_stats_bs(bs
);
1675 qlist_append_obj(devices
, obj
);
1678 *ret_data
= QOBJECT(devices
);
1681 const char *bdrv_get_encrypted_filename(BlockDriverState
*bs
)
1683 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1684 return bs
->backing_file
;
1685 else if (bs
->encrypted
)
1686 return bs
->filename
;
1691 void bdrv_get_backing_filename(BlockDriverState
*bs
,
1692 char *filename
, int filename_size
)
1694 if (!bs
->backing_file
) {
1695 pstrcpy(filename
, filename_size
, "");
1697 pstrcpy(filename
, filename_size
, bs
->backing_file
);
1701 int bdrv_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
1702 const uint8_t *buf
, int nb_sectors
)
1704 BlockDriver
*drv
= bs
->drv
;
1707 if (!drv
->bdrv_write_compressed
)
1709 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1712 if (bs
->dirty_bitmap
) {
1713 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1716 return drv
->bdrv_write_compressed(bs
, sector_num
, buf
, nb_sectors
);
1719 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1721 BlockDriver
*drv
= bs
->drv
;
1724 if (!drv
->bdrv_get_info
)
1726 memset(bdi
, 0, sizeof(*bdi
));
1727 return drv
->bdrv_get_info(bs
, bdi
);
1730 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
1731 int64_t pos
, int size
)
1733 BlockDriver
*drv
= bs
->drv
;
1736 if (drv
->bdrv_save_vmstate
)
1737 return drv
->bdrv_save_vmstate(bs
, buf
, pos
, size
);
1739 return bdrv_save_vmstate(bs
->file
, buf
, pos
, size
);
1743 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
1744 int64_t pos
, int size
)
1746 BlockDriver
*drv
= bs
->drv
;
1749 if (drv
->bdrv_load_vmstate
)
1750 return drv
->bdrv_load_vmstate(bs
, buf
, pos
, size
);
1752 return bdrv_load_vmstate(bs
->file
, buf
, pos
, size
);
1756 void bdrv_debug_event(BlockDriverState
*bs
, BlkDebugEvent event
)
1758 BlockDriver
*drv
= bs
->drv
;
1760 if (!drv
|| !drv
->bdrv_debug_event
) {
1764 return drv
->bdrv_debug_event(bs
, event
);
1768 /**************************************************************/
1769 /* handling of snapshots */
1771 int bdrv_can_snapshot(BlockDriverState
*bs
)
1773 BlockDriver
*drv
= bs
->drv
;
1774 if (!drv
|| bdrv_is_removable(bs
) || bdrv_is_read_only(bs
)) {
1778 if (!drv
->bdrv_snapshot_create
) {
1779 if (bs
->file
!= NULL
) {
1780 return bdrv_can_snapshot(bs
->file
);
1788 BlockDriverState
*bdrv_snapshots(void)
1790 BlockDriverState
*bs
;
1793 return bs_snapshots
;
1796 while ((bs
= bdrv_next(bs
))) {
1797 if (bdrv_can_snapshot(bs
)) {
1807 int bdrv_snapshot_create(BlockDriverState
*bs
,
1808 QEMUSnapshotInfo
*sn_info
)
1810 BlockDriver
*drv
= bs
->drv
;
1813 if (drv
->bdrv_snapshot_create
)
1814 return drv
->bdrv_snapshot_create(bs
, sn_info
);
1816 return bdrv_snapshot_create(bs
->file
, sn_info
);
1820 int bdrv_snapshot_goto(BlockDriverState
*bs
,
1821 const char *snapshot_id
)
1823 BlockDriver
*drv
= bs
->drv
;
1828 if (drv
->bdrv_snapshot_goto
)
1829 return drv
->bdrv_snapshot_goto(bs
, snapshot_id
);
1832 drv
->bdrv_close(bs
);
1833 ret
= bdrv_snapshot_goto(bs
->file
, snapshot_id
);
1834 open_ret
= drv
->bdrv_open(bs
, bs
->open_flags
);
1836 bdrv_delete(bs
->file
);
1846 int bdrv_snapshot_delete(BlockDriverState
*bs
, const char *snapshot_id
)
1848 BlockDriver
*drv
= bs
->drv
;
1851 if (drv
->bdrv_snapshot_delete
)
1852 return drv
->bdrv_snapshot_delete(bs
, snapshot_id
);
1854 return bdrv_snapshot_delete(bs
->file
, snapshot_id
);
1858 int bdrv_snapshot_list(BlockDriverState
*bs
,
1859 QEMUSnapshotInfo
**psn_info
)
1861 BlockDriver
*drv
= bs
->drv
;
1864 if (drv
->bdrv_snapshot_list
)
1865 return drv
->bdrv_snapshot_list(bs
, psn_info
);
1867 return bdrv_snapshot_list(bs
->file
, psn_info
);
1871 #define NB_SUFFIXES 4
1873 char *get_human_readable_size(char *buf
, int buf_size
, int64_t size
)
1875 static const char suffixes
[NB_SUFFIXES
] = "KMGT";
1880 snprintf(buf
, buf_size
, "%" PRId64
, size
);
1883 for(i
= 0; i
< NB_SUFFIXES
; i
++) {
1884 if (size
< (10 * base
)) {
1885 snprintf(buf
, buf_size
, "%0.1f%c",
1886 (double)size
/ base
,
1889 } else if (size
< (1000 * base
) || i
== (NB_SUFFIXES
- 1)) {
1890 snprintf(buf
, buf_size
, "%" PRId64
"%c",
1891 ((size
+ (base
>> 1)) / base
),
1901 char *bdrv_snapshot_dump(char *buf
, int buf_size
, QEMUSnapshotInfo
*sn
)
1903 char buf1
[128], date_buf
[128], clock_buf
[128];
1913 snprintf(buf
, buf_size
,
1914 "%-10s%-20s%7s%20s%15s",
1915 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
1919 ptm
= localtime(&ti
);
1920 strftime(date_buf
, sizeof(date_buf
),
1921 "%Y-%m-%d %H:%M:%S", ptm
);
1923 localtime_r(&ti
, &tm
);
1924 strftime(date_buf
, sizeof(date_buf
),
1925 "%Y-%m-%d %H:%M:%S", &tm
);
1927 secs
= sn
->vm_clock_nsec
/ 1000000000;
1928 snprintf(clock_buf
, sizeof(clock_buf
),
1929 "%02d:%02d:%02d.%03d",
1931 (int)((secs
/ 60) % 60),
1933 (int)((sn
->vm_clock_nsec
/ 1000000) % 1000));
1934 snprintf(buf
, buf_size
,
1935 "%-10s%-20s%7s%20s%15s",
1936 sn
->id_str
, sn
->name
,
1937 get_human_readable_size(buf1
, sizeof(buf1
), sn
->vm_state_size
),
1945 /**************************************************************/
1948 BlockDriverAIOCB
*bdrv_aio_readv(BlockDriverState
*bs
, int64_t sector_num
,
1949 QEMUIOVector
*qiov
, int nb_sectors
,
1950 BlockDriverCompletionFunc
*cb
, void *opaque
)
1952 BlockDriver
*drv
= bs
->drv
;
1953 BlockDriverAIOCB
*ret
;
1957 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1960 ret
= drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
1964 /* Update stats even though technically transfer has not happened. */
1965 bs
->rd_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
1972 BlockDriverAIOCB
*bdrv_aio_writev(BlockDriverState
*bs
, int64_t sector_num
,
1973 QEMUIOVector
*qiov
, int nb_sectors
,
1974 BlockDriverCompletionFunc
*cb
, void *opaque
)
1976 BlockDriver
*drv
= bs
->drv
;
1977 BlockDriverAIOCB
*ret
;
1983 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1986 if (bs
->dirty_bitmap
) {
1987 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1990 ret
= drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
1994 /* Update stats even though technically transfer has not happened. */
1995 bs
->wr_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
1997 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1998 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
2006 typedef struct MultiwriteCB
{
2011 BlockDriverCompletionFunc
*cb
;
2013 QEMUIOVector
*free_qiov
;
2018 static void multiwrite_user_cb(MultiwriteCB
*mcb
)
2022 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2023 mcb
->callbacks
[i
].cb(mcb
->callbacks
[i
].opaque
, mcb
->error
);
2024 if (mcb
->callbacks
[i
].free_qiov
) {
2025 qemu_iovec_destroy(mcb
->callbacks
[i
].free_qiov
);
2027 qemu_free(mcb
->callbacks
[i
].free_qiov
);
2028 qemu_vfree(mcb
->callbacks
[i
].free_buf
);
2032 static void multiwrite_cb(void *opaque
, int ret
)
2034 MultiwriteCB
*mcb
= opaque
;
2036 if (ret
< 0 && !mcb
->error
) {
2038 multiwrite_user_cb(mcb
);
2041 mcb
->num_requests
--;
2042 if (mcb
->num_requests
== 0) {
2043 if (mcb
->error
== 0) {
2044 multiwrite_user_cb(mcb
);
2050 static int multiwrite_req_compare(const void *a
, const void *b
)
2052 const BlockRequest
*req1
= a
, *req2
= b
;
2055 * Note that we can't simply subtract req2->sector from req1->sector
2056 * here as that could overflow the return value.
2058 if (req1
->sector
> req2
->sector
) {
2060 } else if (req1
->sector
< req2
->sector
) {
2068 * Takes a bunch of requests and tries to merge them. Returns the number of
2069 * requests that remain after merging.
2071 static int multiwrite_merge(BlockDriverState
*bs
, BlockRequest
*reqs
,
2072 int num_reqs
, MultiwriteCB
*mcb
)
2076 // Sort requests by start sector
2077 qsort(reqs
, num_reqs
, sizeof(*reqs
), &multiwrite_req_compare
);
2079 // Check if adjacent requests touch the same clusters. If so, combine them,
2080 // filling up gaps with zero sectors.
2082 for (i
= 1; i
< num_reqs
; i
++) {
2084 int64_t oldreq_last
= reqs
[outidx
].sector
+ reqs
[outidx
].nb_sectors
;
2086 // This handles the cases that are valid for all block drivers, namely
2087 // exactly sequential writes and overlapping writes.
2088 if (reqs
[i
].sector
<= oldreq_last
) {
2092 // The block driver may decide that it makes sense to combine requests
2093 // even if there is a gap of some sectors between them. In this case,
2094 // the gap is filled with zeros (therefore only applicable for yet
2095 // unused space in format like qcow2).
2096 if (!merge
&& bs
->drv
->bdrv_merge_requests
) {
2097 merge
= bs
->drv
->bdrv_merge_requests(bs
, &reqs
[outidx
], &reqs
[i
]);
2100 if (reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1 > IOV_MAX
) {
2106 QEMUIOVector
*qiov
= qemu_mallocz(sizeof(*qiov
));
2107 qemu_iovec_init(qiov
,
2108 reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1);
2110 // Add the first request to the merged one. If the requests are
2111 // overlapping, drop the last sectors of the first request.
2112 size
= (reqs
[i
].sector
- reqs
[outidx
].sector
) << 9;
2113 qemu_iovec_concat(qiov
, reqs
[outidx
].qiov
, size
);
2115 // We might need to add some zeros between the two requests
2116 if (reqs
[i
].sector
> oldreq_last
) {
2117 size_t zero_bytes
= (reqs
[i
].sector
- oldreq_last
) << 9;
2118 uint8_t *buf
= qemu_blockalign(bs
, zero_bytes
);
2119 memset(buf
, 0, zero_bytes
);
2120 qemu_iovec_add(qiov
, buf
, zero_bytes
);
2121 mcb
->callbacks
[i
].free_buf
= buf
;
2124 // Add the second request
2125 qemu_iovec_concat(qiov
, reqs
[i
].qiov
, reqs
[i
].qiov
->size
);
2127 reqs
[outidx
].nb_sectors
= qiov
->size
>> 9;
2128 reqs
[outidx
].qiov
= qiov
;
2130 mcb
->callbacks
[i
].free_qiov
= reqs
[outidx
].qiov
;
2133 reqs
[outidx
].sector
= reqs
[i
].sector
;
2134 reqs
[outidx
].nb_sectors
= reqs
[i
].nb_sectors
;
2135 reqs
[outidx
].qiov
= reqs
[i
].qiov
;
2143 * Submit multiple AIO write requests at once.
2145 * On success, the function returns 0 and all requests in the reqs array have
2146 * been submitted. In error case this function returns -1, and any of the
2147 * requests may or may not be submitted yet. In particular, this means that the
2148 * callback will be called for some of the requests, for others it won't. The
2149 * caller must check the error field of the BlockRequest to wait for the right
2150 * callbacks (if error != 0, no callback will be called).
2152 * The implementation may modify the contents of the reqs array, e.g. to merge
2153 * requests. However, the fields opaque and error are left unmodified as they
2154 * are used to signal failure for a single request to the caller.
2156 int bdrv_aio_multiwrite(BlockDriverState
*bs
, BlockRequest
*reqs
, int num_reqs
)
2158 BlockDriverAIOCB
*acb
;
2162 if (num_reqs
== 0) {
2166 // Create MultiwriteCB structure
2167 mcb
= qemu_mallocz(sizeof(*mcb
) + num_reqs
* sizeof(*mcb
->callbacks
));
2168 mcb
->num_requests
= 0;
2169 mcb
->num_callbacks
= num_reqs
;
2171 for (i
= 0; i
< num_reqs
; i
++) {
2172 mcb
->callbacks
[i
].cb
= reqs
[i
].cb
;
2173 mcb
->callbacks
[i
].opaque
= reqs
[i
].opaque
;
2176 // Check for mergable requests
2177 num_reqs
= multiwrite_merge(bs
, reqs
, num_reqs
, mcb
);
2179 // Run the aio requests
2180 for (i
= 0; i
< num_reqs
; i
++) {
2181 acb
= bdrv_aio_writev(bs
, reqs
[i
].sector
, reqs
[i
].qiov
,
2182 reqs
[i
].nb_sectors
, multiwrite_cb
, mcb
);
2185 // We can only fail the whole thing if no request has been
2186 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2187 // complete and report the error in the callback.
2188 if (mcb
->num_requests
== 0) {
2189 reqs
[i
].error
= -EIO
;
2192 mcb
->num_requests
++;
2193 multiwrite_cb(mcb
, -EIO
);
2197 mcb
->num_requests
++;
2208 BlockDriverAIOCB
*bdrv_aio_flush(BlockDriverState
*bs
,
2209 BlockDriverCompletionFunc
*cb
, void *opaque
)
2211 BlockDriver
*drv
= bs
->drv
;
2213 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2214 return bdrv_aio_noop_em(bs
, cb
, opaque
);
2219 return drv
->bdrv_aio_flush(bs
, cb
, opaque
);
2222 void bdrv_aio_cancel(BlockDriverAIOCB
*acb
)
2224 acb
->pool
->cancel(acb
);
2228 /**************************************************************/
2229 /* async block device emulation */
2231 typedef struct BlockDriverAIOCBSync
{
2232 BlockDriverAIOCB common
;
2235 /* vector translation state */
2239 } BlockDriverAIOCBSync
;
2241 static void bdrv_aio_cancel_em(BlockDriverAIOCB
*blockacb
)
2243 BlockDriverAIOCBSync
*acb
=
2244 container_of(blockacb
, BlockDriverAIOCBSync
, common
);
2245 qemu_bh_delete(acb
->bh
);
2247 qemu_aio_release(acb
);
2250 static AIOPool bdrv_em_aio_pool
= {
2251 .aiocb_size
= sizeof(BlockDriverAIOCBSync
),
2252 .cancel
= bdrv_aio_cancel_em
,
2255 static void bdrv_aio_bh_cb(void *opaque
)
2257 BlockDriverAIOCBSync
*acb
= opaque
;
2260 qemu_iovec_from_buffer(acb
->qiov
, acb
->bounce
, acb
->qiov
->size
);
2261 qemu_vfree(acb
->bounce
);
2262 acb
->common
.cb(acb
->common
.opaque
, acb
->ret
);
2263 qemu_bh_delete(acb
->bh
);
2265 qemu_aio_release(acb
);
2268 static BlockDriverAIOCB
*bdrv_aio_rw_vector(BlockDriverState
*bs
,
2272 BlockDriverCompletionFunc
*cb
,
2277 BlockDriverAIOCBSync
*acb
;
2279 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2280 acb
->is_write
= is_write
;
2282 acb
->bounce
= qemu_blockalign(bs
, qiov
->size
);
2285 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2288 qemu_iovec_to_buffer(acb
->qiov
, acb
->bounce
);
2289 acb
->ret
= bdrv_write(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2291 acb
->ret
= bdrv_read(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2294 qemu_bh_schedule(acb
->bh
);
2296 return &acb
->common
;
2299 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
2300 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2301 BlockDriverCompletionFunc
*cb
, void *opaque
)
2303 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 0);
2306 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
2307 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2308 BlockDriverCompletionFunc
*cb
, void *opaque
)
2310 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 1);
2313 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
2314 BlockDriverCompletionFunc
*cb
, void *opaque
)
2316 BlockDriverAIOCBSync
*acb
;
2318 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2319 acb
->is_write
= 1; /* don't bounce in the completion hadler */
2325 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2328 qemu_bh_schedule(acb
->bh
);
2329 return &acb
->common
;
2332 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
2333 BlockDriverCompletionFunc
*cb
, void *opaque
)
2335 BlockDriverAIOCBSync
*acb
;
2337 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2338 acb
->is_write
= 1; /* don't bounce in the completion handler */
2344 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2347 qemu_bh_schedule(acb
->bh
);
2348 return &acb
->common
;
2351 /**************************************************************/
2352 /* sync block device emulation */
2354 static void bdrv_rw_em_cb(void *opaque
, int ret
)
2356 *(int *)opaque
= ret
;
2359 #define NOT_DONE 0x7fffffff
2361 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
2362 uint8_t *buf
, int nb_sectors
)
2365 BlockDriverAIOCB
*acb
;
2369 async_context_push();
2371 async_ret
= NOT_DONE
;
2372 iov
.iov_base
= (void *)buf
;
2373 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2374 qemu_iovec_init_external(&qiov
, &iov
, 1);
2375 acb
= bdrv_aio_readv(bs
, sector_num
, &qiov
, nb_sectors
,
2376 bdrv_rw_em_cb
, &async_ret
);
2382 while (async_ret
== NOT_DONE
) {
2388 async_context_pop();
2392 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
2393 const uint8_t *buf
, int nb_sectors
)
2396 BlockDriverAIOCB
*acb
;
2400 async_context_push();
2402 async_ret
= NOT_DONE
;
2403 iov
.iov_base
= (void *)buf
;
2404 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2405 qemu_iovec_init_external(&qiov
, &iov
, 1);
2406 acb
= bdrv_aio_writev(bs
, sector_num
, &qiov
, nb_sectors
,
2407 bdrv_rw_em_cb
, &async_ret
);
2412 while (async_ret
== NOT_DONE
) {
2417 async_context_pop();
2421 void bdrv_init(void)
2423 module_call_init(MODULE_INIT_BLOCK
);
2426 void bdrv_init_with_whitelist(void)
2428 use_bdrv_whitelist
= 1;
2432 void *qemu_aio_get(AIOPool
*pool
, BlockDriverState
*bs
,
2433 BlockDriverCompletionFunc
*cb
, void *opaque
)
2435 BlockDriverAIOCB
*acb
;
2437 if (pool
->free_aiocb
) {
2438 acb
= pool
->free_aiocb
;
2439 pool
->free_aiocb
= acb
->next
;
2441 acb
= qemu_mallocz(pool
->aiocb_size
);
2446 acb
->opaque
= opaque
;
2450 void qemu_aio_release(void *p
)
2452 BlockDriverAIOCB
*acb
= (BlockDriverAIOCB
*)p
;
2453 AIOPool
*pool
= acb
->pool
;
2454 acb
->next
= pool
->free_aiocb
;
2455 pool
->free_aiocb
= acb
;
2458 /**************************************************************/
2459 /* removable device support */
2462 * Return TRUE if the media is present
2464 int bdrv_is_inserted(BlockDriverState
*bs
)
2466 BlockDriver
*drv
= bs
->drv
;
2470 if (!drv
->bdrv_is_inserted
)
2472 ret
= drv
->bdrv_is_inserted(bs
);
2477 * Return TRUE if the media changed since the last call to this
2478 * function. It is currently only used for floppy disks
2480 int bdrv_media_changed(BlockDriverState
*bs
)
2482 BlockDriver
*drv
= bs
->drv
;
2485 if (!drv
|| !drv
->bdrv_media_changed
)
2488 ret
= drv
->bdrv_media_changed(bs
);
2489 if (ret
== -ENOTSUP
)
2490 ret
= bs
->media_changed
;
2491 bs
->media_changed
= 0;
2496 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
2498 int bdrv_eject(BlockDriverState
*bs
, int eject_flag
)
2500 BlockDriver
*drv
= bs
->drv
;
2507 if (!drv
|| !drv
->bdrv_eject
) {
2510 ret
= drv
->bdrv_eject(bs
, eject_flag
);
2512 if (ret
== -ENOTSUP
) {
2521 int bdrv_is_locked(BlockDriverState
*bs
)
2527 * Lock or unlock the media (if it is locked, the user won't be able
2528 * to eject it manually).
2530 void bdrv_set_locked(BlockDriverState
*bs
, int locked
)
2532 BlockDriver
*drv
= bs
->drv
;
2534 bs
->locked
= locked
;
2535 if (drv
&& drv
->bdrv_set_locked
) {
2536 drv
->bdrv_set_locked(bs
, locked
);
2540 /* needed for generic scsi interface */
2542 int bdrv_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
2544 BlockDriver
*drv
= bs
->drv
;
2546 if (drv
&& drv
->bdrv_ioctl
)
2547 return drv
->bdrv_ioctl(bs
, req
, buf
);
2551 BlockDriverAIOCB
*bdrv_aio_ioctl(BlockDriverState
*bs
,
2552 unsigned long int req
, void *buf
,
2553 BlockDriverCompletionFunc
*cb
, void *opaque
)
2555 BlockDriver
*drv
= bs
->drv
;
2557 if (drv
&& drv
->bdrv_aio_ioctl
)
2558 return drv
->bdrv_aio_ioctl(bs
, req
, buf
, cb
, opaque
);
2564 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
2566 return qemu_memalign((bs
&& bs
->buffer_alignment
) ? bs
->buffer_alignment
: 512, size
);
2569 void bdrv_set_dirty_tracking(BlockDriverState
*bs
, int enable
)
2571 int64_t bitmap_size
;
2573 bs
->dirty_count
= 0;
2575 if (!bs
->dirty_bitmap
) {
2576 bitmap_size
= (bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
) +
2577 BDRV_SECTORS_PER_DIRTY_CHUNK
* 8 - 1;
2578 bitmap_size
/= BDRV_SECTORS_PER_DIRTY_CHUNK
* 8;
2580 bs
->dirty_bitmap
= qemu_mallocz(bitmap_size
);
2583 if (bs
->dirty_bitmap
) {
2584 qemu_free(bs
->dirty_bitmap
);
2585 bs
->dirty_bitmap
= NULL
;
2590 int bdrv_get_dirty(BlockDriverState
*bs
, int64_t sector
)
2592 int64_t chunk
= sector
/ (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK
;
2594 if (bs
->dirty_bitmap
&&
2595 (sector
<< BDRV_SECTOR_BITS
) < bdrv_getlength(bs
)) {
2596 return bs
->dirty_bitmap
[chunk
/ (sizeof(unsigned long) * 8)] &
2597 (1 << (chunk
% (sizeof(unsigned long) * 8)));
2603 void bdrv_reset_dirty(BlockDriverState
*bs
, int64_t cur_sector
,
2606 set_dirty_bitmap(bs
, cur_sector
, nr_sectors
, 0);
2609 int64_t bdrv_get_dirty_count(BlockDriverState
*bs
)
2611 return bs
->dirty_count
;