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"
28 #include "block_int.h"
30 #include "qemu-objects.h"
31 #include "qemu-coroutine.h"
34 #include <sys/types.h>
36 #include <sys/ioctl.h>
37 #include <sys/queue.h>
47 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
48 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
49 BlockDriverCompletionFunc
*cb
, void *opaque
);
50 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
51 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
52 BlockDriverCompletionFunc
*cb
, void *opaque
);
53 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
54 BlockDriverCompletionFunc
*cb
, void *opaque
);
55 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
56 BlockDriverCompletionFunc
*cb
, void *opaque
);
57 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
58 uint8_t *buf
, int nb_sectors
);
59 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
60 const uint8_t *buf
, int nb_sectors
);
61 static BlockDriverAIOCB
*bdrv_co_aio_readv_em(BlockDriverState
*bs
,
62 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
63 BlockDriverCompletionFunc
*cb
, void *opaque
);
64 static BlockDriverAIOCB
*bdrv_co_aio_writev_em(BlockDriverState
*bs
,
65 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
66 BlockDriverCompletionFunc
*cb
, void *opaque
);
67 static int coroutine_fn
bdrv_co_readv_em(BlockDriverState
*bs
,
68 int64_t sector_num
, int nb_sectors
,
70 static int coroutine_fn
bdrv_co_writev_em(BlockDriverState
*bs
,
71 int64_t sector_num
, int nb_sectors
,
73 static int coroutine_fn
bdrv_co_flush_em(BlockDriverState
*bs
);
75 static QTAILQ_HEAD(, BlockDriverState
) bdrv_states
=
76 QTAILQ_HEAD_INITIALIZER(bdrv_states
);
78 static QLIST_HEAD(, BlockDriver
) bdrv_drivers
=
79 QLIST_HEAD_INITIALIZER(bdrv_drivers
);
81 /* The device to use for VM snapshots */
82 static BlockDriverState
*bs_snapshots
;
84 /* If non-zero, use only whitelisted block drivers */
85 static int use_bdrv_whitelist
;
88 static int is_windows_drive_prefix(const char *filename
)
90 return (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
91 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
95 int is_windows_drive(const char *filename
)
97 if (is_windows_drive_prefix(filename
) &&
100 if (strstart(filename
, "\\\\.\\", NULL
) ||
101 strstart(filename
, "//./", NULL
))
107 /* check if the path starts with "<protocol>:" */
108 static int path_has_protocol(const char *path
)
111 if (is_windows_drive(path
) ||
112 is_windows_drive_prefix(path
)) {
117 return strchr(path
, ':') != NULL
;
120 int path_is_absolute(const char *path
)
124 /* specific case for names like: "\\.\d:" */
125 if (*path
== '/' || *path
== '\\')
128 p
= strchr(path
, ':');
134 return (*p
== '/' || *p
== '\\');
140 /* if filename is absolute, just copy it to dest. Otherwise, build a
141 path to it by considering it is relative to base_path. URL are
143 void path_combine(char *dest
, int dest_size
,
144 const char *base_path
,
145 const char *filename
)
152 if (path_is_absolute(filename
)) {
153 pstrcpy(dest
, dest_size
, filename
);
155 p
= strchr(base_path
, ':');
160 p1
= strrchr(base_path
, '/');
164 p2
= strrchr(base_path
, '\\');
176 if (len
> dest_size
- 1)
178 memcpy(dest
, base_path
, len
);
180 pstrcat(dest
, dest_size
, filename
);
184 void bdrv_register(BlockDriver
*bdrv
)
186 if (bdrv
->bdrv_co_readv
) {
187 /* Emulate AIO by coroutines, and sync by AIO */
188 bdrv
->bdrv_aio_readv
= bdrv_co_aio_readv_em
;
189 bdrv
->bdrv_aio_writev
= bdrv_co_aio_writev_em
;
190 bdrv
->bdrv_read
= bdrv_read_em
;
191 bdrv
->bdrv_write
= bdrv_write_em
;
193 bdrv
->bdrv_co_readv
= bdrv_co_readv_em
;
194 bdrv
->bdrv_co_writev
= bdrv_co_writev_em
;
196 if (!bdrv
->bdrv_aio_readv
) {
197 /* add AIO emulation layer */
198 bdrv
->bdrv_aio_readv
= bdrv_aio_readv_em
;
199 bdrv
->bdrv_aio_writev
= bdrv_aio_writev_em
;
200 } else if (!bdrv
->bdrv_read
) {
201 /* add synchronous IO emulation layer */
202 bdrv
->bdrv_read
= bdrv_read_em
;
203 bdrv
->bdrv_write
= bdrv_write_em
;
207 if (!bdrv
->bdrv_aio_flush
)
208 bdrv
->bdrv_aio_flush
= bdrv_aio_flush_em
;
210 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
213 /* create a new block device (by default it is empty) */
214 BlockDriverState
*bdrv_new(const char *device_name
)
216 BlockDriverState
*bs
;
218 bs
= g_malloc0(sizeof(BlockDriverState
));
219 pstrcpy(bs
->device_name
, sizeof(bs
->device_name
), device_name
);
220 if (device_name
[0] != '\0') {
221 QTAILQ_INSERT_TAIL(&bdrv_states
, bs
, list
);
226 BlockDriver
*bdrv_find_format(const char *format_name
)
229 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
230 if (!strcmp(drv1
->format_name
, format_name
)) {
237 static int bdrv_is_whitelisted(BlockDriver
*drv
)
239 static const char *whitelist
[] = {
240 CONFIG_BDRV_WHITELIST
245 return 1; /* no whitelist, anything goes */
247 for (p
= whitelist
; *p
; p
++) {
248 if (!strcmp(drv
->format_name
, *p
)) {
255 BlockDriver
*bdrv_find_whitelisted_format(const char *format_name
)
257 BlockDriver
*drv
= bdrv_find_format(format_name
);
258 return drv
&& bdrv_is_whitelisted(drv
) ? drv
: NULL
;
261 int bdrv_create(BlockDriver
*drv
, const char* filename
,
262 QEMUOptionParameter
*options
)
264 if (!drv
->bdrv_create
)
267 return drv
->bdrv_create(filename
, options
);
270 int bdrv_create_file(const char* filename
, QEMUOptionParameter
*options
)
274 drv
= bdrv_find_protocol(filename
);
279 return bdrv_create(drv
, filename
, options
);
283 void get_tmp_filename(char *filename
, int size
)
285 char temp_dir
[MAX_PATH
];
287 GetTempPath(MAX_PATH
, temp_dir
);
288 GetTempFileName(temp_dir
, "qem", 0, filename
);
291 void get_tmp_filename(char *filename
, int size
)
295 /* XXX: race condition possible */
296 tmpdir
= getenv("TMPDIR");
299 snprintf(filename
, size
, "%s/vl.XXXXXX", tmpdir
);
300 fd
= mkstemp(filename
);
306 * Detect host devices. By convention, /dev/cdrom[N] is always
307 * recognized as a host CDROM.
309 static BlockDriver
*find_hdev_driver(const char *filename
)
311 int score_max
= 0, score
;
312 BlockDriver
*drv
= NULL
, *d
;
314 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
315 if (d
->bdrv_probe_device
) {
316 score
= d
->bdrv_probe_device(filename
);
317 if (score
> score_max
) {
327 BlockDriver
*bdrv_find_protocol(const char *filename
)
334 /* TODO Drivers without bdrv_file_open must be specified explicitly */
337 * XXX(hch): we really should not let host device detection
338 * override an explicit protocol specification, but moving this
339 * later breaks access to device names with colons in them.
340 * Thanks to the brain-dead persistent naming schemes on udev-
341 * based Linux systems those actually are quite common.
343 drv1
= find_hdev_driver(filename
);
348 if (!path_has_protocol(filename
)) {
349 return bdrv_find_format("file");
351 p
= strchr(filename
, ':');
354 if (len
> sizeof(protocol
) - 1)
355 len
= sizeof(protocol
) - 1;
356 memcpy(protocol
, filename
, len
);
357 protocol
[len
] = '\0';
358 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
359 if (drv1
->protocol_name
&&
360 !strcmp(drv1
->protocol_name
, protocol
)) {
367 static int find_image_format(const char *filename
, BlockDriver
**pdrv
)
369 int ret
, score
, score_max
;
370 BlockDriver
*drv1
, *drv
;
372 BlockDriverState
*bs
;
374 ret
= bdrv_file_open(&bs
, filename
, 0);
380 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
381 if (bs
->sg
|| !bdrv_is_inserted(bs
)) {
383 drv
= bdrv_find_format("raw");
391 ret
= bdrv_pread(bs
, 0, buf
, sizeof(buf
));
400 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
401 if (drv1
->bdrv_probe
) {
402 score
= drv1
->bdrv_probe(buf
, ret
, filename
);
403 if (score
> score_max
) {
417 * Set the current 'total_sectors' value
419 static int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
421 BlockDriver
*drv
= bs
->drv
;
423 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
427 /* query actual device if possible, otherwise just trust the hint */
428 if (drv
->bdrv_getlength
) {
429 int64_t length
= drv
->bdrv_getlength(bs
);
433 hint
= length
>> BDRV_SECTOR_BITS
;
436 bs
->total_sectors
= hint
;
441 * Set open flags for a given cache mode
443 * Return 0 on success, -1 if the cache mode was invalid.
445 int bdrv_parse_cache_flags(const char *mode
, int *flags
)
447 *flags
&= ~BDRV_O_CACHE_MASK
;
449 if (!strcmp(mode
, "off") || !strcmp(mode
, "none")) {
450 *flags
|= BDRV_O_NOCACHE
| BDRV_O_CACHE_WB
;
451 } else if (!strcmp(mode
, "directsync")) {
452 *flags
|= BDRV_O_NOCACHE
;
453 } else if (!strcmp(mode
, "writeback")) {
454 *flags
|= BDRV_O_CACHE_WB
;
455 } else if (!strcmp(mode
, "unsafe")) {
456 *flags
|= BDRV_O_CACHE_WB
;
457 *flags
|= BDRV_O_NO_FLUSH
;
458 } else if (!strcmp(mode
, "writethrough")) {
459 /* this is the default */
468 * Common part for opening disk images and files
470 static int bdrv_open_common(BlockDriverState
*bs
, const char *filename
,
471 int flags
, BlockDriver
*drv
)
478 bs
->total_sectors
= 0;
481 bs
->open_flags
= flags
;
482 /* buffer_alignment defaulted to 512, drivers can change this value */
483 bs
->buffer_alignment
= 512;
485 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
487 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
)) {
492 bs
->opaque
= g_malloc0(drv
->instance_size
);
494 if (flags
& BDRV_O_CACHE_WB
)
495 bs
->enable_write_cache
= 1;
498 * Clear flags that are internal to the block layer before opening the
501 open_flags
= flags
& ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
504 * Snapshots should be writable.
506 if (bs
->is_temporary
) {
507 open_flags
|= BDRV_O_RDWR
;
510 /* Open the image, either directly or using a protocol */
511 if (drv
->bdrv_file_open
) {
512 ret
= drv
->bdrv_file_open(bs
, filename
, open_flags
);
514 ret
= bdrv_file_open(&bs
->file
, filename
, open_flags
);
516 ret
= drv
->bdrv_open(bs
, open_flags
);
524 bs
->keep_read_only
= bs
->read_only
= !(open_flags
& BDRV_O_RDWR
);
526 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
532 if (bs
->is_temporary
) {
540 bdrv_delete(bs
->file
);
550 * Opens a file using a protocol (file, host_device, nbd, ...)
552 int bdrv_file_open(BlockDriverState
**pbs
, const char *filename
, int flags
)
554 BlockDriverState
*bs
;
558 drv
= bdrv_find_protocol(filename
);
564 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
575 * Opens a disk image (raw, qcow2, vmdk, ...)
577 int bdrv_open(BlockDriverState
*bs
, const char *filename
, int flags
,
582 if (flags
& BDRV_O_SNAPSHOT
) {
583 BlockDriverState
*bs1
;
586 BlockDriver
*bdrv_qcow2
;
587 QEMUOptionParameter
*options
;
588 char tmp_filename
[PATH_MAX
];
589 char backing_filename
[PATH_MAX
];
591 /* if snapshot, we create a temporary backing file and open it
592 instead of opening 'filename' directly */
594 /* if there is a backing file, use it */
596 ret
= bdrv_open(bs1
, filename
, 0, drv
);
601 total_size
= bdrv_getlength(bs1
) & BDRV_SECTOR_MASK
;
603 if (bs1
->drv
&& bs1
->drv
->protocol_name
)
608 get_tmp_filename(tmp_filename
, sizeof(tmp_filename
));
610 /* Real path is meaningless for protocols */
612 snprintf(backing_filename
, sizeof(backing_filename
),
614 else if (!realpath(filename
, backing_filename
))
617 bdrv_qcow2
= bdrv_find_format("qcow2");
618 options
= parse_option_parameters("", bdrv_qcow2
->create_options
, NULL
);
620 set_option_parameter_int(options
, BLOCK_OPT_SIZE
, total_size
);
621 set_option_parameter(options
, BLOCK_OPT_BACKING_FILE
, backing_filename
);
623 set_option_parameter(options
, BLOCK_OPT_BACKING_FMT
,
627 ret
= bdrv_create(bdrv_qcow2
, tmp_filename
, options
);
628 free_option_parameters(options
);
633 filename
= tmp_filename
;
635 bs
->is_temporary
= 1;
638 /* Find the right image format driver */
640 ret
= find_image_format(filename
, &drv
);
644 goto unlink_and_fail
;
648 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
650 goto unlink_and_fail
;
653 /* If there is a backing file, use it */
654 if ((flags
& BDRV_O_NO_BACKING
) == 0 && bs
->backing_file
[0] != '\0') {
655 char backing_filename
[PATH_MAX
];
657 BlockDriver
*back_drv
= NULL
;
659 bs
->backing_hd
= bdrv_new("");
661 if (path_has_protocol(bs
->backing_file
)) {
662 pstrcpy(backing_filename
, sizeof(backing_filename
),
665 path_combine(backing_filename
, sizeof(backing_filename
),
666 filename
, bs
->backing_file
);
669 if (bs
->backing_format
[0] != '\0') {
670 back_drv
= bdrv_find_format(bs
->backing_format
);
673 /* backing files always opened read-only */
675 flags
& ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
677 ret
= bdrv_open(bs
->backing_hd
, backing_filename
, back_flags
, back_drv
);
682 if (bs
->is_temporary
) {
683 bs
->backing_hd
->keep_read_only
= !(flags
& BDRV_O_RDWR
);
685 /* base image inherits from "parent" */
686 bs
->backing_hd
->keep_read_only
= bs
->keep_read_only
;
690 if (!bdrv_key_required(bs
)) {
691 /* call the change callback */
692 bs
->media_changed
= 1;
694 bs
->change_cb(bs
->change_opaque
, CHANGE_MEDIA
);
700 if (bs
->is_temporary
) {
706 void bdrv_close(BlockDriverState
*bs
)
709 if (bs
== bs_snapshots
) {
712 if (bs
->backing_hd
) {
713 bdrv_delete(bs
->backing_hd
);
714 bs
->backing_hd
= NULL
;
716 bs
->drv
->bdrv_close(bs
);
719 if (bs
->is_temporary
) {
720 unlink(bs
->filename
);
726 if (bs
->file
!= NULL
) {
727 bdrv_close(bs
->file
);
730 /* call the change callback */
731 bs
->media_changed
= 1;
733 bs
->change_cb(bs
->change_opaque
, CHANGE_MEDIA
);
737 void bdrv_close_all(void)
739 BlockDriverState
*bs
;
741 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
746 /* make a BlockDriverState anonymous by removing from bdrv_state list.
747 Also, NULL terminate the device_name to prevent double remove */
748 void bdrv_make_anon(BlockDriverState
*bs
)
750 if (bs
->device_name
[0] != '\0') {
751 QTAILQ_REMOVE(&bdrv_states
, bs
, list
);
753 bs
->device_name
[0] = '\0';
756 void bdrv_delete(BlockDriverState
*bs
)
760 /* remove from list, if necessary */
764 if (bs
->file
!= NULL
) {
765 bdrv_delete(bs
->file
);
768 assert(bs
!= bs_snapshots
);
772 int bdrv_attach(BlockDriverState
*bs
, DeviceState
*qdev
)
781 void bdrv_detach(BlockDriverState
*bs
, DeviceState
*qdev
)
783 assert(bs
->peer
== qdev
);
785 bs
->change_cb
= NULL
;
786 bs
->change_opaque
= NULL
;
789 DeviceState
*bdrv_get_attached(BlockDriverState
*bs
)
795 * Run consistency checks on an image
797 * Returns 0 if the check could be completed (it doesn't mean that the image is
798 * free of errors) or -errno when an internal error occurred. The results of the
799 * check are stored in res.
801 int bdrv_check(BlockDriverState
*bs
, BdrvCheckResult
*res
)
803 if (bs
->drv
->bdrv_check
== NULL
) {
807 memset(res
, 0, sizeof(*res
));
808 return bs
->drv
->bdrv_check(bs
, res
);
811 #define COMMIT_BUF_SECTORS 2048
813 /* commit COW file into the raw image */
814 int bdrv_commit(BlockDriverState
*bs
)
816 BlockDriver
*drv
= bs
->drv
;
817 BlockDriver
*backing_drv
;
818 int64_t sector
, total_sectors
;
819 int n
, ro
, open_flags
;
820 int ret
= 0, rw_ret
= 0;
823 BlockDriverState
*bs_rw
, *bs_ro
;
828 if (!bs
->backing_hd
) {
832 if (bs
->backing_hd
->keep_read_only
) {
836 backing_drv
= bs
->backing_hd
->drv
;
837 ro
= bs
->backing_hd
->read_only
;
838 strncpy(filename
, bs
->backing_hd
->filename
, sizeof(filename
));
839 open_flags
= bs
->backing_hd
->open_flags
;
843 bdrv_delete(bs
->backing_hd
);
844 bs
->backing_hd
= NULL
;
845 bs_rw
= bdrv_new("");
846 rw_ret
= bdrv_open(bs_rw
, filename
, open_flags
| BDRV_O_RDWR
,
850 /* try to re-open read-only */
851 bs_ro
= bdrv_new("");
852 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
,
856 /* drive not functional anymore */
860 bs
->backing_hd
= bs_ro
;
863 bs
->backing_hd
= bs_rw
;
866 total_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
867 buf
= g_malloc(COMMIT_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
869 for (sector
= 0; sector
< total_sectors
; sector
+= n
) {
870 if (drv
->bdrv_is_allocated(bs
, sector
, COMMIT_BUF_SECTORS
, &n
)) {
872 if (bdrv_read(bs
, sector
, buf
, n
) != 0) {
877 if (bdrv_write(bs
->backing_hd
, sector
, buf
, n
) != 0) {
884 if (drv
->bdrv_make_empty
) {
885 ret
= drv
->bdrv_make_empty(bs
);
890 * Make sure all data we wrote to the backing device is actually
894 bdrv_flush(bs
->backing_hd
);
901 bdrv_delete(bs
->backing_hd
);
902 bs
->backing_hd
= NULL
;
903 bs_ro
= bdrv_new("");
904 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
,
908 /* drive not functional anymore */
912 bs
->backing_hd
= bs_ro
;
913 bs
->backing_hd
->keep_read_only
= 0;
919 void bdrv_commit_all(void)
921 BlockDriverState
*bs
;
923 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
931 * -EINVAL - backing format specified, but no file
932 * -ENOSPC - can't update the backing file because no space is left in the
934 * -ENOTSUP - format driver doesn't support changing the backing file
936 int bdrv_change_backing_file(BlockDriverState
*bs
,
937 const char *backing_file
, const char *backing_fmt
)
939 BlockDriver
*drv
= bs
->drv
;
941 if (drv
->bdrv_change_backing_file
!= NULL
) {
942 return drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
948 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
953 if (!bdrv_is_inserted(bs
))
959 len
= bdrv_getlength(bs
);
964 if ((offset
> len
) || (len
- offset
< size
))
970 static int bdrv_check_request(BlockDriverState
*bs
, int64_t sector_num
,
973 return bdrv_check_byte_request(bs
, sector_num
* BDRV_SECTOR_SIZE
,
974 nb_sectors
* BDRV_SECTOR_SIZE
);
977 static inline bool bdrv_has_async_rw(BlockDriver
*drv
)
979 return drv
->bdrv_co_readv
!= bdrv_co_readv_em
980 || drv
->bdrv_aio_readv
!= bdrv_aio_readv_em
;
983 static inline bool bdrv_has_async_flush(BlockDriver
*drv
)
985 return drv
->bdrv_aio_flush
!= bdrv_aio_flush_em
;
988 /* return < 0 if error. See bdrv_write() for the return codes */
989 int bdrv_read(BlockDriverState
*bs
, int64_t sector_num
,
990 uint8_t *buf
, int nb_sectors
)
992 BlockDriver
*drv
= bs
->drv
;
997 if (bdrv_has_async_rw(drv
) && qemu_in_coroutine()) {
1000 .iov_base
= (void *)buf
,
1001 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
1004 qemu_iovec_init_external(&qiov
, &iov
, 1);
1005 return bdrv_co_readv(bs
, sector_num
, nb_sectors
, &qiov
);
1008 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1011 return drv
->bdrv_read(bs
, sector_num
, buf
, nb_sectors
);
1014 static void set_dirty_bitmap(BlockDriverState
*bs
, int64_t sector_num
,
1015 int nb_sectors
, int dirty
)
1018 unsigned long val
, idx
, bit
;
1020 start
= sector_num
/ BDRV_SECTORS_PER_DIRTY_CHUNK
;
1021 end
= (sector_num
+ nb_sectors
- 1) / BDRV_SECTORS_PER_DIRTY_CHUNK
;
1023 for (; start
<= end
; start
++) {
1024 idx
= start
/ (sizeof(unsigned long) * 8);
1025 bit
= start
% (sizeof(unsigned long) * 8);
1026 val
= bs
->dirty_bitmap
[idx
];
1028 if (!(val
& (1UL << bit
))) {
1033 if (val
& (1UL << bit
)) {
1035 val
&= ~(1UL << bit
);
1038 bs
->dirty_bitmap
[idx
] = val
;
1042 /* Return < 0 if error. Important errors are:
1043 -EIO generic I/O error (may happen for all errors)
1044 -ENOMEDIUM No media inserted.
1045 -EINVAL Invalid sector number or nb_sectors
1046 -EACCES Trying to write a read-only device
1048 int bdrv_write(BlockDriverState
*bs
, int64_t sector_num
,
1049 const uint8_t *buf
, int nb_sectors
)
1051 BlockDriver
*drv
= bs
->drv
;
1056 if (bdrv_has_async_rw(drv
) && qemu_in_coroutine()) {
1058 struct iovec iov
= {
1059 .iov_base
= (void *)buf
,
1060 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
1063 qemu_iovec_init_external(&qiov
, &iov
, 1);
1064 return bdrv_co_writev(bs
, sector_num
, nb_sectors
, &qiov
);
1069 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1072 if (bs
->dirty_bitmap
) {
1073 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1076 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1077 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1080 return drv
->bdrv_write(bs
, sector_num
, buf
, nb_sectors
);
1083 int bdrv_pread(BlockDriverState
*bs
, int64_t offset
,
1084 void *buf
, int count1
)
1086 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1087 int len
, nb_sectors
, count
;
1092 /* first read to align to sector start */
1093 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1096 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1098 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1100 memcpy(buf
, tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), len
);
1108 /* read the sectors "in place" */
1109 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1110 if (nb_sectors
> 0) {
1111 if ((ret
= bdrv_read(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1113 sector_num
+= nb_sectors
;
1114 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1119 /* add data from the last sector */
1121 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1123 memcpy(buf
, tmp_buf
, count
);
1128 int bdrv_pwrite(BlockDriverState
*bs
, int64_t offset
,
1129 const void *buf
, int count1
)
1131 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1132 int len
, nb_sectors
, count
;
1137 /* first write to align to sector start */
1138 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1141 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1143 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1145 memcpy(tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), buf
, len
);
1146 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1155 /* write the sectors "in place" */
1156 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1157 if (nb_sectors
> 0) {
1158 if ((ret
= bdrv_write(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1160 sector_num
+= nb_sectors
;
1161 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1166 /* add data from the last sector */
1168 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1170 memcpy(tmp_buf
, buf
, count
);
1171 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1178 * Writes to the file and ensures that no writes are reordered across this
1179 * request (acts as a barrier)
1181 * Returns 0 on success, -errno in error cases.
1183 int bdrv_pwrite_sync(BlockDriverState
*bs
, int64_t offset
,
1184 const void *buf
, int count
)
1188 ret
= bdrv_pwrite(bs
, offset
, buf
, count
);
1193 /* No flush needed for cache modes that use O_DSYNC */
1194 if ((bs
->open_flags
& BDRV_O_CACHE_WB
) != 0) {
1201 int coroutine_fn
bdrv_co_readv(BlockDriverState
*bs
, int64_t sector_num
,
1202 int nb_sectors
, QEMUIOVector
*qiov
)
1204 BlockDriver
*drv
= bs
->drv
;
1206 trace_bdrv_co_readv(bs
, sector_num
, nb_sectors
);
1211 if (bdrv_check_request(bs
, sector_num
, nb_sectors
)) {
1215 return drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1218 int coroutine_fn
bdrv_co_writev(BlockDriverState
*bs
, int64_t sector_num
,
1219 int nb_sectors
, QEMUIOVector
*qiov
)
1221 BlockDriver
*drv
= bs
->drv
;
1223 trace_bdrv_co_writev(bs
, sector_num
, nb_sectors
);
1228 if (bs
->read_only
) {
1231 if (bdrv_check_request(bs
, sector_num
, nb_sectors
)) {
1235 if (bs
->dirty_bitmap
) {
1236 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1239 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1240 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1243 return drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
);
1247 * Truncate file to 'offset' bytes (needed only for file protocols)
1249 int bdrv_truncate(BlockDriverState
*bs
, int64_t offset
)
1251 BlockDriver
*drv
= bs
->drv
;
1255 if (!drv
->bdrv_truncate
)
1259 if (bdrv_in_use(bs
))
1261 ret
= drv
->bdrv_truncate(bs
, offset
);
1263 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
1264 if (bs
->change_cb
) {
1265 bs
->change_cb(bs
->change_opaque
, CHANGE_SIZE
);
1272 * Length of a allocated file in bytes. Sparse files are counted by actual
1273 * allocated space. Return < 0 if error or unknown.
1275 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
1277 BlockDriver
*drv
= bs
->drv
;
1281 if (drv
->bdrv_get_allocated_file_size
) {
1282 return drv
->bdrv_get_allocated_file_size(bs
);
1285 return bdrv_get_allocated_file_size(bs
->file
);
1291 * Length of a file in bytes. Return < 0 if error or unknown.
1293 int64_t bdrv_getlength(BlockDriverState
*bs
)
1295 BlockDriver
*drv
= bs
->drv
;
1299 if (bs
->growable
|| bs
->removable
) {
1300 if (drv
->bdrv_getlength
) {
1301 return drv
->bdrv_getlength(bs
);
1304 return bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1307 /* return 0 as number of sectors if no device present or error */
1308 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
1311 length
= bdrv_getlength(bs
);
1315 length
= length
>> BDRV_SECTOR_BITS
;
1316 *nb_sectors_ptr
= length
;
1320 uint8_t boot_ind
; /* 0x80 - active */
1321 uint8_t head
; /* starting head */
1322 uint8_t sector
; /* starting sector */
1323 uint8_t cyl
; /* starting cylinder */
1324 uint8_t sys_ind
; /* What partition type */
1325 uint8_t end_head
; /* end head */
1326 uint8_t end_sector
; /* end sector */
1327 uint8_t end_cyl
; /* end cylinder */
1328 uint32_t start_sect
; /* starting sector counting from 0 */
1329 uint32_t nr_sects
; /* nr of sectors in partition */
1330 } __attribute__((packed
));
1332 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1333 static int guess_disk_lchs(BlockDriverState
*bs
,
1334 int *pcylinders
, int *pheads
, int *psectors
)
1336 uint8_t buf
[BDRV_SECTOR_SIZE
];
1337 int ret
, i
, heads
, sectors
, cylinders
;
1338 struct partition
*p
;
1340 uint64_t nb_sectors
;
1342 bdrv_get_geometry(bs
, &nb_sectors
);
1344 ret
= bdrv_read(bs
, 0, buf
, 1);
1347 /* test msdos magic */
1348 if (buf
[510] != 0x55 || buf
[511] != 0xaa)
1350 for(i
= 0; i
< 4; i
++) {
1351 p
= ((struct partition
*)(buf
+ 0x1be)) + i
;
1352 nr_sects
= le32_to_cpu(p
->nr_sects
);
1353 if (nr_sects
&& p
->end_head
) {
1354 /* We make the assumption that the partition terminates on
1355 a cylinder boundary */
1356 heads
= p
->end_head
+ 1;
1357 sectors
= p
->end_sector
& 63;
1360 cylinders
= nb_sectors
/ (heads
* sectors
);
1361 if (cylinders
< 1 || cylinders
> 16383)
1364 *psectors
= sectors
;
1365 *pcylinders
= cylinders
;
1367 printf("guessed geometry: LCHS=%d %d %d\n",
1368 cylinders
, heads
, sectors
);
1376 void bdrv_guess_geometry(BlockDriverState
*bs
, int *pcyls
, int *pheads
, int *psecs
)
1378 int translation
, lba_detected
= 0;
1379 int cylinders
, heads
, secs
;
1380 uint64_t nb_sectors
;
1382 /* if a geometry hint is available, use it */
1383 bdrv_get_geometry(bs
, &nb_sectors
);
1384 bdrv_get_geometry_hint(bs
, &cylinders
, &heads
, &secs
);
1385 translation
= bdrv_get_translation_hint(bs
);
1386 if (cylinders
!= 0) {
1391 if (guess_disk_lchs(bs
, &cylinders
, &heads
, &secs
) == 0) {
1393 /* if heads > 16, it means that a BIOS LBA
1394 translation was active, so the default
1395 hardware geometry is OK */
1397 goto default_geometry
;
1402 /* disable any translation to be in sync with
1403 the logical geometry */
1404 if (translation
== BIOS_ATA_TRANSLATION_AUTO
) {
1405 bdrv_set_translation_hint(bs
,
1406 BIOS_ATA_TRANSLATION_NONE
);
1411 /* if no geometry, use a standard physical disk geometry */
1412 cylinders
= nb_sectors
/ (16 * 63);
1414 if (cylinders
> 16383)
1416 else if (cylinders
< 2)
1421 if ((lba_detected
== 1) && (translation
== BIOS_ATA_TRANSLATION_AUTO
)) {
1422 if ((*pcyls
* *pheads
) <= 131072) {
1423 bdrv_set_translation_hint(bs
,
1424 BIOS_ATA_TRANSLATION_LARGE
);
1426 bdrv_set_translation_hint(bs
,
1427 BIOS_ATA_TRANSLATION_LBA
);
1431 bdrv_set_geometry_hint(bs
, *pcyls
, *pheads
, *psecs
);
1435 void bdrv_set_geometry_hint(BlockDriverState
*bs
,
1436 int cyls
, int heads
, int secs
)
1443 void bdrv_set_translation_hint(BlockDriverState
*bs
, int translation
)
1445 bs
->translation
= translation
;
1448 void bdrv_get_geometry_hint(BlockDriverState
*bs
,
1449 int *pcyls
, int *pheads
, int *psecs
)
1452 *pheads
= bs
->heads
;
1456 /* Recognize floppy formats */
1457 typedef struct FDFormat
{
1464 static const FDFormat fd_formats
[] = {
1465 /* First entry is default format */
1466 /* 1.44 MB 3"1/2 floppy disks */
1467 { FDRIVE_DRV_144
, 18, 80, 1, },
1468 { FDRIVE_DRV_144
, 20, 80, 1, },
1469 { FDRIVE_DRV_144
, 21, 80, 1, },
1470 { FDRIVE_DRV_144
, 21, 82, 1, },
1471 { FDRIVE_DRV_144
, 21, 83, 1, },
1472 { FDRIVE_DRV_144
, 22, 80, 1, },
1473 { FDRIVE_DRV_144
, 23, 80, 1, },
1474 { FDRIVE_DRV_144
, 24, 80, 1, },
1475 /* 2.88 MB 3"1/2 floppy disks */
1476 { FDRIVE_DRV_288
, 36, 80, 1, },
1477 { FDRIVE_DRV_288
, 39, 80, 1, },
1478 { FDRIVE_DRV_288
, 40, 80, 1, },
1479 { FDRIVE_DRV_288
, 44, 80, 1, },
1480 { FDRIVE_DRV_288
, 48, 80, 1, },
1481 /* 720 kB 3"1/2 floppy disks */
1482 { FDRIVE_DRV_144
, 9, 80, 1, },
1483 { FDRIVE_DRV_144
, 10, 80, 1, },
1484 { FDRIVE_DRV_144
, 10, 82, 1, },
1485 { FDRIVE_DRV_144
, 10, 83, 1, },
1486 { FDRIVE_DRV_144
, 13, 80, 1, },
1487 { FDRIVE_DRV_144
, 14, 80, 1, },
1488 /* 1.2 MB 5"1/4 floppy disks */
1489 { FDRIVE_DRV_120
, 15, 80, 1, },
1490 { FDRIVE_DRV_120
, 18, 80, 1, },
1491 { FDRIVE_DRV_120
, 18, 82, 1, },
1492 { FDRIVE_DRV_120
, 18, 83, 1, },
1493 { FDRIVE_DRV_120
, 20, 80, 1, },
1494 /* 720 kB 5"1/4 floppy disks */
1495 { FDRIVE_DRV_120
, 9, 80, 1, },
1496 { FDRIVE_DRV_120
, 11, 80, 1, },
1497 /* 360 kB 5"1/4 floppy disks */
1498 { FDRIVE_DRV_120
, 9, 40, 1, },
1499 { FDRIVE_DRV_120
, 9, 40, 0, },
1500 { FDRIVE_DRV_120
, 10, 41, 1, },
1501 { FDRIVE_DRV_120
, 10, 42, 1, },
1502 /* 320 kB 5"1/4 floppy disks */
1503 { FDRIVE_DRV_120
, 8, 40, 1, },
1504 { FDRIVE_DRV_120
, 8, 40, 0, },
1505 /* 360 kB must match 5"1/4 better than 3"1/2... */
1506 { FDRIVE_DRV_144
, 9, 80, 0, },
1508 { FDRIVE_DRV_NONE
, -1, -1, 0, },
1511 void bdrv_get_floppy_geometry_hint(BlockDriverState
*bs
, int *nb_heads
,
1512 int *max_track
, int *last_sect
,
1513 FDriveType drive_in
, FDriveType
*drive
)
1515 const FDFormat
*parse
;
1516 uint64_t nb_sectors
, size
;
1517 int i
, first_match
, match
;
1519 bdrv_get_geometry_hint(bs
, nb_heads
, max_track
, last_sect
);
1520 if (*nb_heads
!= 0 && *max_track
!= 0 && *last_sect
!= 0) {
1521 /* User defined disk */
1523 bdrv_get_geometry(bs
, &nb_sectors
);
1526 for (i
= 0; ; i
++) {
1527 parse
= &fd_formats
[i
];
1528 if (parse
->drive
== FDRIVE_DRV_NONE
) {
1531 if (drive_in
== parse
->drive
||
1532 drive_in
== FDRIVE_DRV_NONE
) {
1533 size
= (parse
->max_head
+ 1) * parse
->max_track
*
1535 if (nb_sectors
== size
) {
1539 if (first_match
== -1) {
1545 if (first_match
== -1) {
1548 match
= first_match
;
1550 parse
= &fd_formats
[match
];
1552 *nb_heads
= parse
->max_head
+ 1;
1553 *max_track
= parse
->max_track
;
1554 *last_sect
= parse
->last_sect
;
1555 *drive
= parse
->drive
;
1559 int bdrv_get_translation_hint(BlockDriverState
*bs
)
1561 return bs
->translation
;
1564 void bdrv_set_on_error(BlockDriverState
*bs
, BlockErrorAction on_read_error
,
1565 BlockErrorAction on_write_error
)
1567 bs
->on_read_error
= on_read_error
;
1568 bs
->on_write_error
= on_write_error
;
1571 BlockErrorAction
bdrv_get_on_error(BlockDriverState
*bs
, int is_read
)
1573 return is_read
? bs
->on_read_error
: bs
->on_write_error
;
1576 void bdrv_set_removable(BlockDriverState
*bs
, int removable
)
1578 bs
->removable
= removable
;
1579 if (removable
&& bs
== bs_snapshots
) {
1580 bs_snapshots
= NULL
;
1584 int bdrv_is_removable(BlockDriverState
*bs
)
1586 return bs
->removable
;
1589 int bdrv_is_read_only(BlockDriverState
*bs
)
1591 return bs
->read_only
;
1594 int bdrv_is_sg(BlockDriverState
*bs
)
1599 int bdrv_enable_write_cache(BlockDriverState
*bs
)
1601 return bs
->enable_write_cache
;
1604 /* XXX: no longer used */
1605 void bdrv_set_change_cb(BlockDriverState
*bs
,
1606 void (*change_cb
)(void *opaque
, int reason
),
1609 bs
->change_cb
= change_cb
;
1610 bs
->change_opaque
= opaque
;
1613 int bdrv_is_encrypted(BlockDriverState
*bs
)
1615 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1617 return bs
->encrypted
;
1620 int bdrv_key_required(BlockDriverState
*bs
)
1622 BlockDriverState
*backing_hd
= bs
->backing_hd
;
1624 if (backing_hd
&& backing_hd
->encrypted
&& !backing_hd
->valid_key
)
1626 return (bs
->encrypted
&& !bs
->valid_key
);
1629 int bdrv_set_key(BlockDriverState
*bs
, const char *key
)
1632 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
) {
1633 ret
= bdrv_set_key(bs
->backing_hd
, key
);
1639 if (!bs
->encrypted
) {
1641 } else if (!bs
->drv
|| !bs
->drv
->bdrv_set_key
) {
1644 ret
= bs
->drv
->bdrv_set_key(bs
, key
);
1647 } else if (!bs
->valid_key
) {
1649 /* call the change callback now, we skipped it on open */
1650 bs
->media_changed
= 1;
1652 bs
->change_cb(bs
->change_opaque
, CHANGE_MEDIA
);
1657 void bdrv_get_format(BlockDriverState
*bs
, char *buf
, int buf_size
)
1662 pstrcpy(buf
, buf_size
, bs
->drv
->format_name
);
1666 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
1671 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
1672 it(opaque
, drv
->format_name
);
1676 BlockDriverState
*bdrv_find(const char *name
)
1678 BlockDriverState
*bs
;
1680 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1681 if (!strcmp(name
, bs
->device_name
)) {
1688 BlockDriverState
*bdrv_next(BlockDriverState
*bs
)
1691 return QTAILQ_FIRST(&bdrv_states
);
1693 return QTAILQ_NEXT(bs
, list
);
1696 void bdrv_iterate(void (*it
)(void *opaque
, BlockDriverState
*bs
), void *opaque
)
1698 BlockDriverState
*bs
;
1700 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1705 const char *bdrv_get_device_name(BlockDriverState
*bs
)
1707 return bs
->device_name
;
1710 int bdrv_flush(BlockDriverState
*bs
)
1712 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
1716 if (bs
->drv
&& bdrv_has_async_flush(bs
->drv
) && qemu_in_coroutine()) {
1717 return bdrv_co_flush_em(bs
);
1720 if (bs
->drv
&& bs
->drv
->bdrv_flush
) {
1721 return bs
->drv
->bdrv_flush(bs
);
1725 * Some block drivers always operate in either writethrough or unsafe mode
1726 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1727 * the server works (because the behaviour is hardcoded or depends on
1728 * server-side configuration), so we can't ensure that everything is safe
1729 * on disk. Returning an error doesn't work because that would break guests
1730 * even if the server operates in writethrough mode.
1732 * Let's hope the user knows what he's doing.
1737 void bdrv_flush_all(void)
1739 BlockDriverState
*bs
;
1741 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1742 if (bs
->drv
&& !bdrv_is_read_only(bs
) &&
1743 (!bdrv_is_removable(bs
) || bdrv_is_inserted(bs
))) {
1749 int bdrv_has_zero_init(BlockDriverState
*bs
)
1753 if (bs
->drv
->bdrv_has_zero_init
) {
1754 return bs
->drv
->bdrv_has_zero_init(bs
);
1760 int bdrv_discard(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
)
1765 if (!bs
->drv
->bdrv_discard
) {
1768 return bs
->drv
->bdrv_discard(bs
, sector_num
, nb_sectors
);
1772 * Returns true iff the specified sector is present in the disk image. Drivers
1773 * not implementing the functionality are assumed to not support backing files,
1774 * hence all their sectors are reported as allocated.
1776 * 'pnum' is set to the number of sectors (including and immediately following
1777 * the specified sector) that are known to be in the same
1778 * allocated/unallocated state.
1780 * 'nb_sectors' is the max value 'pnum' should be set to.
1782 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
,
1786 if (!bs
->drv
->bdrv_is_allocated
) {
1787 if (sector_num
>= bs
->total_sectors
) {
1791 n
= bs
->total_sectors
- sector_num
;
1792 *pnum
= (n
< nb_sectors
) ? (n
) : (nb_sectors
);
1795 return bs
->drv
->bdrv_is_allocated(bs
, sector_num
, nb_sectors
, pnum
);
1798 void bdrv_mon_event(const BlockDriverState
*bdrv
,
1799 BlockMonEventAction action
, int is_read
)
1802 const char *action_str
;
1805 case BDRV_ACTION_REPORT
:
1806 action_str
= "report";
1808 case BDRV_ACTION_IGNORE
:
1809 action_str
= "ignore";
1811 case BDRV_ACTION_STOP
:
1812 action_str
= "stop";
1818 data
= qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1821 is_read
? "read" : "write");
1822 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR
, data
);
1824 qobject_decref(data
);
1827 static void bdrv_print_dict(QObject
*obj
, void *opaque
)
1830 Monitor
*mon
= opaque
;
1832 bs_dict
= qobject_to_qdict(obj
);
1834 monitor_printf(mon
, "%s: removable=%d",
1835 qdict_get_str(bs_dict
, "device"),
1836 qdict_get_bool(bs_dict
, "removable"));
1838 if (qdict_get_bool(bs_dict
, "removable")) {
1839 monitor_printf(mon
, " locked=%d", qdict_get_bool(bs_dict
, "locked"));
1842 if (qdict_haskey(bs_dict
, "inserted")) {
1843 QDict
*qdict
= qobject_to_qdict(qdict_get(bs_dict
, "inserted"));
1845 monitor_printf(mon
, " file=");
1846 monitor_print_filename(mon
, qdict_get_str(qdict
, "file"));
1847 if (qdict_haskey(qdict
, "backing_file")) {
1848 monitor_printf(mon
, " backing_file=");
1849 monitor_print_filename(mon
, qdict_get_str(qdict
, "backing_file"));
1851 monitor_printf(mon
, " ro=%d drv=%s encrypted=%d",
1852 qdict_get_bool(qdict
, "ro"),
1853 qdict_get_str(qdict
, "drv"),
1854 qdict_get_bool(qdict
, "encrypted"));
1856 monitor_printf(mon
, " [not inserted]");
1859 monitor_printf(mon
, "\n");
1862 void bdrv_info_print(Monitor
*mon
, const QObject
*data
)
1864 qlist_iter(qobject_to_qlist(data
), bdrv_print_dict
, mon
);
1867 void bdrv_info(Monitor
*mon
, QObject
**ret_data
)
1870 BlockDriverState
*bs
;
1872 bs_list
= qlist_new();
1874 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1877 bs_obj
= qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
1878 "'removable': %i, 'locked': %i }",
1879 bs
->device_name
, bs
->removable
,
1884 QDict
*bs_dict
= qobject_to_qdict(bs_obj
);
1886 obj
= qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1887 "'encrypted': %i }",
1888 bs
->filename
, bs
->read_only
,
1889 bs
->drv
->format_name
,
1890 bdrv_is_encrypted(bs
));
1891 if (bs
->backing_file
[0] != '\0') {
1892 QDict
*qdict
= qobject_to_qdict(obj
);
1893 qdict_put(qdict
, "backing_file",
1894 qstring_from_str(bs
->backing_file
));
1897 qdict_put_obj(bs_dict
, "inserted", obj
);
1899 qlist_append_obj(bs_list
, bs_obj
);
1902 *ret_data
= QOBJECT(bs_list
);
1905 static void bdrv_stats_iter(QObject
*data
, void *opaque
)
1908 Monitor
*mon
= opaque
;
1910 qdict
= qobject_to_qdict(data
);
1911 monitor_printf(mon
, "%s:", qdict_get_str(qdict
, "device"));
1913 qdict
= qobject_to_qdict(qdict_get(qdict
, "stats"));
1914 monitor_printf(mon
, " rd_bytes=%" PRId64
1915 " wr_bytes=%" PRId64
1916 " rd_operations=%" PRId64
1917 " wr_operations=%" PRId64
1918 " flush_operations=%" PRId64
1920 qdict_get_int(qdict
, "rd_bytes"),
1921 qdict_get_int(qdict
, "wr_bytes"),
1922 qdict_get_int(qdict
, "rd_operations"),
1923 qdict_get_int(qdict
, "wr_operations"),
1924 qdict_get_int(qdict
, "flush_operations"));
1927 void bdrv_stats_print(Monitor
*mon
, const QObject
*data
)
1929 qlist_iter(qobject_to_qlist(data
), bdrv_stats_iter
, mon
);
1932 static QObject
* bdrv_info_stats_bs(BlockDriverState
*bs
)
1937 res
= qobject_from_jsonf("{ 'stats': {"
1938 "'rd_bytes': %" PRId64
","
1939 "'wr_bytes': %" PRId64
","
1940 "'rd_operations': %" PRId64
","
1941 "'wr_operations': %" PRId64
","
1942 "'wr_highest_offset': %" PRId64
","
1943 "'flush_operations': %" PRId64
1949 bs
->wr_highest_sector
*
1950 (uint64_t)BDRV_SECTOR_SIZE
,
1952 dict
= qobject_to_qdict(res
);
1954 if (*bs
->device_name
) {
1955 qdict_put(dict
, "device", qstring_from_str(bs
->device_name
));
1959 QObject
*parent
= bdrv_info_stats_bs(bs
->file
);
1960 qdict_put_obj(dict
, "parent", parent
);
1966 void bdrv_info_stats(Monitor
*mon
, QObject
**ret_data
)
1970 BlockDriverState
*bs
;
1972 devices
= qlist_new();
1974 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1975 obj
= bdrv_info_stats_bs(bs
);
1976 qlist_append_obj(devices
, obj
);
1979 *ret_data
= QOBJECT(devices
);
1982 const char *bdrv_get_encrypted_filename(BlockDriverState
*bs
)
1984 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1985 return bs
->backing_file
;
1986 else if (bs
->encrypted
)
1987 return bs
->filename
;
1992 void bdrv_get_backing_filename(BlockDriverState
*bs
,
1993 char *filename
, int filename_size
)
1995 if (!bs
->backing_file
) {
1996 pstrcpy(filename
, filename_size
, "");
1998 pstrcpy(filename
, filename_size
, bs
->backing_file
);
2002 int bdrv_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
2003 const uint8_t *buf
, int nb_sectors
)
2005 BlockDriver
*drv
= bs
->drv
;
2008 if (!drv
->bdrv_write_compressed
)
2010 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2013 if (bs
->dirty_bitmap
) {
2014 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
2017 return drv
->bdrv_write_compressed(bs
, sector_num
, buf
, nb_sectors
);
2020 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2022 BlockDriver
*drv
= bs
->drv
;
2025 if (!drv
->bdrv_get_info
)
2027 memset(bdi
, 0, sizeof(*bdi
));
2028 return drv
->bdrv_get_info(bs
, bdi
);
2031 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2032 int64_t pos
, int size
)
2034 BlockDriver
*drv
= bs
->drv
;
2037 if (drv
->bdrv_save_vmstate
)
2038 return drv
->bdrv_save_vmstate(bs
, buf
, pos
, size
);
2040 return bdrv_save_vmstate(bs
->file
, buf
, pos
, size
);
2044 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2045 int64_t pos
, int size
)
2047 BlockDriver
*drv
= bs
->drv
;
2050 if (drv
->bdrv_load_vmstate
)
2051 return drv
->bdrv_load_vmstate(bs
, buf
, pos
, size
);
2053 return bdrv_load_vmstate(bs
->file
, buf
, pos
, size
);
2057 void bdrv_debug_event(BlockDriverState
*bs
, BlkDebugEvent event
)
2059 BlockDriver
*drv
= bs
->drv
;
2061 if (!drv
|| !drv
->bdrv_debug_event
) {
2065 return drv
->bdrv_debug_event(bs
, event
);
2069 /**************************************************************/
2070 /* handling of snapshots */
2072 int bdrv_can_snapshot(BlockDriverState
*bs
)
2074 BlockDriver
*drv
= bs
->drv
;
2075 if (!drv
|| bdrv_is_removable(bs
) || bdrv_is_read_only(bs
)) {
2079 if (!drv
->bdrv_snapshot_create
) {
2080 if (bs
->file
!= NULL
) {
2081 return bdrv_can_snapshot(bs
->file
);
2089 int bdrv_is_snapshot(BlockDriverState
*bs
)
2091 return !!(bs
->open_flags
& BDRV_O_SNAPSHOT
);
2094 BlockDriverState
*bdrv_snapshots(void)
2096 BlockDriverState
*bs
;
2099 return bs_snapshots
;
2103 while ((bs
= bdrv_next(bs
))) {
2104 if (bdrv_can_snapshot(bs
)) {
2112 int bdrv_snapshot_create(BlockDriverState
*bs
,
2113 QEMUSnapshotInfo
*sn_info
)
2115 BlockDriver
*drv
= bs
->drv
;
2118 if (drv
->bdrv_snapshot_create
)
2119 return drv
->bdrv_snapshot_create(bs
, sn_info
);
2121 return bdrv_snapshot_create(bs
->file
, sn_info
);
2125 int bdrv_snapshot_goto(BlockDriverState
*bs
,
2126 const char *snapshot_id
)
2128 BlockDriver
*drv
= bs
->drv
;
2133 if (drv
->bdrv_snapshot_goto
)
2134 return drv
->bdrv_snapshot_goto(bs
, snapshot_id
);
2137 drv
->bdrv_close(bs
);
2138 ret
= bdrv_snapshot_goto(bs
->file
, snapshot_id
);
2139 open_ret
= drv
->bdrv_open(bs
, bs
->open_flags
);
2141 bdrv_delete(bs
->file
);
2151 int bdrv_snapshot_delete(BlockDriverState
*bs
, const char *snapshot_id
)
2153 BlockDriver
*drv
= bs
->drv
;
2156 if (drv
->bdrv_snapshot_delete
)
2157 return drv
->bdrv_snapshot_delete(bs
, snapshot_id
);
2159 return bdrv_snapshot_delete(bs
->file
, snapshot_id
);
2163 int bdrv_snapshot_list(BlockDriverState
*bs
,
2164 QEMUSnapshotInfo
**psn_info
)
2166 BlockDriver
*drv
= bs
->drv
;
2169 if (drv
->bdrv_snapshot_list
)
2170 return drv
->bdrv_snapshot_list(bs
, psn_info
);
2172 return bdrv_snapshot_list(bs
->file
, psn_info
);
2176 int bdrv_snapshot_load_tmp(BlockDriverState
*bs
,
2177 const char *snapshot_name
)
2179 BlockDriver
*drv
= bs
->drv
;
2183 if (!bs
->read_only
) {
2186 if (drv
->bdrv_snapshot_load_tmp
) {
2187 return drv
->bdrv_snapshot_load_tmp(bs
, snapshot_name
);
2192 #define NB_SUFFIXES 4
2194 char *get_human_readable_size(char *buf
, int buf_size
, int64_t size
)
2196 static const char suffixes
[NB_SUFFIXES
] = "KMGT";
2201 snprintf(buf
, buf_size
, "%" PRId64
, size
);
2204 for(i
= 0; i
< NB_SUFFIXES
; i
++) {
2205 if (size
< (10 * base
)) {
2206 snprintf(buf
, buf_size
, "%0.1f%c",
2207 (double)size
/ base
,
2210 } else if (size
< (1000 * base
) || i
== (NB_SUFFIXES
- 1)) {
2211 snprintf(buf
, buf_size
, "%" PRId64
"%c",
2212 ((size
+ (base
>> 1)) / base
),
2222 char *bdrv_snapshot_dump(char *buf
, int buf_size
, QEMUSnapshotInfo
*sn
)
2224 char buf1
[128], date_buf
[128], clock_buf
[128];
2234 snprintf(buf
, buf_size
,
2235 "%-10s%-20s%7s%20s%15s",
2236 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2240 ptm
= localtime(&ti
);
2241 strftime(date_buf
, sizeof(date_buf
),
2242 "%Y-%m-%d %H:%M:%S", ptm
);
2244 localtime_r(&ti
, &tm
);
2245 strftime(date_buf
, sizeof(date_buf
),
2246 "%Y-%m-%d %H:%M:%S", &tm
);
2248 secs
= sn
->vm_clock_nsec
/ 1000000000;
2249 snprintf(clock_buf
, sizeof(clock_buf
),
2250 "%02d:%02d:%02d.%03d",
2252 (int)((secs
/ 60) % 60),
2254 (int)((sn
->vm_clock_nsec
/ 1000000) % 1000));
2255 snprintf(buf
, buf_size
,
2256 "%-10s%-20s%7s%20s%15s",
2257 sn
->id_str
, sn
->name
,
2258 get_human_readable_size(buf1
, sizeof(buf1
), sn
->vm_state_size
),
2266 /**************************************************************/
2269 BlockDriverAIOCB
*bdrv_aio_readv(BlockDriverState
*bs
, int64_t sector_num
,
2270 QEMUIOVector
*qiov
, int nb_sectors
,
2271 BlockDriverCompletionFunc
*cb
, void *opaque
)
2273 BlockDriver
*drv
= bs
->drv
;
2274 BlockDriverAIOCB
*ret
;
2276 trace_bdrv_aio_readv(bs
, sector_num
, nb_sectors
, opaque
);
2280 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2283 ret
= drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
2287 /* Update stats even though technically transfer has not happened. */
2288 bs
->rd_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
2295 typedef struct BlockCompleteData
{
2296 BlockDriverCompletionFunc
*cb
;
2298 BlockDriverState
*bs
;
2301 } BlockCompleteData
;
2303 static void block_complete_cb(void *opaque
, int ret
)
2305 BlockCompleteData
*b
= opaque
;
2307 if (b
->bs
->dirty_bitmap
) {
2308 set_dirty_bitmap(b
->bs
, b
->sector_num
, b
->nb_sectors
, 1);
2310 b
->cb(b
->opaque
, ret
);
2314 static BlockCompleteData
*blk_dirty_cb_alloc(BlockDriverState
*bs
,
2317 BlockDriverCompletionFunc
*cb
,
2320 BlockCompleteData
*blkdata
= g_malloc0(sizeof(BlockCompleteData
));
2324 blkdata
->opaque
= opaque
;
2325 blkdata
->sector_num
= sector_num
;
2326 blkdata
->nb_sectors
= nb_sectors
;
2331 BlockDriverAIOCB
*bdrv_aio_writev(BlockDriverState
*bs
, int64_t sector_num
,
2332 QEMUIOVector
*qiov
, int nb_sectors
,
2333 BlockDriverCompletionFunc
*cb
, void *opaque
)
2335 BlockDriver
*drv
= bs
->drv
;
2336 BlockDriverAIOCB
*ret
;
2337 BlockCompleteData
*blk_cb_data
;
2339 trace_bdrv_aio_writev(bs
, sector_num
, nb_sectors
, opaque
);
2345 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2348 if (bs
->dirty_bitmap
) {
2349 blk_cb_data
= blk_dirty_cb_alloc(bs
, sector_num
, nb_sectors
, cb
,
2351 cb
= &block_complete_cb
;
2352 opaque
= blk_cb_data
;
2355 ret
= drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
2359 /* Update stats even though technically transfer has not happened. */
2360 bs
->wr_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
2362 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
2363 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
2371 typedef struct MultiwriteCB
{
2376 BlockDriverCompletionFunc
*cb
;
2378 QEMUIOVector
*free_qiov
;
2383 static void multiwrite_user_cb(MultiwriteCB
*mcb
)
2387 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2388 mcb
->callbacks
[i
].cb(mcb
->callbacks
[i
].opaque
, mcb
->error
);
2389 if (mcb
->callbacks
[i
].free_qiov
) {
2390 qemu_iovec_destroy(mcb
->callbacks
[i
].free_qiov
);
2392 g_free(mcb
->callbacks
[i
].free_qiov
);
2393 qemu_vfree(mcb
->callbacks
[i
].free_buf
);
2397 static void multiwrite_cb(void *opaque
, int ret
)
2399 MultiwriteCB
*mcb
= opaque
;
2401 trace_multiwrite_cb(mcb
, ret
);
2403 if (ret
< 0 && !mcb
->error
) {
2407 mcb
->num_requests
--;
2408 if (mcb
->num_requests
== 0) {
2409 multiwrite_user_cb(mcb
);
2414 static int multiwrite_req_compare(const void *a
, const void *b
)
2416 const BlockRequest
*req1
= a
, *req2
= b
;
2419 * Note that we can't simply subtract req2->sector from req1->sector
2420 * here as that could overflow the return value.
2422 if (req1
->sector
> req2
->sector
) {
2424 } else if (req1
->sector
< req2
->sector
) {
2432 * Takes a bunch of requests and tries to merge them. Returns the number of
2433 * requests that remain after merging.
2435 static int multiwrite_merge(BlockDriverState
*bs
, BlockRequest
*reqs
,
2436 int num_reqs
, MultiwriteCB
*mcb
)
2440 // Sort requests by start sector
2441 qsort(reqs
, num_reqs
, sizeof(*reqs
), &multiwrite_req_compare
);
2443 // Check if adjacent requests touch the same clusters. If so, combine them,
2444 // filling up gaps with zero sectors.
2446 for (i
= 1; i
< num_reqs
; i
++) {
2448 int64_t oldreq_last
= reqs
[outidx
].sector
+ reqs
[outidx
].nb_sectors
;
2450 // This handles the cases that are valid for all block drivers, namely
2451 // exactly sequential writes and overlapping writes.
2452 if (reqs
[i
].sector
<= oldreq_last
) {
2456 // The block driver may decide that it makes sense to combine requests
2457 // even if there is a gap of some sectors between them. In this case,
2458 // the gap is filled with zeros (therefore only applicable for yet
2459 // unused space in format like qcow2).
2460 if (!merge
&& bs
->drv
->bdrv_merge_requests
) {
2461 merge
= bs
->drv
->bdrv_merge_requests(bs
, &reqs
[outidx
], &reqs
[i
]);
2464 if (reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1 > IOV_MAX
) {
2470 QEMUIOVector
*qiov
= g_malloc0(sizeof(*qiov
));
2471 qemu_iovec_init(qiov
,
2472 reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1);
2474 // Add the first request to the merged one. If the requests are
2475 // overlapping, drop the last sectors of the first request.
2476 size
= (reqs
[i
].sector
- reqs
[outidx
].sector
) << 9;
2477 qemu_iovec_concat(qiov
, reqs
[outidx
].qiov
, size
);
2479 // We might need to add some zeros between the two requests
2480 if (reqs
[i
].sector
> oldreq_last
) {
2481 size_t zero_bytes
= (reqs
[i
].sector
- oldreq_last
) << 9;
2482 uint8_t *buf
= qemu_blockalign(bs
, zero_bytes
);
2483 memset(buf
, 0, zero_bytes
);
2484 qemu_iovec_add(qiov
, buf
, zero_bytes
);
2485 mcb
->callbacks
[i
].free_buf
= buf
;
2488 // Add the second request
2489 qemu_iovec_concat(qiov
, reqs
[i
].qiov
, reqs
[i
].qiov
->size
);
2491 reqs
[outidx
].nb_sectors
= qiov
->size
>> 9;
2492 reqs
[outidx
].qiov
= qiov
;
2494 mcb
->callbacks
[i
].free_qiov
= reqs
[outidx
].qiov
;
2497 reqs
[outidx
].sector
= reqs
[i
].sector
;
2498 reqs
[outidx
].nb_sectors
= reqs
[i
].nb_sectors
;
2499 reqs
[outidx
].qiov
= reqs
[i
].qiov
;
2507 * Submit multiple AIO write requests at once.
2509 * On success, the function returns 0 and all requests in the reqs array have
2510 * been submitted. In error case this function returns -1, and any of the
2511 * requests may or may not be submitted yet. In particular, this means that the
2512 * callback will be called for some of the requests, for others it won't. The
2513 * caller must check the error field of the BlockRequest to wait for the right
2514 * callbacks (if error != 0, no callback will be called).
2516 * The implementation may modify the contents of the reqs array, e.g. to merge
2517 * requests. However, the fields opaque and error are left unmodified as they
2518 * are used to signal failure for a single request to the caller.
2520 int bdrv_aio_multiwrite(BlockDriverState
*bs
, BlockRequest
*reqs
, int num_reqs
)
2522 BlockDriverAIOCB
*acb
;
2526 /* don't submit writes if we don't have a medium */
2527 if (bs
->drv
== NULL
) {
2528 for (i
= 0; i
< num_reqs
; i
++) {
2529 reqs
[i
].error
= -ENOMEDIUM
;
2534 if (num_reqs
== 0) {
2538 // Create MultiwriteCB structure
2539 mcb
= g_malloc0(sizeof(*mcb
) + num_reqs
* sizeof(*mcb
->callbacks
));
2540 mcb
->num_requests
= 0;
2541 mcb
->num_callbacks
= num_reqs
;
2543 for (i
= 0; i
< num_reqs
; i
++) {
2544 mcb
->callbacks
[i
].cb
= reqs
[i
].cb
;
2545 mcb
->callbacks
[i
].opaque
= reqs
[i
].opaque
;
2548 // Check for mergable requests
2549 num_reqs
= multiwrite_merge(bs
, reqs
, num_reqs
, mcb
);
2551 trace_bdrv_aio_multiwrite(mcb
, mcb
->num_callbacks
, num_reqs
);
2554 * Run the aio requests. As soon as one request can't be submitted
2555 * successfully, fail all requests that are not yet submitted (we must
2556 * return failure for all requests anyway)
2558 * num_requests cannot be set to the right value immediately: If
2559 * bdrv_aio_writev fails for some request, num_requests would be too high
2560 * and therefore multiwrite_cb() would never recognize the multiwrite
2561 * request as completed. We also cannot use the loop variable i to set it
2562 * when the first request fails because the callback may already have been
2563 * called for previously submitted requests. Thus, num_requests must be
2564 * incremented for each request that is submitted.
2566 * The problem that callbacks may be called early also means that we need
2567 * to take care that num_requests doesn't become 0 before all requests are
2568 * submitted - multiwrite_cb() would consider the multiwrite request
2569 * completed. A dummy request that is "completed" by a manual call to
2570 * multiwrite_cb() takes care of this.
2572 mcb
->num_requests
= 1;
2574 // Run the aio requests
2575 for (i
= 0; i
< num_reqs
; i
++) {
2576 mcb
->num_requests
++;
2577 acb
= bdrv_aio_writev(bs
, reqs
[i
].sector
, reqs
[i
].qiov
,
2578 reqs
[i
].nb_sectors
, multiwrite_cb
, mcb
);
2581 // We can only fail the whole thing if no request has been
2582 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2583 // complete and report the error in the callback.
2585 trace_bdrv_aio_multiwrite_earlyfail(mcb
);
2588 trace_bdrv_aio_multiwrite_latefail(mcb
, i
);
2589 multiwrite_cb(mcb
, -EIO
);
2595 /* Complete the dummy request */
2596 multiwrite_cb(mcb
, 0);
2601 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2602 reqs
[i
].error
= -EIO
;
2608 BlockDriverAIOCB
*bdrv_aio_flush(BlockDriverState
*bs
,
2609 BlockDriverCompletionFunc
*cb
, void *opaque
)
2611 BlockDriver
*drv
= bs
->drv
;
2613 trace_bdrv_aio_flush(bs
, opaque
);
2617 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2618 return bdrv_aio_noop_em(bs
, cb
, opaque
);
2623 return drv
->bdrv_aio_flush(bs
, cb
, opaque
);
2626 void bdrv_aio_cancel(BlockDriverAIOCB
*acb
)
2628 acb
->pool
->cancel(acb
);
2632 /**************************************************************/
2633 /* async block device emulation */
2635 typedef struct BlockDriverAIOCBSync
{
2636 BlockDriverAIOCB common
;
2639 /* vector translation state */
2643 } BlockDriverAIOCBSync
;
2645 static void bdrv_aio_cancel_em(BlockDriverAIOCB
*blockacb
)
2647 BlockDriverAIOCBSync
*acb
=
2648 container_of(blockacb
, BlockDriverAIOCBSync
, common
);
2649 qemu_bh_delete(acb
->bh
);
2651 qemu_aio_release(acb
);
2654 static AIOPool bdrv_em_aio_pool
= {
2655 .aiocb_size
= sizeof(BlockDriverAIOCBSync
),
2656 .cancel
= bdrv_aio_cancel_em
,
2659 static void bdrv_aio_bh_cb(void *opaque
)
2661 BlockDriverAIOCBSync
*acb
= opaque
;
2664 qemu_iovec_from_buffer(acb
->qiov
, acb
->bounce
, acb
->qiov
->size
);
2665 qemu_vfree(acb
->bounce
);
2666 acb
->common
.cb(acb
->common
.opaque
, acb
->ret
);
2667 qemu_bh_delete(acb
->bh
);
2669 qemu_aio_release(acb
);
2672 static BlockDriverAIOCB
*bdrv_aio_rw_vector(BlockDriverState
*bs
,
2676 BlockDriverCompletionFunc
*cb
,
2681 BlockDriverAIOCBSync
*acb
;
2683 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2684 acb
->is_write
= is_write
;
2686 acb
->bounce
= qemu_blockalign(bs
, qiov
->size
);
2689 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2692 qemu_iovec_to_buffer(acb
->qiov
, acb
->bounce
);
2693 acb
->ret
= bdrv_write(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2695 acb
->ret
= bdrv_read(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2698 qemu_bh_schedule(acb
->bh
);
2700 return &acb
->common
;
2703 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
2704 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2705 BlockDriverCompletionFunc
*cb
, void *opaque
)
2707 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 0);
2710 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
2711 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2712 BlockDriverCompletionFunc
*cb
, void *opaque
)
2714 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 1);
2718 typedef struct BlockDriverAIOCBCoroutine
{
2719 BlockDriverAIOCB common
;
2723 } BlockDriverAIOCBCoroutine
;
2725 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB
*blockacb
)
2730 static AIOPool bdrv_em_co_aio_pool
= {
2731 .aiocb_size
= sizeof(BlockDriverAIOCBCoroutine
),
2732 .cancel
= bdrv_aio_co_cancel_em
,
2735 static void bdrv_co_rw_bh(void *opaque
)
2737 BlockDriverAIOCBCoroutine
*acb
= opaque
;
2739 acb
->common
.cb(acb
->common
.opaque
, acb
->req
.error
);
2740 qemu_bh_delete(acb
->bh
);
2741 qemu_aio_release(acb
);
2744 static void coroutine_fn
bdrv_co_rw(void *opaque
)
2746 BlockDriverAIOCBCoroutine
*acb
= opaque
;
2747 BlockDriverState
*bs
= acb
->common
.bs
;
2749 if (!acb
->is_write
) {
2750 acb
->req
.error
= bs
->drv
->bdrv_co_readv(bs
, acb
->req
.sector
,
2751 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2753 acb
->req
.error
= bs
->drv
->bdrv_co_writev(bs
, acb
->req
.sector
,
2754 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2757 acb
->bh
= qemu_bh_new(bdrv_co_rw_bh
, acb
);
2758 qemu_bh_schedule(acb
->bh
);
2761 static BlockDriverAIOCB
*bdrv_co_aio_rw_vector(BlockDriverState
*bs
,
2765 BlockDriverCompletionFunc
*cb
,
2770 BlockDriverAIOCBCoroutine
*acb
;
2772 acb
= qemu_aio_get(&bdrv_em_co_aio_pool
, bs
, cb
, opaque
);
2773 acb
->req
.sector
= sector_num
;
2774 acb
->req
.nb_sectors
= nb_sectors
;
2775 acb
->req
.qiov
= qiov
;
2776 acb
->is_write
= is_write
;
2778 co
= qemu_coroutine_create(bdrv_co_rw
);
2779 qemu_coroutine_enter(co
, acb
);
2781 return &acb
->common
;
2784 static BlockDriverAIOCB
*bdrv_co_aio_readv_em(BlockDriverState
*bs
,
2785 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2786 BlockDriverCompletionFunc
*cb
, void *opaque
)
2788 return bdrv_co_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
,
2792 static BlockDriverAIOCB
*bdrv_co_aio_writev_em(BlockDriverState
*bs
,
2793 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2794 BlockDriverCompletionFunc
*cb
, void *opaque
)
2796 return bdrv_co_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
,
2800 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
2801 BlockDriverCompletionFunc
*cb
, void *opaque
)
2803 BlockDriverAIOCBSync
*acb
;
2805 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2806 acb
->is_write
= 1; /* don't bounce in the completion hadler */
2812 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2815 qemu_bh_schedule(acb
->bh
);
2816 return &acb
->common
;
2819 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
2820 BlockDriverCompletionFunc
*cb
, void *opaque
)
2822 BlockDriverAIOCBSync
*acb
;
2824 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2825 acb
->is_write
= 1; /* don't bounce in the completion handler */
2831 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2834 qemu_bh_schedule(acb
->bh
);
2835 return &acb
->common
;
2838 /**************************************************************/
2839 /* sync block device emulation */
2841 static void bdrv_rw_em_cb(void *opaque
, int ret
)
2843 *(int *)opaque
= ret
;
2846 #define NOT_DONE 0x7fffffff
2848 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
2849 uint8_t *buf
, int nb_sectors
)
2852 BlockDriverAIOCB
*acb
;
2856 async_ret
= NOT_DONE
;
2857 iov
.iov_base
= (void *)buf
;
2858 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2859 qemu_iovec_init_external(&qiov
, &iov
, 1);
2860 acb
= bdrv_aio_readv(bs
, sector_num
, &qiov
, nb_sectors
,
2861 bdrv_rw_em_cb
, &async_ret
);
2867 while (async_ret
== NOT_DONE
) {
2876 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
2877 const uint8_t *buf
, int nb_sectors
)
2880 BlockDriverAIOCB
*acb
;
2884 async_ret
= NOT_DONE
;
2885 iov
.iov_base
= (void *)buf
;
2886 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2887 qemu_iovec_init_external(&qiov
, &iov
, 1);
2888 acb
= bdrv_aio_writev(bs
, sector_num
, &qiov
, nb_sectors
,
2889 bdrv_rw_em_cb
, &async_ret
);
2894 while (async_ret
== NOT_DONE
) {
2902 void bdrv_init(void)
2904 module_call_init(MODULE_INIT_BLOCK
);
2907 void bdrv_init_with_whitelist(void)
2909 use_bdrv_whitelist
= 1;
2913 void *qemu_aio_get(AIOPool
*pool
, BlockDriverState
*bs
,
2914 BlockDriverCompletionFunc
*cb
, void *opaque
)
2916 BlockDriverAIOCB
*acb
;
2918 if (pool
->free_aiocb
) {
2919 acb
= pool
->free_aiocb
;
2920 pool
->free_aiocb
= acb
->next
;
2922 acb
= g_malloc0(pool
->aiocb_size
);
2927 acb
->opaque
= opaque
;
2931 void qemu_aio_release(void *p
)
2933 BlockDriverAIOCB
*acb
= (BlockDriverAIOCB
*)p
;
2934 AIOPool
*pool
= acb
->pool
;
2935 acb
->next
= pool
->free_aiocb
;
2936 pool
->free_aiocb
= acb
;
2939 /**************************************************************/
2940 /* Coroutine block device emulation */
2942 typedef struct CoroutineIOCompletion
{
2943 Coroutine
*coroutine
;
2945 } CoroutineIOCompletion
;
2947 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
2949 CoroutineIOCompletion
*co
= opaque
;
2952 qemu_coroutine_enter(co
->coroutine
, NULL
);
2955 static int coroutine_fn
bdrv_co_io_em(BlockDriverState
*bs
, int64_t sector_num
,
2956 int nb_sectors
, QEMUIOVector
*iov
,
2959 CoroutineIOCompletion co
= {
2960 .coroutine
= qemu_coroutine_self(),
2962 BlockDriverAIOCB
*acb
;
2965 acb
= bdrv_aio_writev(bs
, sector_num
, iov
, nb_sectors
,
2966 bdrv_co_io_em_complete
, &co
);
2968 acb
= bdrv_aio_readv(bs
, sector_num
, iov
, nb_sectors
,
2969 bdrv_co_io_em_complete
, &co
);
2972 trace_bdrv_co_io(is_write
, acb
);
2976 qemu_coroutine_yield();
2981 static int coroutine_fn
bdrv_co_readv_em(BlockDriverState
*bs
,
2982 int64_t sector_num
, int nb_sectors
,
2985 return bdrv_co_io_em(bs
, sector_num
, nb_sectors
, iov
, false);
2988 static int coroutine_fn
bdrv_co_writev_em(BlockDriverState
*bs
,
2989 int64_t sector_num
, int nb_sectors
,
2992 return bdrv_co_io_em(bs
, sector_num
, nb_sectors
, iov
, true);
2995 static int coroutine_fn
bdrv_co_flush_em(BlockDriverState
*bs
)
2997 CoroutineIOCompletion co
= {
2998 .coroutine
= qemu_coroutine_self(),
3000 BlockDriverAIOCB
*acb
;
3002 acb
= bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
3006 qemu_coroutine_yield();
3010 /**************************************************************/
3011 /* removable device support */
3014 * Return TRUE if the media is present
3016 int bdrv_is_inserted(BlockDriverState
*bs
)
3018 BlockDriver
*drv
= bs
->drv
;
3022 if (!drv
->bdrv_is_inserted
)
3023 return !bs
->tray_open
;
3024 ret
= drv
->bdrv_is_inserted(bs
);
3029 * Return TRUE if the media changed since the last call to this
3030 * function. It is currently only used for floppy disks
3032 int bdrv_media_changed(BlockDriverState
*bs
)
3034 BlockDriver
*drv
= bs
->drv
;
3037 if (!drv
|| !drv
->bdrv_media_changed
)
3040 ret
= drv
->bdrv_media_changed(bs
);
3041 if (ret
== -ENOTSUP
)
3042 ret
= bs
->media_changed
;
3043 bs
->media_changed
= 0;
3048 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3050 int bdrv_eject(BlockDriverState
*bs
, int eject_flag
)
3052 BlockDriver
*drv
= bs
->drv
;
3054 if (eject_flag
&& bs
->locked
) {
3058 if (drv
&& drv
->bdrv_eject
) {
3059 drv
->bdrv_eject(bs
, eject_flag
);
3061 bs
->tray_open
= eject_flag
;
3065 int bdrv_is_locked(BlockDriverState
*bs
)
3071 * Lock or unlock the media (if it is locked, the user won't be able
3072 * to eject it manually).
3074 void bdrv_set_locked(BlockDriverState
*bs
, int locked
)
3076 BlockDriver
*drv
= bs
->drv
;
3078 trace_bdrv_set_locked(bs
, locked
);
3080 bs
->locked
= locked
;
3081 if (drv
&& drv
->bdrv_set_locked
) {
3082 drv
->bdrv_set_locked(bs
, locked
);
3086 /* needed for generic scsi interface */
3088 int bdrv_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
3090 BlockDriver
*drv
= bs
->drv
;
3092 if (drv
&& drv
->bdrv_ioctl
)
3093 return drv
->bdrv_ioctl(bs
, req
, buf
);
3097 BlockDriverAIOCB
*bdrv_aio_ioctl(BlockDriverState
*bs
,
3098 unsigned long int req
, void *buf
,
3099 BlockDriverCompletionFunc
*cb
, void *opaque
)
3101 BlockDriver
*drv
= bs
->drv
;
3103 if (drv
&& drv
->bdrv_aio_ioctl
)
3104 return drv
->bdrv_aio_ioctl(bs
, req
, buf
, cb
, opaque
);
3110 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
3112 return qemu_memalign((bs
&& bs
->buffer_alignment
) ? bs
->buffer_alignment
: 512, size
);
3115 void bdrv_set_dirty_tracking(BlockDriverState
*bs
, int enable
)
3117 int64_t bitmap_size
;
3119 bs
->dirty_count
= 0;
3121 if (!bs
->dirty_bitmap
) {
3122 bitmap_size
= (bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
) +
3123 BDRV_SECTORS_PER_DIRTY_CHUNK
* 8 - 1;
3124 bitmap_size
/= BDRV_SECTORS_PER_DIRTY_CHUNK
* 8;
3126 bs
->dirty_bitmap
= g_malloc0(bitmap_size
);
3129 if (bs
->dirty_bitmap
) {
3130 g_free(bs
->dirty_bitmap
);
3131 bs
->dirty_bitmap
= NULL
;
3136 int bdrv_get_dirty(BlockDriverState
*bs
, int64_t sector
)
3138 int64_t chunk
= sector
/ (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK
;
3140 if (bs
->dirty_bitmap
&&
3141 (sector
<< BDRV_SECTOR_BITS
) < bdrv_getlength(bs
)) {
3142 return !!(bs
->dirty_bitmap
[chunk
/ (sizeof(unsigned long) * 8)] &
3143 (1UL << (chunk
% (sizeof(unsigned long) * 8))));
3149 void bdrv_reset_dirty(BlockDriverState
*bs
, int64_t cur_sector
,
3152 set_dirty_bitmap(bs
, cur_sector
, nr_sectors
, 0);
3155 int64_t bdrv_get_dirty_count(BlockDriverState
*bs
)
3157 return bs
->dirty_count
;
3160 void bdrv_set_in_use(BlockDriverState
*bs
, int in_use
)
3162 assert(bs
->in_use
!= in_use
);
3163 bs
->in_use
= in_use
;
3166 int bdrv_in_use(BlockDriverState
*bs
)
3171 int bdrv_img_create(const char *filename
, const char *fmt
,
3172 const char *base_filename
, const char *base_fmt
,
3173 char *options
, uint64_t img_size
, int flags
)
3175 QEMUOptionParameter
*param
= NULL
, *create_options
= NULL
;
3176 QEMUOptionParameter
*backing_fmt
, *backing_file
, *size
;
3177 BlockDriverState
*bs
= NULL
;
3178 BlockDriver
*drv
, *proto_drv
;
3179 BlockDriver
*backing_drv
= NULL
;
3182 /* Find driver and parse its options */
3183 drv
= bdrv_find_format(fmt
);
3185 error_report("Unknown file format '%s'", fmt
);
3190 proto_drv
= bdrv_find_protocol(filename
);
3192 error_report("Unknown protocol '%s'", filename
);
3197 create_options
= append_option_parameters(create_options
,
3198 drv
->create_options
);
3199 create_options
= append_option_parameters(create_options
,
3200 proto_drv
->create_options
);
3202 /* Create parameter list with default values */
3203 param
= parse_option_parameters("", create_options
, param
);
3205 set_option_parameter_int(param
, BLOCK_OPT_SIZE
, img_size
);
3207 /* Parse -o options */
3209 param
= parse_option_parameters(options
, create_options
, param
);
3210 if (param
== NULL
) {
3211 error_report("Invalid options for file format '%s'.", fmt
);
3217 if (base_filename
) {
3218 if (set_option_parameter(param
, BLOCK_OPT_BACKING_FILE
,
3220 error_report("Backing file not supported for file format '%s'",
3228 if (set_option_parameter(param
, BLOCK_OPT_BACKING_FMT
, base_fmt
)) {
3229 error_report("Backing file format not supported for file "
3230 "format '%s'", fmt
);
3236 backing_file
= get_option_parameter(param
, BLOCK_OPT_BACKING_FILE
);
3237 if (backing_file
&& backing_file
->value
.s
) {
3238 if (!strcmp(filename
, backing_file
->value
.s
)) {
3239 error_report("Error: Trying to create an image with the "
3240 "same filename as the backing file");
3246 backing_fmt
= get_option_parameter(param
, BLOCK_OPT_BACKING_FMT
);
3247 if (backing_fmt
&& backing_fmt
->value
.s
) {
3248 backing_drv
= bdrv_find_format(backing_fmt
->value
.s
);
3250 error_report("Unknown backing file format '%s'",
3251 backing_fmt
->value
.s
);
3257 // The size for the image must always be specified, with one exception:
3258 // If we are using a backing file, we can obtain the size from there
3259 size
= get_option_parameter(param
, BLOCK_OPT_SIZE
);
3260 if (size
&& size
->value
.n
== -1) {
3261 if (backing_file
&& backing_file
->value
.s
) {
3267 ret
= bdrv_open(bs
, backing_file
->value
.s
, flags
, backing_drv
);
3269 error_report("Could not open '%s'", backing_file
->value
.s
);
3272 bdrv_get_geometry(bs
, &size
);
3275 snprintf(buf
, sizeof(buf
), "%" PRId64
, size
);
3276 set_option_parameter(param
, BLOCK_OPT_SIZE
, buf
);
3278 error_report("Image creation needs a size parameter");
3284 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
3285 print_option_parameters(param
);
3288 ret
= bdrv_create(drv
, filename
, param
);
3291 if (ret
== -ENOTSUP
) {
3292 error_report("Formatting or formatting option not supported for "
3293 "file format '%s'", fmt
);
3294 } else if (ret
== -EFBIG
) {
3295 error_report("The image size is too large for file format '%s'",
3298 error_report("%s: error while creating %s: %s", filename
, fmt
,
3304 free_option_parameters(create_options
);
3305 free_option_parameters(param
);