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
, "writeback")) {
452 *flags
|= BDRV_O_CACHE_WB
;
453 } else if (!strcmp(mode
, "unsafe")) {
454 *flags
|= BDRV_O_CACHE_WB
;
455 *flags
|= BDRV_O_NO_FLUSH
;
456 } else if (!strcmp(mode
, "writethrough")) {
457 /* this is the default */
466 * Common part for opening disk images and files
468 static int bdrv_open_common(BlockDriverState
*bs
, const char *filename
,
469 int flags
, BlockDriver
*drv
)
476 bs
->total_sectors
= 0;
479 bs
->open_flags
= flags
;
480 /* buffer_alignment defaulted to 512, drivers can change this value */
481 bs
->buffer_alignment
= 512;
483 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
485 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
)) {
490 bs
->opaque
= g_malloc0(drv
->instance_size
);
492 if (flags
& BDRV_O_CACHE_WB
)
493 bs
->enable_write_cache
= 1;
496 * Clear flags that are internal to the block layer before opening the
499 open_flags
= flags
& ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
502 * Snapshots should be writable.
504 if (bs
->is_temporary
) {
505 open_flags
|= BDRV_O_RDWR
;
508 /* Open the image, either directly or using a protocol */
509 if (drv
->bdrv_file_open
) {
510 ret
= drv
->bdrv_file_open(bs
, filename
, open_flags
);
512 ret
= bdrv_file_open(&bs
->file
, filename
, open_flags
);
514 ret
= drv
->bdrv_open(bs
, open_flags
);
522 bs
->keep_read_only
= bs
->read_only
= !(open_flags
& BDRV_O_RDWR
);
524 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
530 if (bs
->is_temporary
) {
538 bdrv_delete(bs
->file
);
548 * Opens a file using a protocol (file, host_device, nbd, ...)
550 int bdrv_file_open(BlockDriverState
**pbs
, const char *filename
, int flags
)
552 BlockDriverState
*bs
;
556 drv
= bdrv_find_protocol(filename
);
562 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
573 * Opens a disk image (raw, qcow2, vmdk, ...)
575 int bdrv_open(BlockDriverState
*bs
, const char *filename
, int flags
,
580 if (flags
& BDRV_O_SNAPSHOT
) {
581 BlockDriverState
*bs1
;
584 BlockDriver
*bdrv_qcow2
;
585 QEMUOptionParameter
*options
;
586 char tmp_filename
[PATH_MAX
];
587 char backing_filename
[PATH_MAX
];
589 /* if snapshot, we create a temporary backing file and open it
590 instead of opening 'filename' directly */
592 /* if there is a backing file, use it */
594 ret
= bdrv_open(bs1
, filename
, 0, drv
);
599 total_size
= bdrv_getlength(bs1
) & BDRV_SECTOR_MASK
;
601 if (bs1
->drv
&& bs1
->drv
->protocol_name
)
606 get_tmp_filename(tmp_filename
, sizeof(tmp_filename
));
608 /* Real path is meaningless for protocols */
610 snprintf(backing_filename
, sizeof(backing_filename
),
612 else if (!realpath(filename
, backing_filename
))
615 bdrv_qcow2
= bdrv_find_format("qcow2");
616 options
= parse_option_parameters("", bdrv_qcow2
->create_options
, NULL
);
618 set_option_parameter_int(options
, BLOCK_OPT_SIZE
, total_size
);
619 set_option_parameter(options
, BLOCK_OPT_BACKING_FILE
, backing_filename
);
621 set_option_parameter(options
, BLOCK_OPT_BACKING_FMT
,
625 ret
= bdrv_create(bdrv_qcow2
, tmp_filename
, options
);
626 free_option_parameters(options
);
631 filename
= tmp_filename
;
633 bs
->is_temporary
= 1;
636 /* Find the right image format driver */
638 ret
= find_image_format(filename
, &drv
);
642 goto unlink_and_fail
;
646 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
648 goto unlink_and_fail
;
651 /* If there is a backing file, use it */
652 if ((flags
& BDRV_O_NO_BACKING
) == 0 && bs
->backing_file
[0] != '\0') {
653 char backing_filename
[PATH_MAX
];
655 BlockDriver
*back_drv
= NULL
;
657 bs
->backing_hd
= bdrv_new("");
659 if (path_has_protocol(bs
->backing_file
)) {
660 pstrcpy(backing_filename
, sizeof(backing_filename
),
663 path_combine(backing_filename
, sizeof(backing_filename
),
664 filename
, bs
->backing_file
);
667 if (bs
->backing_format
[0] != '\0') {
668 back_drv
= bdrv_find_format(bs
->backing_format
);
671 /* backing files always opened read-only */
673 flags
& ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
675 ret
= bdrv_open(bs
->backing_hd
, backing_filename
, back_flags
, back_drv
);
680 if (bs
->is_temporary
) {
681 bs
->backing_hd
->keep_read_only
= !(flags
& BDRV_O_RDWR
);
683 /* base image inherits from "parent" */
684 bs
->backing_hd
->keep_read_only
= bs
->keep_read_only
;
688 if (!bdrv_key_required(bs
)) {
689 /* call the change callback */
690 bs
->media_changed
= 1;
692 bs
->change_cb(bs
->change_opaque
, CHANGE_MEDIA
);
698 if (bs
->is_temporary
) {
704 void bdrv_close(BlockDriverState
*bs
)
707 if (bs
== bs_snapshots
) {
710 if (bs
->backing_hd
) {
711 bdrv_delete(bs
->backing_hd
);
712 bs
->backing_hd
= NULL
;
714 bs
->drv
->bdrv_close(bs
);
717 if (bs
->is_temporary
) {
718 unlink(bs
->filename
);
724 if (bs
->file
!= NULL
) {
725 bdrv_close(bs
->file
);
728 /* call the change callback */
729 bs
->media_changed
= 1;
731 bs
->change_cb(bs
->change_opaque
, CHANGE_MEDIA
);
735 void bdrv_close_all(void)
737 BlockDriverState
*bs
;
739 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
744 /* make a BlockDriverState anonymous by removing from bdrv_state list.
745 Also, NULL terminate the device_name to prevent double remove */
746 void bdrv_make_anon(BlockDriverState
*bs
)
748 if (bs
->device_name
[0] != '\0') {
749 QTAILQ_REMOVE(&bdrv_states
, bs
, list
);
751 bs
->device_name
[0] = '\0';
754 void bdrv_delete(BlockDriverState
*bs
)
758 /* remove from list, if necessary */
762 if (bs
->file
!= NULL
) {
763 bdrv_delete(bs
->file
);
766 assert(bs
!= bs_snapshots
);
770 int bdrv_attach(BlockDriverState
*bs
, DeviceState
*qdev
)
779 void bdrv_detach(BlockDriverState
*bs
, DeviceState
*qdev
)
781 assert(bs
->peer
== qdev
);
783 bs
->change_cb
= NULL
;
784 bs
->change_opaque
= NULL
;
787 DeviceState
*bdrv_get_attached(BlockDriverState
*bs
)
793 * Run consistency checks on an image
795 * Returns 0 if the check could be completed (it doesn't mean that the image is
796 * free of errors) or -errno when an internal error occurred. The results of the
797 * check are stored in res.
799 int bdrv_check(BlockDriverState
*bs
, BdrvCheckResult
*res
)
801 if (bs
->drv
->bdrv_check
== NULL
) {
805 memset(res
, 0, sizeof(*res
));
806 return bs
->drv
->bdrv_check(bs
, res
);
809 #define COMMIT_BUF_SECTORS 2048
811 /* commit COW file into the raw image */
812 int bdrv_commit(BlockDriverState
*bs
)
814 BlockDriver
*drv
= bs
->drv
;
815 BlockDriver
*backing_drv
;
816 int64_t sector
, total_sectors
;
817 int n
, ro
, open_flags
;
818 int ret
= 0, rw_ret
= 0;
821 BlockDriverState
*bs_rw
, *bs_ro
;
826 if (!bs
->backing_hd
) {
830 if (bs
->backing_hd
->keep_read_only
) {
834 backing_drv
= bs
->backing_hd
->drv
;
835 ro
= bs
->backing_hd
->read_only
;
836 strncpy(filename
, bs
->backing_hd
->filename
, sizeof(filename
));
837 open_flags
= bs
->backing_hd
->open_flags
;
841 bdrv_delete(bs
->backing_hd
);
842 bs
->backing_hd
= NULL
;
843 bs_rw
= bdrv_new("");
844 rw_ret
= bdrv_open(bs_rw
, filename
, open_flags
| BDRV_O_RDWR
,
848 /* try to re-open read-only */
849 bs_ro
= bdrv_new("");
850 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
,
854 /* drive not functional anymore */
858 bs
->backing_hd
= bs_ro
;
861 bs
->backing_hd
= bs_rw
;
864 total_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
865 buf
= g_malloc(COMMIT_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
867 for (sector
= 0; sector
< total_sectors
; sector
+= n
) {
868 if (drv
->bdrv_is_allocated(bs
, sector
, COMMIT_BUF_SECTORS
, &n
)) {
870 if (bdrv_read(bs
, sector
, buf
, n
) != 0) {
875 if (bdrv_write(bs
->backing_hd
, sector
, buf
, n
) != 0) {
882 if (drv
->bdrv_make_empty
) {
883 ret
= drv
->bdrv_make_empty(bs
);
888 * Make sure all data we wrote to the backing device is actually
892 bdrv_flush(bs
->backing_hd
);
899 bdrv_delete(bs
->backing_hd
);
900 bs
->backing_hd
= NULL
;
901 bs_ro
= bdrv_new("");
902 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
,
906 /* drive not functional anymore */
910 bs
->backing_hd
= bs_ro
;
911 bs
->backing_hd
->keep_read_only
= 0;
917 void bdrv_commit_all(void)
919 BlockDriverState
*bs
;
921 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
929 * -EINVAL - backing format specified, but no file
930 * -ENOSPC - can't update the backing file because no space is left in the
932 * -ENOTSUP - format driver doesn't support changing the backing file
934 int bdrv_change_backing_file(BlockDriverState
*bs
,
935 const char *backing_file
, const char *backing_fmt
)
937 BlockDriver
*drv
= bs
->drv
;
939 if (drv
->bdrv_change_backing_file
!= NULL
) {
940 return drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
946 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
951 if (!bdrv_is_inserted(bs
))
957 len
= bdrv_getlength(bs
);
962 if ((offset
> len
) || (len
- offset
< size
))
968 static int bdrv_check_request(BlockDriverState
*bs
, int64_t sector_num
,
971 return bdrv_check_byte_request(bs
, sector_num
* BDRV_SECTOR_SIZE
,
972 nb_sectors
* BDRV_SECTOR_SIZE
);
975 static inline bool bdrv_has_async_rw(BlockDriver
*drv
)
977 return drv
->bdrv_co_readv
!= bdrv_co_readv_em
978 || drv
->bdrv_aio_readv
!= bdrv_aio_readv_em
;
981 static inline bool bdrv_has_async_flush(BlockDriver
*drv
)
983 return drv
->bdrv_aio_flush
!= bdrv_aio_flush_em
;
986 /* return < 0 if error. See bdrv_write() for the return codes */
987 int bdrv_read(BlockDriverState
*bs
, int64_t sector_num
,
988 uint8_t *buf
, int nb_sectors
)
990 BlockDriver
*drv
= bs
->drv
;
995 if (bdrv_has_async_rw(drv
) && qemu_in_coroutine()) {
998 .iov_base
= (void *)buf
,
999 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
1002 qemu_iovec_init_external(&qiov
, &iov
, 1);
1003 return bdrv_co_readv(bs
, sector_num
, nb_sectors
, &qiov
);
1006 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1009 return drv
->bdrv_read(bs
, sector_num
, buf
, nb_sectors
);
1012 static void set_dirty_bitmap(BlockDriverState
*bs
, int64_t sector_num
,
1013 int nb_sectors
, int dirty
)
1016 unsigned long val
, idx
, bit
;
1018 start
= sector_num
/ BDRV_SECTORS_PER_DIRTY_CHUNK
;
1019 end
= (sector_num
+ nb_sectors
- 1) / BDRV_SECTORS_PER_DIRTY_CHUNK
;
1021 for (; start
<= end
; start
++) {
1022 idx
= start
/ (sizeof(unsigned long) * 8);
1023 bit
= start
% (sizeof(unsigned long) * 8);
1024 val
= bs
->dirty_bitmap
[idx
];
1026 if (!(val
& (1UL << bit
))) {
1031 if (val
& (1UL << bit
)) {
1033 val
&= ~(1UL << bit
);
1036 bs
->dirty_bitmap
[idx
] = val
;
1040 /* Return < 0 if error. Important errors are:
1041 -EIO generic I/O error (may happen for all errors)
1042 -ENOMEDIUM No media inserted.
1043 -EINVAL Invalid sector number or nb_sectors
1044 -EACCES Trying to write a read-only device
1046 int bdrv_write(BlockDriverState
*bs
, int64_t sector_num
,
1047 const uint8_t *buf
, int nb_sectors
)
1049 BlockDriver
*drv
= bs
->drv
;
1054 if (bdrv_has_async_rw(drv
) && qemu_in_coroutine()) {
1056 struct iovec iov
= {
1057 .iov_base
= (void *)buf
,
1058 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
1061 qemu_iovec_init_external(&qiov
, &iov
, 1);
1062 return bdrv_co_writev(bs
, sector_num
, nb_sectors
, &qiov
);
1067 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1070 if (bs
->dirty_bitmap
) {
1071 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1074 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1075 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1078 return drv
->bdrv_write(bs
, sector_num
, buf
, nb_sectors
);
1081 int bdrv_pread(BlockDriverState
*bs
, int64_t offset
,
1082 void *buf
, int count1
)
1084 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1085 int len
, nb_sectors
, count
;
1090 /* first read to align to sector start */
1091 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1094 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1096 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1098 memcpy(buf
, tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), len
);
1106 /* read the sectors "in place" */
1107 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1108 if (nb_sectors
> 0) {
1109 if ((ret
= bdrv_read(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1111 sector_num
+= nb_sectors
;
1112 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1117 /* add data from the last sector */
1119 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1121 memcpy(buf
, tmp_buf
, count
);
1126 int bdrv_pwrite(BlockDriverState
*bs
, int64_t offset
,
1127 const void *buf
, int count1
)
1129 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1130 int len
, nb_sectors
, count
;
1135 /* first write to align to sector start */
1136 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1139 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1141 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1143 memcpy(tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), buf
, len
);
1144 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1153 /* write the sectors "in place" */
1154 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1155 if (nb_sectors
> 0) {
1156 if ((ret
= bdrv_write(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1158 sector_num
+= nb_sectors
;
1159 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1164 /* add data from the last sector */
1166 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1168 memcpy(tmp_buf
, buf
, count
);
1169 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1176 * Writes to the file and ensures that no writes are reordered across this
1177 * request (acts as a barrier)
1179 * Returns 0 on success, -errno in error cases.
1181 int bdrv_pwrite_sync(BlockDriverState
*bs
, int64_t offset
,
1182 const void *buf
, int count
)
1186 ret
= bdrv_pwrite(bs
, offset
, buf
, count
);
1191 /* No flush needed for cache=writethrough, it uses O_DSYNC */
1192 if ((bs
->open_flags
& BDRV_O_CACHE_MASK
) != 0) {
1199 int coroutine_fn
bdrv_co_readv(BlockDriverState
*bs
, int64_t sector_num
,
1200 int nb_sectors
, QEMUIOVector
*qiov
)
1202 BlockDriver
*drv
= bs
->drv
;
1204 trace_bdrv_co_readv(bs
, sector_num
, nb_sectors
);
1209 if (bdrv_check_request(bs
, sector_num
, nb_sectors
)) {
1213 return drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1216 int coroutine_fn
bdrv_co_writev(BlockDriverState
*bs
, int64_t sector_num
,
1217 int nb_sectors
, QEMUIOVector
*qiov
)
1219 BlockDriver
*drv
= bs
->drv
;
1221 trace_bdrv_co_writev(bs
, sector_num
, nb_sectors
);
1226 if (bs
->read_only
) {
1229 if (bdrv_check_request(bs
, sector_num
, nb_sectors
)) {
1233 if (bs
->dirty_bitmap
) {
1234 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1237 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1238 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1241 return drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
);
1245 * Truncate file to 'offset' bytes (needed only for file protocols)
1247 int bdrv_truncate(BlockDriverState
*bs
, int64_t offset
)
1249 BlockDriver
*drv
= bs
->drv
;
1253 if (!drv
->bdrv_truncate
)
1257 if (bdrv_in_use(bs
))
1259 ret
= drv
->bdrv_truncate(bs
, offset
);
1261 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
1262 if (bs
->change_cb
) {
1263 bs
->change_cb(bs
->change_opaque
, CHANGE_SIZE
);
1270 * Length of a allocated file in bytes. Sparse files are counted by actual
1271 * allocated space. Return < 0 if error or unknown.
1273 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
1275 BlockDriver
*drv
= bs
->drv
;
1279 if (drv
->bdrv_get_allocated_file_size
) {
1280 return drv
->bdrv_get_allocated_file_size(bs
);
1283 return bdrv_get_allocated_file_size(bs
->file
);
1289 * Length of a file in bytes. Return < 0 if error or unknown.
1291 int64_t bdrv_getlength(BlockDriverState
*bs
)
1293 BlockDriver
*drv
= bs
->drv
;
1297 if (bs
->growable
|| bs
->removable
) {
1298 if (drv
->bdrv_getlength
) {
1299 return drv
->bdrv_getlength(bs
);
1302 return bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1305 /* return 0 as number of sectors if no device present or error */
1306 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
1309 length
= bdrv_getlength(bs
);
1313 length
= length
>> BDRV_SECTOR_BITS
;
1314 *nb_sectors_ptr
= length
;
1318 uint8_t boot_ind
; /* 0x80 - active */
1319 uint8_t head
; /* starting head */
1320 uint8_t sector
; /* starting sector */
1321 uint8_t cyl
; /* starting cylinder */
1322 uint8_t sys_ind
; /* What partition type */
1323 uint8_t end_head
; /* end head */
1324 uint8_t end_sector
; /* end sector */
1325 uint8_t end_cyl
; /* end cylinder */
1326 uint32_t start_sect
; /* starting sector counting from 0 */
1327 uint32_t nr_sects
; /* nr of sectors in partition */
1328 } __attribute__((packed
));
1330 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1331 static int guess_disk_lchs(BlockDriverState
*bs
,
1332 int *pcylinders
, int *pheads
, int *psectors
)
1334 uint8_t buf
[BDRV_SECTOR_SIZE
];
1335 int ret
, i
, heads
, sectors
, cylinders
;
1336 struct partition
*p
;
1338 uint64_t nb_sectors
;
1340 bdrv_get_geometry(bs
, &nb_sectors
);
1342 ret
= bdrv_read(bs
, 0, buf
, 1);
1345 /* test msdos magic */
1346 if (buf
[510] != 0x55 || buf
[511] != 0xaa)
1348 for(i
= 0; i
< 4; i
++) {
1349 p
= ((struct partition
*)(buf
+ 0x1be)) + i
;
1350 nr_sects
= le32_to_cpu(p
->nr_sects
);
1351 if (nr_sects
&& p
->end_head
) {
1352 /* We make the assumption that the partition terminates on
1353 a cylinder boundary */
1354 heads
= p
->end_head
+ 1;
1355 sectors
= p
->end_sector
& 63;
1358 cylinders
= nb_sectors
/ (heads
* sectors
);
1359 if (cylinders
< 1 || cylinders
> 16383)
1362 *psectors
= sectors
;
1363 *pcylinders
= cylinders
;
1365 printf("guessed geometry: LCHS=%d %d %d\n",
1366 cylinders
, heads
, sectors
);
1374 void bdrv_guess_geometry(BlockDriverState
*bs
, int *pcyls
, int *pheads
, int *psecs
)
1376 int translation
, lba_detected
= 0;
1377 int cylinders
, heads
, secs
;
1378 uint64_t nb_sectors
;
1380 /* if a geometry hint is available, use it */
1381 bdrv_get_geometry(bs
, &nb_sectors
);
1382 bdrv_get_geometry_hint(bs
, &cylinders
, &heads
, &secs
);
1383 translation
= bdrv_get_translation_hint(bs
);
1384 if (cylinders
!= 0) {
1389 if (guess_disk_lchs(bs
, &cylinders
, &heads
, &secs
) == 0) {
1391 /* if heads > 16, it means that a BIOS LBA
1392 translation was active, so the default
1393 hardware geometry is OK */
1395 goto default_geometry
;
1400 /* disable any translation to be in sync with
1401 the logical geometry */
1402 if (translation
== BIOS_ATA_TRANSLATION_AUTO
) {
1403 bdrv_set_translation_hint(bs
,
1404 BIOS_ATA_TRANSLATION_NONE
);
1409 /* if no geometry, use a standard physical disk geometry */
1410 cylinders
= nb_sectors
/ (16 * 63);
1412 if (cylinders
> 16383)
1414 else if (cylinders
< 2)
1419 if ((lba_detected
== 1) && (translation
== BIOS_ATA_TRANSLATION_AUTO
)) {
1420 if ((*pcyls
* *pheads
) <= 131072) {
1421 bdrv_set_translation_hint(bs
,
1422 BIOS_ATA_TRANSLATION_LARGE
);
1424 bdrv_set_translation_hint(bs
,
1425 BIOS_ATA_TRANSLATION_LBA
);
1429 bdrv_set_geometry_hint(bs
, *pcyls
, *pheads
, *psecs
);
1433 void bdrv_set_geometry_hint(BlockDriverState
*bs
,
1434 int cyls
, int heads
, int secs
)
1441 void bdrv_set_translation_hint(BlockDriverState
*bs
, int translation
)
1443 bs
->translation
= translation
;
1446 void bdrv_get_geometry_hint(BlockDriverState
*bs
,
1447 int *pcyls
, int *pheads
, int *psecs
)
1450 *pheads
= bs
->heads
;
1454 /* Recognize floppy formats */
1455 typedef struct FDFormat
{
1462 static const FDFormat fd_formats
[] = {
1463 /* First entry is default format */
1464 /* 1.44 MB 3"1/2 floppy disks */
1465 { FDRIVE_DRV_144
, 18, 80, 1, },
1466 { FDRIVE_DRV_144
, 20, 80, 1, },
1467 { FDRIVE_DRV_144
, 21, 80, 1, },
1468 { FDRIVE_DRV_144
, 21, 82, 1, },
1469 { FDRIVE_DRV_144
, 21, 83, 1, },
1470 { FDRIVE_DRV_144
, 22, 80, 1, },
1471 { FDRIVE_DRV_144
, 23, 80, 1, },
1472 { FDRIVE_DRV_144
, 24, 80, 1, },
1473 /* 2.88 MB 3"1/2 floppy disks */
1474 { FDRIVE_DRV_288
, 36, 80, 1, },
1475 { FDRIVE_DRV_288
, 39, 80, 1, },
1476 { FDRIVE_DRV_288
, 40, 80, 1, },
1477 { FDRIVE_DRV_288
, 44, 80, 1, },
1478 { FDRIVE_DRV_288
, 48, 80, 1, },
1479 /* 720 kB 3"1/2 floppy disks */
1480 { FDRIVE_DRV_144
, 9, 80, 1, },
1481 { FDRIVE_DRV_144
, 10, 80, 1, },
1482 { FDRIVE_DRV_144
, 10, 82, 1, },
1483 { FDRIVE_DRV_144
, 10, 83, 1, },
1484 { FDRIVE_DRV_144
, 13, 80, 1, },
1485 { FDRIVE_DRV_144
, 14, 80, 1, },
1486 /* 1.2 MB 5"1/4 floppy disks */
1487 { FDRIVE_DRV_120
, 15, 80, 1, },
1488 { FDRIVE_DRV_120
, 18, 80, 1, },
1489 { FDRIVE_DRV_120
, 18, 82, 1, },
1490 { FDRIVE_DRV_120
, 18, 83, 1, },
1491 { FDRIVE_DRV_120
, 20, 80, 1, },
1492 /* 720 kB 5"1/4 floppy disks */
1493 { FDRIVE_DRV_120
, 9, 80, 1, },
1494 { FDRIVE_DRV_120
, 11, 80, 1, },
1495 /* 360 kB 5"1/4 floppy disks */
1496 { FDRIVE_DRV_120
, 9, 40, 1, },
1497 { FDRIVE_DRV_120
, 9, 40, 0, },
1498 { FDRIVE_DRV_120
, 10, 41, 1, },
1499 { FDRIVE_DRV_120
, 10, 42, 1, },
1500 /* 320 kB 5"1/4 floppy disks */
1501 { FDRIVE_DRV_120
, 8, 40, 1, },
1502 { FDRIVE_DRV_120
, 8, 40, 0, },
1503 /* 360 kB must match 5"1/4 better than 3"1/2... */
1504 { FDRIVE_DRV_144
, 9, 80, 0, },
1506 { FDRIVE_DRV_NONE
, -1, -1, 0, },
1509 void bdrv_get_floppy_geometry_hint(BlockDriverState
*bs
, int *nb_heads
,
1510 int *max_track
, int *last_sect
,
1511 FDriveType drive_in
, FDriveType
*drive
)
1513 const FDFormat
*parse
;
1514 uint64_t nb_sectors
, size
;
1515 int i
, first_match
, match
;
1517 bdrv_get_geometry_hint(bs
, nb_heads
, max_track
, last_sect
);
1518 if (*nb_heads
!= 0 && *max_track
!= 0 && *last_sect
!= 0) {
1519 /* User defined disk */
1521 bdrv_get_geometry(bs
, &nb_sectors
);
1524 for (i
= 0; ; i
++) {
1525 parse
= &fd_formats
[i
];
1526 if (parse
->drive
== FDRIVE_DRV_NONE
) {
1529 if (drive_in
== parse
->drive
||
1530 drive_in
== FDRIVE_DRV_NONE
) {
1531 size
= (parse
->max_head
+ 1) * parse
->max_track
*
1533 if (nb_sectors
== size
) {
1537 if (first_match
== -1) {
1543 if (first_match
== -1) {
1546 match
= first_match
;
1548 parse
= &fd_formats
[match
];
1550 *nb_heads
= parse
->max_head
+ 1;
1551 *max_track
= parse
->max_track
;
1552 *last_sect
= parse
->last_sect
;
1553 *drive
= parse
->drive
;
1557 int bdrv_get_translation_hint(BlockDriverState
*bs
)
1559 return bs
->translation
;
1562 void bdrv_set_on_error(BlockDriverState
*bs
, BlockErrorAction on_read_error
,
1563 BlockErrorAction on_write_error
)
1565 bs
->on_read_error
= on_read_error
;
1566 bs
->on_write_error
= on_write_error
;
1569 BlockErrorAction
bdrv_get_on_error(BlockDriverState
*bs
, int is_read
)
1571 return is_read
? bs
->on_read_error
: bs
->on_write_error
;
1574 void bdrv_set_removable(BlockDriverState
*bs
, int removable
)
1576 bs
->removable
= removable
;
1577 if (removable
&& bs
== bs_snapshots
) {
1578 bs_snapshots
= NULL
;
1582 int bdrv_is_removable(BlockDriverState
*bs
)
1584 return bs
->removable
;
1587 int bdrv_is_read_only(BlockDriverState
*bs
)
1589 return bs
->read_only
;
1592 int bdrv_is_sg(BlockDriverState
*bs
)
1597 int bdrv_enable_write_cache(BlockDriverState
*bs
)
1599 return bs
->enable_write_cache
;
1602 /* XXX: no longer used */
1603 void bdrv_set_change_cb(BlockDriverState
*bs
,
1604 void (*change_cb
)(void *opaque
, int reason
),
1607 bs
->change_cb
= change_cb
;
1608 bs
->change_opaque
= opaque
;
1611 int bdrv_is_encrypted(BlockDriverState
*bs
)
1613 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1615 return bs
->encrypted
;
1618 int bdrv_key_required(BlockDriverState
*bs
)
1620 BlockDriverState
*backing_hd
= bs
->backing_hd
;
1622 if (backing_hd
&& backing_hd
->encrypted
&& !backing_hd
->valid_key
)
1624 return (bs
->encrypted
&& !bs
->valid_key
);
1627 int bdrv_set_key(BlockDriverState
*bs
, const char *key
)
1630 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
) {
1631 ret
= bdrv_set_key(bs
->backing_hd
, key
);
1637 if (!bs
->encrypted
) {
1639 } else if (!bs
->drv
|| !bs
->drv
->bdrv_set_key
) {
1642 ret
= bs
->drv
->bdrv_set_key(bs
, key
);
1645 } else if (!bs
->valid_key
) {
1647 /* call the change callback now, we skipped it on open */
1648 bs
->media_changed
= 1;
1650 bs
->change_cb(bs
->change_opaque
, CHANGE_MEDIA
);
1655 void bdrv_get_format(BlockDriverState
*bs
, char *buf
, int buf_size
)
1660 pstrcpy(buf
, buf_size
, bs
->drv
->format_name
);
1664 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
1669 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
1670 it(opaque
, drv
->format_name
);
1674 BlockDriverState
*bdrv_find(const char *name
)
1676 BlockDriverState
*bs
;
1678 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1679 if (!strcmp(name
, bs
->device_name
)) {
1686 BlockDriverState
*bdrv_next(BlockDriverState
*bs
)
1689 return QTAILQ_FIRST(&bdrv_states
);
1691 return QTAILQ_NEXT(bs
, list
);
1694 void bdrv_iterate(void (*it
)(void *opaque
, BlockDriverState
*bs
), void *opaque
)
1696 BlockDriverState
*bs
;
1698 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1703 const char *bdrv_get_device_name(BlockDriverState
*bs
)
1705 return bs
->device_name
;
1708 int bdrv_flush(BlockDriverState
*bs
)
1710 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
1714 if (bs
->drv
&& bdrv_has_async_flush(bs
->drv
) && qemu_in_coroutine()) {
1715 return bdrv_co_flush_em(bs
);
1718 if (bs
->drv
&& bs
->drv
->bdrv_flush
) {
1719 return bs
->drv
->bdrv_flush(bs
);
1723 * Some block drivers always operate in either writethrough or unsafe mode
1724 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1725 * the server works (because the behaviour is hardcoded or depends on
1726 * server-side configuration), so we can't ensure that everything is safe
1727 * on disk. Returning an error doesn't work because that would break guests
1728 * even if the server operates in writethrough mode.
1730 * Let's hope the user knows what he's doing.
1735 void bdrv_flush_all(void)
1737 BlockDriverState
*bs
;
1739 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1740 if (bs
->drv
&& !bdrv_is_read_only(bs
) &&
1741 (!bdrv_is_removable(bs
) || bdrv_is_inserted(bs
))) {
1747 int bdrv_has_zero_init(BlockDriverState
*bs
)
1751 if (bs
->drv
->bdrv_has_zero_init
) {
1752 return bs
->drv
->bdrv_has_zero_init(bs
);
1758 int bdrv_discard(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
)
1763 if (!bs
->drv
->bdrv_discard
) {
1766 return bs
->drv
->bdrv_discard(bs
, sector_num
, nb_sectors
);
1770 * Returns true iff the specified sector is present in the disk image. Drivers
1771 * not implementing the functionality are assumed to not support backing files,
1772 * hence all their sectors are reported as allocated.
1774 * 'pnum' is set to the number of sectors (including and immediately following
1775 * the specified sector) that are known to be in the same
1776 * allocated/unallocated state.
1778 * 'nb_sectors' is the max value 'pnum' should be set to.
1780 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
,
1784 if (!bs
->drv
->bdrv_is_allocated
) {
1785 if (sector_num
>= bs
->total_sectors
) {
1789 n
= bs
->total_sectors
- sector_num
;
1790 *pnum
= (n
< nb_sectors
) ? (n
) : (nb_sectors
);
1793 return bs
->drv
->bdrv_is_allocated(bs
, sector_num
, nb_sectors
, pnum
);
1796 void bdrv_mon_event(const BlockDriverState
*bdrv
,
1797 BlockMonEventAction action
, int is_read
)
1800 const char *action_str
;
1803 case BDRV_ACTION_REPORT
:
1804 action_str
= "report";
1806 case BDRV_ACTION_IGNORE
:
1807 action_str
= "ignore";
1809 case BDRV_ACTION_STOP
:
1810 action_str
= "stop";
1816 data
= qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1819 is_read
? "read" : "write");
1820 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR
, data
);
1822 qobject_decref(data
);
1825 static void bdrv_print_dict(QObject
*obj
, void *opaque
)
1828 Monitor
*mon
= opaque
;
1830 bs_dict
= qobject_to_qdict(obj
);
1832 monitor_printf(mon
, "%s: removable=%d",
1833 qdict_get_str(bs_dict
, "device"),
1834 qdict_get_bool(bs_dict
, "removable"));
1836 if (qdict_get_bool(bs_dict
, "removable")) {
1837 monitor_printf(mon
, " locked=%d", qdict_get_bool(bs_dict
, "locked"));
1840 if (qdict_haskey(bs_dict
, "inserted")) {
1841 QDict
*qdict
= qobject_to_qdict(qdict_get(bs_dict
, "inserted"));
1843 monitor_printf(mon
, " file=");
1844 monitor_print_filename(mon
, qdict_get_str(qdict
, "file"));
1845 if (qdict_haskey(qdict
, "backing_file")) {
1846 monitor_printf(mon
, " backing_file=");
1847 monitor_print_filename(mon
, qdict_get_str(qdict
, "backing_file"));
1849 monitor_printf(mon
, " ro=%d drv=%s encrypted=%d",
1850 qdict_get_bool(qdict
, "ro"),
1851 qdict_get_str(qdict
, "drv"),
1852 qdict_get_bool(qdict
, "encrypted"));
1854 monitor_printf(mon
, " [not inserted]");
1857 monitor_printf(mon
, "\n");
1860 void bdrv_info_print(Monitor
*mon
, const QObject
*data
)
1862 qlist_iter(qobject_to_qlist(data
), bdrv_print_dict
, mon
);
1865 void bdrv_info(Monitor
*mon
, QObject
**ret_data
)
1868 BlockDriverState
*bs
;
1870 bs_list
= qlist_new();
1872 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1875 bs_obj
= qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
1876 "'removable': %i, 'locked': %i }",
1877 bs
->device_name
, bs
->removable
,
1882 QDict
*bs_dict
= qobject_to_qdict(bs_obj
);
1884 obj
= qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1885 "'encrypted': %i }",
1886 bs
->filename
, bs
->read_only
,
1887 bs
->drv
->format_name
,
1888 bdrv_is_encrypted(bs
));
1889 if (bs
->backing_file
[0] != '\0') {
1890 QDict
*qdict
= qobject_to_qdict(obj
);
1891 qdict_put(qdict
, "backing_file",
1892 qstring_from_str(bs
->backing_file
));
1895 qdict_put_obj(bs_dict
, "inserted", obj
);
1897 qlist_append_obj(bs_list
, bs_obj
);
1900 *ret_data
= QOBJECT(bs_list
);
1903 static void bdrv_stats_iter(QObject
*data
, void *opaque
)
1906 Monitor
*mon
= opaque
;
1908 qdict
= qobject_to_qdict(data
);
1909 monitor_printf(mon
, "%s:", qdict_get_str(qdict
, "device"));
1911 qdict
= qobject_to_qdict(qdict_get(qdict
, "stats"));
1912 monitor_printf(mon
, " rd_bytes=%" PRId64
1913 " wr_bytes=%" PRId64
1914 " rd_operations=%" PRId64
1915 " wr_operations=%" PRId64
1917 qdict_get_int(qdict
, "rd_bytes"),
1918 qdict_get_int(qdict
, "wr_bytes"),
1919 qdict_get_int(qdict
, "rd_operations"),
1920 qdict_get_int(qdict
, "wr_operations"));
1923 void bdrv_stats_print(Monitor
*mon
, const QObject
*data
)
1925 qlist_iter(qobject_to_qlist(data
), bdrv_stats_iter
, mon
);
1928 static QObject
* bdrv_info_stats_bs(BlockDriverState
*bs
)
1933 res
= qobject_from_jsonf("{ 'stats': {"
1934 "'rd_bytes': %" PRId64
","
1935 "'wr_bytes': %" PRId64
","
1936 "'rd_operations': %" PRId64
","
1937 "'wr_operations': %" PRId64
","
1938 "'wr_highest_offset': %" PRId64
1940 bs
->rd_bytes
, bs
->wr_bytes
,
1941 bs
->rd_ops
, bs
->wr_ops
,
1942 bs
->wr_highest_sector
*
1943 (uint64_t)BDRV_SECTOR_SIZE
);
1944 dict
= qobject_to_qdict(res
);
1946 if (*bs
->device_name
) {
1947 qdict_put(dict
, "device", qstring_from_str(bs
->device_name
));
1951 QObject
*parent
= bdrv_info_stats_bs(bs
->file
);
1952 qdict_put_obj(dict
, "parent", parent
);
1958 void bdrv_info_stats(Monitor
*mon
, QObject
**ret_data
)
1962 BlockDriverState
*bs
;
1964 devices
= qlist_new();
1966 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1967 obj
= bdrv_info_stats_bs(bs
);
1968 qlist_append_obj(devices
, obj
);
1971 *ret_data
= QOBJECT(devices
);
1974 const char *bdrv_get_encrypted_filename(BlockDriverState
*bs
)
1976 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1977 return bs
->backing_file
;
1978 else if (bs
->encrypted
)
1979 return bs
->filename
;
1984 void bdrv_get_backing_filename(BlockDriverState
*bs
,
1985 char *filename
, int filename_size
)
1987 if (!bs
->backing_file
) {
1988 pstrcpy(filename
, filename_size
, "");
1990 pstrcpy(filename
, filename_size
, bs
->backing_file
);
1994 int bdrv_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
1995 const uint8_t *buf
, int nb_sectors
)
1997 BlockDriver
*drv
= bs
->drv
;
2000 if (!drv
->bdrv_write_compressed
)
2002 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2005 if (bs
->dirty_bitmap
) {
2006 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
2009 return drv
->bdrv_write_compressed(bs
, sector_num
, buf
, nb_sectors
);
2012 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2014 BlockDriver
*drv
= bs
->drv
;
2017 if (!drv
->bdrv_get_info
)
2019 memset(bdi
, 0, sizeof(*bdi
));
2020 return drv
->bdrv_get_info(bs
, bdi
);
2023 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2024 int64_t pos
, int size
)
2026 BlockDriver
*drv
= bs
->drv
;
2029 if (drv
->bdrv_save_vmstate
)
2030 return drv
->bdrv_save_vmstate(bs
, buf
, pos
, size
);
2032 return bdrv_save_vmstate(bs
->file
, buf
, pos
, size
);
2036 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2037 int64_t pos
, int size
)
2039 BlockDriver
*drv
= bs
->drv
;
2042 if (drv
->bdrv_load_vmstate
)
2043 return drv
->bdrv_load_vmstate(bs
, buf
, pos
, size
);
2045 return bdrv_load_vmstate(bs
->file
, buf
, pos
, size
);
2049 void bdrv_debug_event(BlockDriverState
*bs
, BlkDebugEvent event
)
2051 BlockDriver
*drv
= bs
->drv
;
2053 if (!drv
|| !drv
->bdrv_debug_event
) {
2057 return drv
->bdrv_debug_event(bs
, event
);
2061 /**************************************************************/
2062 /* handling of snapshots */
2064 int bdrv_can_snapshot(BlockDriverState
*bs
)
2066 BlockDriver
*drv
= bs
->drv
;
2067 if (!drv
|| bdrv_is_removable(bs
) || bdrv_is_read_only(bs
)) {
2071 if (!drv
->bdrv_snapshot_create
) {
2072 if (bs
->file
!= NULL
) {
2073 return bdrv_can_snapshot(bs
->file
);
2081 int bdrv_is_snapshot(BlockDriverState
*bs
)
2083 return !!(bs
->open_flags
& BDRV_O_SNAPSHOT
);
2086 BlockDriverState
*bdrv_snapshots(void)
2088 BlockDriverState
*bs
;
2091 return bs_snapshots
;
2095 while ((bs
= bdrv_next(bs
))) {
2096 if (bdrv_can_snapshot(bs
)) {
2104 int bdrv_snapshot_create(BlockDriverState
*bs
,
2105 QEMUSnapshotInfo
*sn_info
)
2107 BlockDriver
*drv
= bs
->drv
;
2110 if (drv
->bdrv_snapshot_create
)
2111 return drv
->bdrv_snapshot_create(bs
, sn_info
);
2113 return bdrv_snapshot_create(bs
->file
, sn_info
);
2117 int bdrv_snapshot_goto(BlockDriverState
*bs
,
2118 const char *snapshot_id
)
2120 BlockDriver
*drv
= bs
->drv
;
2125 if (drv
->bdrv_snapshot_goto
)
2126 return drv
->bdrv_snapshot_goto(bs
, snapshot_id
);
2129 drv
->bdrv_close(bs
);
2130 ret
= bdrv_snapshot_goto(bs
->file
, snapshot_id
);
2131 open_ret
= drv
->bdrv_open(bs
, bs
->open_flags
);
2133 bdrv_delete(bs
->file
);
2143 int bdrv_snapshot_delete(BlockDriverState
*bs
, const char *snapshot_id
)
2145 BlockDriver
*drv
= bs
->drv
;
2148 if (drv
->bdrv_snapshot_delete
)
2149 return drv
->bdrv_snapshot_delete(bs
, snapshot_id
);
2151 return bdrv_snapshot_delete(bs
->file
, snapshot_id
);
2155 int bdrv_snapshot_list(BlockDriverState
*bs
,
2156 QEMUSnapshotInfo
**psn_info
)
2158 BlockDriver
*drv
= bs
->drv
;
2161 if (drv
->bdrv_snapshot_list
)
2162 return drv
->bdrv_snapshot_list(bs
, psn_info
);
2164 return bdrv_snapshot_list(bs
->file
, psn_info
);
2168 int bdrv_snapshot_load_tmp(BlockDriverState
*bs
,
2169 const char *snapshot_name
)
2171 BlockDriver
*drv
= bs
->drv
;
2175 if (!bs
->read_only
) {
2178 if (drv
->bdrv_snapshot_load_tmp
) {
2179 return drv
->bdrv_snapshot_load_tmp(bs
, snapshot_name
);
2184 #define NB_SUFFIXES 4
2186 char *get_human_readable_size(char *buf
, int buf_size
, int64_t size
)
2188 static const char suffixes
[NB_SUFFIXES
] = "KMGT";
2193 snprintf(buf
, buf_size
, "%" PRId64
, size
);
2196 for(i
= 0; i
< NB_SUFFIXES
; i
++) {
2197 if (size
< (10 * base
)) {
2198 snprintf(buf
, buf_size
, "%0.1f%c",
2199 (double)size
/ base
,
2202 } else if (size
< (1000 * base
) || i
== (NB_SUFFIXES
- 1)) {
2203 snprintf(buf
, buf_size
, "%" PRId64
"%c",
2204 ((size
+ (base
>> 1)) / base
),
2214 char *bdrv_snapshot_dump(char *buf
, int buf_size
, QEMUSnapshotInfo
*sn
)
2216 char buf1
[128], date_buf
[128], clock_buf
[128];
2226 snprintf(buf
, buf_size
,
2227 "%-10s%-20s%7s%20s%15s",
2228 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2232 ptm
= localtime(&ti
);
2233 strftime(date_buf
, sizeof(date_buf
),
2234 "%Y-%m-%d %H:%M:%S", ptm
);
2236 localtime_r(&ti
, &tm
);
2237 strftime(date_buf
, sizeof(date_buf
),
2238 "%Y-%m-%d %H:%M:%S", &tm
);
2240 secs
= sn
->vm_clock_nsec
/ 1000000000;
2241 snprintf(clock_buf
, sizeof(clock_buf
),
2242 "%02d:%02d:%02d.%03d",
2244 (int)((secs
/ 60) % 60),
2246 (int)((sn
->vm_clock_nsec
/ 1000000) % 1000));
2247 snprintf(buf
, buf_size
,
2248 "%-10s%-20s%7s%20s%15s",
2249 sn
->id_str
, sn
->name
,
2250 get_human_readable_size(buf1
, sizeof(buf1
), sn
->vm_state_size
),
2258 /**************************************************************/
2261 BlockDriverAIOCB
*bdrv_aio_readv(BlockDriverState
*bs
, int64_t sector_num
,
2262 QEMUIOVector
*qiov
, int nb_sectors
,
2263 BlockDriverCompletionFunc
*cb
, void *opaque
)
2265 BlockDriver
*drv
= bs
->drv
;
2266 BlockDriverAIOCB
*ret
;
2268 trace_bdrv_aio_readv(bs
, sector_num
, nb_sectors
, opaque
);
2272 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2275 ret
= drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
2279 /* Update stats even though technically transfer has not happened. */
2280 bs
->rd_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
2287 typedef struct BlockCompleteData
{
2288 BlockDriverCompletionFunc
*cb
;
2290 BlockDriverState
*bs
;
2293 } BlockCompleteData
;
2295 static void block_complete_cb(void *opaque
, int ret
)
2297 BlockCompleteData
*b
= opaque
;
2299 if (b
->bs
->dirty_bitmap
) {
2300 set_dirty_bitmap(b
->bs
, b
->sector_num
, b
->nb_sectors
, 1);
2302 b
->cb(b
->opaque
, ret
);
2306 static BlockCompleteData
*blk_dirty_cb_alloc(BlockDriverState
*bs
,
2309 BlockDriverCompletionFunc
*cb
,
2312 BlockCompleteData
*blkdata
= g_malloc0(sizeof(BlockCompleteData
));
2316 blkdata
->opaque
= opaque
;
2317 blkdata
->sector_num
= sector_num
;
2318 blkdata
->nb_sectors
= nb_sectors
;
2323 BlockDriverAIOCB
*bdrv_aio_writev(BlockDriverState
*bs
, int64_t sector_num
,
2324 QEMUIOVector
*qiov
, int nb_sectors
,
2325 BlockDriverCompletionFunc
*cb
, void *opaque
)
2327 BlockDriver
*drv
= bs
->drv
;
2328 BlockDriverAIOCB
*ret
;
2329 BlockCompleteData
*blk_cb_data
;
2331 trace_bdrv_aio_writev(bs
, sector_num
, nb_sectors
, opaque
);
2337 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2340 if (bs
->dirty_bitmap
) {
2341 blk_cb_data
= blk_dirty_cb_alloc(bs
, sector_num
, nb_sectors
, cb
,
2343 cb
= &block_complete_cb
;
2344 opaque
= blk_cb_data
;
2347 ret
= drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
2351 /* Update stats even though technically transfer has not happened. */
2352 bs
->wr_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
2354 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
2355 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
2363 typedef struct MultiwriteCB
{
2368 BlockDriverCompletionFunc
*cb
;
2370 QEMUIOVector
*free_qiov
;
2375 static void multiwrite_user_cb(MultiwriteCB
*mcb
)
2379 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2380 mcb
->callbacks
[i
].cb(mcb
->callbacks
[i
].opaque
, mcb
->error
);
2381 if (mcb
->callbacks
[i
].free_qiov
) {
2382 qemu_iovec_destroy(mcb
->callbacks
[i
].free_qiov
);
2384 g_free(mcb
->callbacks
[i
].free_qiov
);
2385 qemu_vfree(mcb
->callbacks
[i
].free_buf
);
2389 static void multiwrite_cb(void *opaque
, int ret
)
2391 MultiwriteCB
*mcb
= opaque
;
2393 trace_multiwrite_cb(mcb
, ret
);
2395 if (ret
< 0 && !mcb
->error
) {
2399 mcb
->num_requests
--;
2400 if (mcb
->num_requests
== 0) {
2401 multiwrite_user_cb(mcb
);
2406 static int multiwrite_req_compare(const void *a
, const void *b
)
2408 const BlockRequest
*req1
= a
, *req2
= b
;
2411 * Note that we can't simply subtract req2->sector from req1->sector
2412 * here as that could overflow the return value.
2414 if (req1
->sector
> req2
->sector
) {
2416 } else if (req1
->sector
< req2
->sector
) {
2424 * Takes a bunch of requests and tries to merge them. Returns the number of
2425 * requests that remain after merging.
2427 static int multiwrite_merge(BlockDriverState
*bs
, BlockRequest
*reqs
,
2428 int num_reqs
, MultiwriteCB
*mcb
)
2432 // Sort requests by start sector
2433 qsort(reqs
, num_reqs
, sizeof(*reqs
), &multiwrite_req_compare
);
2435 // Check if adjacent requests touch the same clusters. If so, combine them,
2436 // filling up gaps with zero sectors.
2438 for (i
= 1; i
< num_reqs
; i
++) {
2440 int64_t oldreq_last
= reqs
[outidx
].sector
+ reqs
[outidx
].nb_sectors
;
2442 // This handles the cases that are valid for all block drivers, namely
2443 // exactly sequential writes and overlapping writes.
2444 if (reqs
[i
].sector
<= oldreq_last
) {
2448 // The block driver may decide that it makes sense to combine requests
2449 // even if there is a gap of some sectors between them. In this case,
2450 // the gap is filled with zeros (therefore only applicable for yet
2451 // unused space in format like qcow2).
2452 if (!merge
&& bs
->drv
->bdrv_merge_requests
) {
2453 merge
= bs
->drv
->bdrv_merge_requests(bs
, &reqs
[outidx
], &reqs
[i
]);
2456 if (reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1 > IOV_MAX
) {
2462 QEMUIOVector
*qiov
= g_malloc0(sizeof(*qiov
));
2463 qemu_iovec_init(qiov
,
2464 reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1);
2466 // Add the first request to the merged one. If the requests are
2467 // overlapping, drop the last sectors of the first request.
2468 size
= (reqs
[i
].sector
- reqs
[outidx
].sector
) << 9;
2469 qemu_iovec_concat(qiov
, reqs
[outidx
].qiov
, size
);
2471 // We might need to add some zeros between the two requests
2472 if (reqs
[i
].sector
> oldreq_last
) {
2473 size_t zero_bytes
= (reqs
[i
].sector
- oldreq_last
) << 9;
2474 uint8_t *buf
= qemu_blockalign(bs
, zero_bytes
);
2475 memset(buf
, 0, zero_bytes
);
2476 qemu_iovec_add(qiov
, buf
, zero_bytes
);
2477 mcb
->callbacks
[i
].free_buf
= buf
;
2480 // Add the second request
2481 qemu_iovec_concat(qiov
, reqs
[i
].qiov
, reqs
[i
].qiov
->size
);
2483 reqs
[outidx
].nb_sectors
= qiov
->size
>> 9;
2484 reqs
[outidx
].qiov
= qiov
;
2486 mcb
->callbacks
[i
].free_qiov
= reqs
[outidx
].qiov
;
2489 reqs
[outidx
].sector
= reqs
[i
].sector
;
2490 reqs
[outidx
].nb_sectors
= reqs
[i
].nb_sectors
;
2491 reqs
[outidx
].qiov
= reqs
[i
].qiov
;
2499 * Submit multiple AIO write requests at once.
2501 * On success, the function returns 0 and all requests in the reqs array have
2502 * been submitted. In error case this function returns -1, and any of the
2503 * requests may or may not be submitted yet. In particular, this means that the
2504 * callback will be called for some of the requests, for others it won't. The
2505 * caller must check the error field of the BlockRequest to wait for the right
2506 * callbacks (if error != 0, no callback will be called).
2508 * The implementation may modify the contents of the reqs array, e.g. to merge
2509 * requests. However, the fields opaque and error are left unmodified as they
2510 * are used to signal failure for a single request to the caller.
2512 int bdrv_aio_multiwrite(BlockDriverState
*bs
, BlockRequest
*reqs
, int num_reqs
)
2514 BlockDriverAIOCB
*acb
;
2518 /* don't submit writes if we don't have a medium */
2519 if (bs
->drv
== NULL
) {
2520 for (i
= 0; i
< num_reqs
; i
++) {
2521 reqs
[i
].error
= -ENOMEDIUM
;
2526 if (num_reqs
== 0) {
2530 // Create MultiwriteCB structure
2531 mcb
= g_malloc0(sizeof(*mcb
) + num_reqs
* sizeof(*mcb
->callbacks
));
2532 mcb
->num_requests
= 0;
2533 mcb
->num_callbacks
= num_reqs
;
2535 for (i
= 0; i
< num_reqs
; i
++) {
2536 mcb
->callbacks
[i
].cb
= reqs
[i
].cb
;
2537 mcb
->callbacks
[i
].opaque
= reqs
[i
].opaque
;
2540 // Check for mergable requests
2541 num_reqs
= multiwrite_merge(bs
, reqs
, num_reqs
, mcb
);
2543 trace_bdrv_aio_multiwrite(mcb
, mcb
->num_callbacks
, num_reqs
);
2546 * Run the aio requests. As soon as one request can't be submitted
2547 * successfully, fail all requests that are not yet submitted (we must
2548 * return failure for all requests anyway)
2550 * num_requests cannot be set to the right value immediately: If
2551 * bdrv_aio_writev fails for some request, num_requests would be too high
2552 * and therefore multiwrite_cb() would never recognize the multiwrite
2553 * request as completed. We also cannot use the loop variable i to set it
2554 * when the first request fails because the callback may already have been
2555 * called for previously submitted requests. Thus, num_requests must be
2556 * incremented for each request that is submitted.
2558 * The problem that callbacks may be called early also means that we need
2559 * to take care that num_requests doesn't become 0 before all requests are
2560 * submitted - multiwrite_cb() would consider the multiwrite request
2561 * completed. A dummy request that is "completed" by a manual call to
2562 * multiwrite_cb() takes care of this.
2564 mcb
->num_requests
= 1;
2566 // Run the aio requests
2567 for (i
= 0; i
< num_reqs
; i
++) {
2568 mcb
->num_requests
++;
2569 acb
= bdrv_aio_writev(bs
, reqs
[i
].sector
, reqs
[i
].qiov
,
2570 reqs
[i
].nb_sectors
, multiwrite_cb
, mcb
);
2573 // We can only fail the whole thing if no request has been
2574 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2575 // complete and report the error in the callback.
2577 trace_bdrv_aio_multiwrite_earlyfail(mcb
);
2580 trace_bdrv_aio_multiwrite_latefail(mcb
, i
);
2581 multiwrite_cb(mcb
, -EIO
);
2587 /* Complete the dummy request */
2588 multiwrite_cb(mcb
, 0);
2593 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2594 reqs
[i
].error
= -EIO
;
2600 BlockDriverAIOCB
*bdrv_aio_flush(BlockDriverState
*bs
,
2601 BlockDriverCompletionFunc
*cb
, void *opaque
)
2603 BlockDriver
*drv
= bs
->drv
;
2605 trace_bdrv_aio_flush(bs
, opaque
);
2607 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2608 return bdrv_aio_noop_em(bs
, cb
, opaque
);
2613 return drv
->bdrv_aio_flush(bs
, cb
, opaque
);
2616 void bdrv_aio_cancel(BlockDriverAIOCB
*acb
)
2618 acb
->pool
->cancel(acb
);
2622 /**************************************************************/
2623 /* async block device emulation */
2625 typedef struct BlockDriverAIOCBSync
{
2626 BlockDriverAIOCB common
;
2629 /* vector translation state */
2633 } BlockDriverAIOCBSync
;
2635 static void bdrv_aio_cancel_em(BlockDriverAIOCB
*blockacb
)
2637 BlockDriverAIOCBSync
*acb
=
2638 container_of(blockacb
, BlockDriverAIOCBSync
, common
);
2639 qemu_bh_delete(acb
->bh
);
2641 qemu_aio_release(acb
);
2644 static AIOPool bdrv_em_aio_pool
= {
2645 .aiocb_size
= sizeof(BlockDriverAIOCBSync
),
2646 .cancel
= bdrv_aio_cancel_em
,
2649 static void bdrv_aio_bh_cb(void *opaque
)
2651 BlockDriverAIOCBSync
*acb
= opaque
;
2654 qemu_iovec_from_buffer(acb
->qiov
, acb
->bounce
, acb
->qiov
->size
);
2655 qemu_vfree(acb
->bounce
);
2656 acb
->common
.cb(acb
->common
.opaque
, acb
->ret
);
2657 qemu_bh_delete(acb
->bh
);
2659 qemu_aio_release(acb
);
2662 static BlockDriverAIOCB
*bdrv_aio_rw_vector(BlockDriverState
*bs
,
2666 BlockDriverCompletionFunc
*cb
,
2671 BlockDriverAIOCBSync
*acb
;
2673 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2674 acb
->is_write
= is_write
;
2676 acb
->bounce
= qemu_blockalign(bs
, qiov
->size
);
2679 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2682 qemu_iovec_to_buffer(acb
->qiov
, acb
->bounce
);
2683 acb
->ret
= bdrv_write(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2685 acb
->ret
= bdrv_read(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2688 qemu_bh_schedule(acb
->bh
);
2690 return &acb
->common
;
2693 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
2694 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2695 BlockDriverCompletionFunc
*cb
, void *opaque
)
2697 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 0);
2700 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
2701 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2702 BlockDriverCompletionFunc
*cb
, void *opaque
)
2704 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 1);
2708 typedef struct BlockDriverAIOCBCoroutine
{
2709 BlockDriverAIOCB common
;
2713 } BlockDriverAIOCBCoroutine
;
2715 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB
*blockacb
)
2720 static AIOPool bdrv_em_co_aio_pool
= {
2721 .aiocb_size
= sizeof(BlockDriverAIOCBCoroutine
),
2722 .cancel
= bdrv_aio_co_cancel_em
,
2725 static void bdrv_co_rw_bh(void *opaque
)
2727 BlockDriverAIOCBCoroutine
*acb
= opaque
;
2729 acb
->common
.cb(acb
->common
.opaque
, acb
->req
.error
);
2730 qemu_bh_delete(acb
->bh
);
2731 qemu_aio_release(acb
);
2734 static void coroutine_fn
bdrv_co_rw(void *opaque
)
2736 BlockDriverAIOCBCoroutine
*acb
= opaque
;
2737 BlockDriverState
*bs
= acb
->common
.bs
;
2739 if (!acb
->is_write
) {
2740 acb
->req
.error
= bs
->drv
->bdrv_co_readv(bs
, acb
->req
.sector
,
2741 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2743 acb
->req
.error
= bs
->drv
->bdrv_co_writev(bs
, acb
->req
.sector
,
2744 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2747 acb
->bh
= qemu_bh_new(bdrv_co_rw_bh
, acb
);
2748 qemu_bh_schedule(acb
->bh
);
2751 static BlockDriverAIOCB
*bdrv_co_aio_rw_vector(BlockDriverState
*bs
,
2755 BlockDriverCompletionFunc
*cb
,
2760 BlockDriverAIOCBCoroutine
*acb
;
2762 acb
= qemu_aio_get(&bdrv_em_co_aio_pool
, bs
, cb
, opaque
);
2763 acb
->req
.sector
= sector_num
;
2764 acb
->req
.nb_sectors
= nb_sectors
;
2765 acb
->req
.qiov
= qiov
;
2766 acb
->is_write
= is_write
;
2768 co
= qemu_coroutine_create(bdrv_co_rw
);
2769 qemu_coroutine_enter(co
, acb
);
2771 return &acb
->common
;
2774 static BlockDriverAIOCB
*bdrv_co_aio_readv_em(BlockDriverState
*bs
,
2775 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2776 BlockDriverCompletionFunc
*cb
, void *opaque
)
2778 return bdrv_co_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
,
2782 static BlockDriverAIOCB
*bdrv_co_aio_writev_em(BlockDriverState
*bs
,
2783 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2784 BlockDriverCompletionFunc
*cb
, void *opaque
)
2786 return bdrv_co_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
,
2790 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
2791 BlockDriverCompletionFunc
*cb
, void *opaque
)
2793 BlockDriverAIOCBSync
*acb
;
2795 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2796 acb
->is_write
= 1; /* don't bounce in the completion hadler */
2802 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2805 qemu_bh_schedule(acb
->bh
);
2806 return &acb
->common
;
2809 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
2810 BlockDriverCompletionFunc
*cb
, void *opaque
)
2812 BlockDriverAIOCBSync
*acb
;
2814 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2815 acb
->is_write
= 1; /* don't bounce in the completion handler */
2821 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2824 qemu_bh_schedule(acb
->bh
);
2825 return &acb
->common
;
2828 /**************************************************************/
2829 /* sync block device emulation */
2831 static void bdrv_rw_em_cb(void *opaque
, int ret
)
2833 *(int *)opaque
= ret
;
2836 #define NOT_DONE 0x7fffffff
2838 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
2839 uint8_t *buf
, int nb_sectors
)
2842 BlockDriverAIOCB
*acb
;
2846 async_ret
= NOT_DONE
;
2847 iov
.iov_base
= (void *)buf
;
2848 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2849 qemu_iovec_init_external(&qiov
, &iov
, 1);
2850 acb
= bdrv_aio_readv(bs
, sector_num
, &qiov
, nb_sectors
,
2851 bdrv_rw_em_cb
, &async_ret
);
2857 while (async_ret
== NOT_DONE
) {
2866 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
2867 const uint8_t *buf
, int nb_sectors
)
2870 BlockDriverAIOCB
*acb
;
2874 async_ret
= NOT_DONE
;
2875 iov
.iov_base
= (void *)buf
;
2876 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2877 qemu_iovec_init_external(&qiov
, &iov
, 1);
2878 acb
= bdrv_aio_writev(bs
, sector_num
, &qiov
, nb_sectors
,
2879 bdrv_rw_em_cb
, &async_ret
);
2884 while (async_ret
== NOT_DONE
) {
2892 void bdrv_init(void)
2894 module_call_init(MODULE_INIT_BLOCK
);
2897 void bdrv_init_with_whitelist(void)
2899 use_bdrv_whitelist
= 1;
2903 void *qemu_aio_get(AIOPool
*pool
, BlockDriverState
*bs
,
2904 BlockDriverCompletionFunc
*cb
, void *opaque
)
2906 BlockDriverAIOCB
*acb
;
2908 if (pool
->free_aiocb
) {
2909 acb
= pool
->free_aiocb
;
2910 pool
->free_aiocb
= acb
->next
;
2912 acb
= g_malloc0(pool
->aiocb_size
);
2917 acb
->opaque
= opaque
;
2921 void qemu_aio_release(void *p
)
2923 BlockDriverAIOCB
*acb
= (BlockDriverAIOCB
*)p
;
2924 AIOPool
*pool
= acb
->pool
;
2925 acb
->next
= pool
->free_aiocb
;
2926 pool
->free_aiocb
= acb
;
2929 /**************************************************************/
2930 /* Coroutine block device emulation */
2932 typedef struct CoroutineIOCompletion
{
2933 Coroutine
*coroutine
;
2935 } CoroutineIOCompletion
;
2937 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
2939 CoroutineIOCompletion
*co
= opaque
;
2942 qemu_coroutine_enter(co
->coroutine
, NULL
);
2945 static int coroutine_fn
bdrv_co_io_em(BlockDriverState
*bs
, int64_t sector_num
,
2946 int nb_sectors
, QEMUIOVector
*iov
,
2949 CoroutineIOCompletion co
= {
2950 .coroutine
= qemu_coroutine_self(),
2952 BlockDriverAIOCB
*acb
;
2955 acb
= bdrv_aio_writev(bs
, sector_num
, iov
, nb_sectors
,
2956 bdrv_co_io_em_complete
, &co
);
2958 acb
= bdrv_aio_readv(bs
, sector_num
, iov
, nb_sectors
,
2959 bdrv_co_io_em_complete
, &co
);
2962 trace_bdrv_co_io(is_write
, acb
);
2966 qemu_coroutine_yield();
2971 static int coroutine_fn
bdrv_co_readv_em(BlockDriverState
*bs
,
2972 int64_t sector_num
, int nb_sectors
,
2975 return bdrv_co_io_em(bs
, sector_num
, nb_sectors
, iov
, false);
2978 static int coroutine_fn
bdrv_co_writev_em(BlockDriverState
*bs
,
2979 int64_t sector_num
, int nb_sectors
,
2982 return bdrv_co_io_em(bs
, sector_num
, nb_sectors
, iov
, true);
2985 static int coroutine_fn
bdrv_co_flush_em(BlockDriverState
*bs
)
2987 CoroutineIOCompletion co
= {
2988 .coroutine
= qemu_coroutine_self(),
2990 BlockDriverAIOCB
*acb
;
2992 acb
= bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
2996 qemu_coroutine_yield();
3000 /**************************************************************/
3001 /* removable device support */
3004 * Return TRUE if the media is present
3006 int bdrv_is_inserted(BlockDriverState
*bs
)
3008 BlockDriver
*drv
= bs
->drv
;
3012 if (!drv
->bdrv_is_inserted
)
3013 return !bs
->tray_open
;
3014 ret
= drv
->bdrv_is_inserted(bs
);
3019 * Return TRUE if the media changed since the last call to this
3020 * function. It is currently only used for floppy disks
3022 int bdrv_media_changed(BlockDriverState
*bs
)
3024 BlockDriver
*drv
= bs
->drv
;
3027 if (!drv
|| !drv
->bdrv_media_changed
)
3030 ret
= drv
->bdrv_media_changed(bs
);
3031 if (ret
== -ENOTSUP
)
3032 ret
= bs
->media_changed
;
3033 bs
->media_changed
= 0;
3038 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3040 int bdrv_eject(BlockDriverState
*bs
, int eject_flag
)
3042 BlockDriver
*drv
= bs
->drv
;
3044 if (eject_flag
&& bs
->locked
) {
3048 if (drv
&& drv
->bdrv_eject
) {
3049 drv
->bdrv_eject(bs
, eject_flag
);
3051 bs
->tray_open
= eject_flag
;
3055 int bdrv_is_locked(BlockDriverState
*bs
)
3061 * Lock or unlock the media (if it is locked, the user won't be able
3062 * to eject it manually).
3064 void bdrv_set_locked(BlockDriverState
*bs
, int locked
)
3066 BlockDriver
*drv
= bs
->drv
;
3068 trace_bdrv_set_locked(bs
, locked
);
3070 bs
->locked
= locked
;
3071 if (drv
&& drv
->bdrv_set_locked
) {
3072 drv
->bdrv_set_locked(bs
, locked
);
3076 /* needed for generic scsi interface */
3078 int bdrv_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
3080 BlockDriver
*drv
= bs
->drv
;
3082 if (drv
&& drv
->bdrv_ioctl
)
3083 return drv
->bdrv_ioctl(bs
, req
, buf
);
3087 BlockDriverAIOCB
*bdrv_aio_ioctl(BlockDriverState
*bs
,
3088 unsigned long int req
, void *buf
,
3089 BlockDriverCompletionFunc
*cb
, void *opaque
)
3091 BlockDriver
*drv
= bs
->drv
;
3093 if (drv
&& drv
->bdrv_aio_ioctl
)
3094 return drv
->bdrv_aio_ioctl(bs
, req
, buf
, cb
, opaque
);
3100 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
3102 return qemu_memalign((bs
&& bs
->buffer_alignment
) ? bs
->buffer_alignment
: 512, size
);
3105 void bdrv_set_dirty_tracking(BlockDriverState
*bs
, int enable
)
3107 int64_t bitmap_size
;
3109 bs
->dirty_count
= 0;
3111 if (!bs
->dirty_bitmap
) {
3112 bitmap_size
= (bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
) +
3113 BDRV_SECTORS_PER_DIRTY_CHUNK
* 8 - 1;
3114 bitmap_size
/= BDRV_SECTORS_PER_DIRTY_CHUNK
* 8;
3116 bs
->dirty_bitmap
= g_malloc0(bitmap_size
);
3119 if (bs
->dirty_bitmap
) {
3120 g_free(bs
->dirty_bitmap
);
3121 bs
->dirty_bitmap
= NULL
;
3126 int bdrv_get_dirty(BlockDriverState
*bs
, int64_t sector
)
3128 int64_t chunk
= sector
/ (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK
;
3130 if (bs
->dirty_bitmap
&&
3131 (sector
<< BDRV_SECTOR_BITS
) < bdrv_getlength(bs
)) {
3132 return !!(bs
->dirty_bitmap
[chunk
/ (sizeof(unsigned long) * 8)] &
3133 (1UL << (chunk
% (sizeof(unsigned long) * 8))));
3139 void bdrv_reset_dirty(BlockDriverState
*bs
, int64_t cur_sector
,
3142 set_dirty_bitmap(bs
, cur_sector
, nr_sectors
, 0);
3145 int64_t bdrv_get_dirty_count(BlockDriverState
*bs
)
3147 return bs
->dirty_count
;
3150 void bdrv_set_in_use(BlockDriverState
*bs
, int in_use
)
3152 assert(bs
->in_use
!= in_use
);
3153 bs
->in_use
= in_use
;
3156 int bdrv_in_use(BlockDriverState
*bs
)
3161 int bdrv_img_create(const char *filename
, const char *fmt
,
3162 const char *base_filename
, const char *base_fmt
,
3163 char *options
, uint64_t img_size
, int flags
)
3165 QEMUOptionParameter
*param
= NULL
, *create_options
= NULL
;
3166 QEMUOptionParameter
*backing_fmt
, *backing_file
, *size
;
3167 BlockDriverState
*bs
= NULL
;
3168 BlockDriver
*drv
, *proto_drv
;
3169 BlockDriver
*backing_drv
= NULL
;
3172 /* Find driver and parse its options */
3173 drv
= bdrv_find_format(fmt
);
3175 error_report("Unknown file format '%s'", fmt
);
3180 proto_drv
= bdrv_find_protocol(filename
);
3182 error_report("Unknown protocol '%s'", filename
);
3187 create_options
= append_option_parameters(create_options
,
3188 drv
->create_options
);
3189 create_options
= append_option_parameters(create_options
,
3190 proto_drv
->create_options
);
3192 /* Create parameter list with default values */
3193 param
= parse_option_parameters("", create_options
, param
);
3195 set_option_parameter_int(param
, BLOCK_OPT_SIZE
, img_size
);
3197 /* Parse -o options */
3199 param
= parse_option_parameters(options
, create_options
, param
);
3200 if (param
== NULL
) {
3201 error_report("Invalid options for file format '%s'.", fmt
);
3207 if (base_filename
) {
3208 if (set_option_parameter(param
, BLOCK_OPT_BACKING_FILE
,
3210 error_report("Backing file not supported for file format '%s'",
3218 if (set_option_parameter(param
, BLOCK_OPT_BACKING_FMT
, base_fmt
)) {
3219 error_report("Backing file format not supported for file "
3220 "format '%s'", fmt
);
3226 backing_file
= get_option_parameter(param
, BLOCK_OPT_BACKING_FILE
);
3227 if (backing_file
&& backing_file
->value
.s
) {
3228 if (!strcmp(filename
, backing_file
->value
.s
)) {
3229 error_report("Error: Trying to create an image with the "
3230 "same filename as the backing file");
3236 backing_fmt
= get_option_parameter(param
, BLOCK_OPT_BACKING_FMT
);
3237 if (backing_fmt
&& backing_fmt
->value
.s
) {
3238 backing_drv
= bdrv_find_format(backing_fmt
->value
.s
);
3240 error_report("Unknown backing file format '%s'",
3241 backing_fmt
->value
.s
);
3247 // The size for the image must always be specified, with one exception:
3248 // If we are using a backing file, we can obtain the size from there
3249 size
= get_option_parameter(param
, BLOCK_OPT_SIZE
);
3250 if (size
&& size
->value
.n
== -1) {
3251 if (backing_file
&& backing_file
->value
.s
) {
3257 ret
= bdrv_open(bs
, backing_file
->value
.s
, flags
, backing_drv
);
3259 error_report("Could not open '%s'", backing_file
->value
.s
);
3262 bdrv_get_geometry(bs
, &size
);
3265 snprintf(buf
, sizeof(buf
), "%" PRId64
, size
);
3266 set_option_parameter(param
, BLOCK_OPT_SIZE
, buf
);
3268 error_report("Image creation needs a size parameter");
3274 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
3275 print_option_parameters(param
);
3278 ret
= bdrv_create(drv
, filename
, param
);
3281 if (ret
== -ENOTSUP
) {
3282 error_report("Formatting or formatting option not supported for "
3283 "file format '%s'", fmt
);
3284 } else if (ret
== -EFBIG
) {
3285 error_report("The image size is too large for file format '%s'",
3288 error_report("%s: error while creating %s: %s", filename
, fmt
,
3294 free_option_parameters(create_options
);
3295 free_option_parameters(param
);