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
= qemu_mallocz(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 * Common part for opening disk images and files
443 static int bdrv_open_common(BlockDriverState
*bs
, const char *filename
,
444 int flags
, BlockDriver
*drv
)
451 bs
->total_sectors
= 0;
454 bs
->open_flags
= flags
;
455 /* buffer_alignment defaulted to 512, drivers can change this value */
456 bs
->buffer_alignment
= 512;
458 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
460 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
)) {
465 bs
->opaque
= qemu_mallocz(drv
->instance_size
);
467 if (flags
& BDRV_O_CACHE_WB
)
468 bs
->enable_write_cache
= 1;
471 * Clear flags that are internal to the block layer before opening the
474 open_flags
= flags
& ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
477 * Snapshots should be writable.
479 if (bs
->is_temporary
) {
480 open_flags
|= BDRV_O_RDWR
;
483 /* Open the image, either directly or using a protocol */
484 if (drv
->bdrv_file_open
) {
485 ret
= drv
->bdrv_file_open(bs
, filename
, open_flags
);
487 ret
= bdrv_file_open(&bs
->file
, filename
, open_flags
);
489 ret
= drv
->bdrv_open(bs
, open_flags
);
497 bs
->keep_read_only
= bs
->read_only
= !(open_flags
& BDRV_O_RDWR
);
499 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
505 if (bs
->is_temporary
) {
513 bdrv_delete(bs
->file
);
516 qemu_free(bs
->opaque
);
523 * Opens a file using a protocol (file, host_device, nbd, ...)
525 int bdrv_file_open(BlockDriverState
**pbs
, const char *filename
, int flags
)
527 BlockDriverState
*bs
;
531 drv
= bdrv_find_protocol(filename
);
537 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
548 * Opens a disk image (raw, qcow2, vmdk, ...)
550 int bdrv_open(BlockDriverState
*bs
, const char *filename
, int flags
,
555 if (flags
& BDRV_O_SNAPSHOT
) {
556 BlockDriverState
*bs1
;
559 BlockDriver
*bdrv_qcow2
;
560 QEMUOptionParameter
*options
;
561 char tmp_filename
[PATH_MAX
];
562 char backing_filename
[PATH_MAX
];
564 /* if snapshot, we create a temporary backing file and open it
565 instead of opening 'filename' directly */
567 /* if there is a backing file, use it */
569 ret
= bdrv_open(bs1
, filename
, 0, drv
);
574 total_size
= bdrv_getlength(bs1
) & BDRV_SECTOR_MASK
;
576 if (bs1
->drv
&& bs1
->drv
->protocol_name
)
581 get_tmp_filename(tmp_filename
, sizeof(tmp_filename
));
583 /* Real path is meaningless for protocols */
585 snprintf(backing_filename
, sizeof(backing_filename
),
587 else if (!realpath(filename
, backing_filename
))
590 bdrv_qcow2
= bdrv_find_format("qcow2");
591 options
= parse_option_parameters("", bdrv_qcow2
->create_options
, NULL
);
593 set_option_parameter_int(options
, BLOCK_OPT_SIZE
, total_size
);
594 set_option_parameter(options
, BLOCK_OPT_BACKING_FILE
, backing_filename
);
596 set_option_parameter(options
, BLOCK_OPT_BACKING_FMT
,
600 ret
= bdrv_create(bdrv_qcow2
, tmp_filename
, options
);
601 free_option_parameters(options
);
606 filename
= tmp_filename
;
608 bs
->is_temporary
= 1;
611 /* Find the right image format driver */
613 ret
= find_image_format(filename
, &drv
);
617 goto unlink_and_fail
;
621 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
623 goto unlink_and_fail
;
626 /* If there is a backing file, use it */
627 if ((flags
& BDRV_O_NO_BACKING
) == 0 && bs
->backing_file
[0] != '\0') {
628 char backing_filename
[PATH_MAX
];
630 BlockDriver
*back_drv
= NULL
;
632 char imaging_filename
[PATH_MAX
];
634 BlockDriver
*cow_drv
= NULL
;
636 bs
->backing_hd
= bdrv_new("");
638 if (path_has_protocol(bs
->backing_file
)) {
639 pstrcpy(backing_filename
, sizeof(backing_filename
),
642 path_combine(backing_filename
, sizeof(backing_filename
),
643 filename
, bs
->backing_file
);
646 if (bs
->backing_format
[0] != '\0') {
647 back_drv
= bdrv_find_format(bs
->backing_format
);
650 /* backing files always opened read-only */
652 flags
& ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
654 ret
= bdrv_open(bs
->backing_hd
, backing_filename
, back_flags
, back_drv
);
659 if (bs
->is_temporary
) {
660 bs
->backing_hd
->keep_read_only
= !(flags
& BDRV_O_RDWR
);
662 /* base image inherits from "parent" */
663 bs
->backing_hd
->keep_read_only
= bs
->keep_read_only
;
666 /* If there is a image_file, must be together with backing_file */
667 if (bs
->image_file
[0] != '\0') {
668 bs
->cow_hd
= bdrv_new("");
669 if (path_has_protocol(bs
->image_file
)) {
670 pstrcpy(imaging_filename
, sizeof(imaging_filename
),
673 path_combine(imaging_filename
, sizeof(imaging_filename
),
674 filename
, bs
->image_file
);
677 cow_drv
= bdrv_find_format("add-cow");
680 (flags
& (~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
))) | BDRV_O_RDWR
;
681 bs
->cow_hd
->keep_read_only
= 0;
683 ret
= bdrv_open(bs
->cow_hd
, imaging_filename
, cow_flags
, back_drv
);
691 if (!bdrv_key_required(bs
)) {
692 /* call the change callback */
693 bs
->media_changed
= 1;
695 bs
->change_cb(bs
->change_opaque
, CHANGE_MEDIA
);
701 if (bs
->is_temporary
) {
707 void bdrv_close(BlockDriverState
*bs
)
710 if (bs
== bs_snapshots
) {
713 if (bs
->backing_hd
) {
714 bdrv_delete(bs
->backing_hd
);
715 bs
->backing_hd
= NULL
;
718 bdrv_delete(bs
->cow_hd
);
722 bs
->drv
->bdrv_close(bs
);
723 qemu_free(bs
->opaque
);
725 if (bs
->is_temporary
) {
726 unlink(bs
->filename
);
732 if (bs
->file
!= NULL
) {
733 bdrv_close(bs
->file
);
736 /* call the change callback */
737 bs
->media_changed
= 1;
739 bs
->change_cb(bs
->change_opaque
, CHANGE_MEDIA
);
743 void bdrv_close_all(void)
745 BlockDriverState
*bs
;
747 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
752 /* make a BlockDriverState anonymous by removing from bdrv_state list.
753 Also, NULL terminate the device_name to prevent double remove */
754 void bdrv_make_anon(BlockDriverState
*bs
)
756 if (bs
->device_name
[0] != '\0') {
757 QTAILQ_REMOVE(&bdrv_states
, bs
, list
);
759 bs
->device_name
[0] = '\0';
762 void bdrv_delete(BlockDriverState
*bs
)
766 /* remove from list, if necessary */
770 if (bs
->file
!= NULL
) {
771 bdrv_delete(bs
->file
);
774 assert(bs
!= bs_snapshots
);
778 int bdrv_attach(BlockDriverState
*bs
, DeviceState
*qdev
)
787 void bdrv_detach(BlockDriverState
*bs
, DeviceState
*qdev
)
789 assert(bs
->peer
== qdev
);
791 bs
->change_cb
= NULL
;
792 bs
->change_opaque
= NULL
;
795 DeviceState
*bdrv_get_attached(BlockDriverState
*bs
)
801 * Run consistency checks on an image
803 * Returns 0 if the check could be completed (it doesn't mean that the image is
804 * free of errors) or -errno when an internal error occurred. The results of the
805 * check are stored in res.
807 int bdrv_check(BlockDriverState
*bs
, BdrvCheckResult
*res
)
809 if (bs
->drv
->bdrv_check
== NULL
) {
813 memset(res
, 0, sizeof(*res
));
814 return bs
->drv
->bdrv_check(bs
, res
);
817 #define COMMIT_BUF_SECTORS 2048
819 /* commit COW file into the raw image */
820 int bdrv_commit(BlockDriverState
*bs
)
822 BlockDriver
*drv
= bs
->drv
;
823 BlockDriver
*backing_drv
;
824 int64_t sector
, total_sectors
;
825 int n
, ro
, open_flags
;
826 int ret
= 0, rw_ret
= 0;
829 BlockDriverState
*bs_rw
, *bs_ro
;
834 if (!bs
->backing_hd
) {
838 if (bs
->backing_hd
->keep_read_only
) {
842 backing_drv
= bs
->backing_hd
->drv
;
843 ro
= bs
->backing_hd
->read_only
;
844 strncpy(filename
, bs
->backing_hd
->filename
, sizeof(filename
));
845 open_flags
= bs
->backing_hd
->open_flags
;
849 bdrv_delete(bs
->backing_hd
);
850 bs
->backing_hd
= NULL
;
851 bs_rw
= bdrv_new("");
852 rw_ret
= bdrv_open(bs_rw
, filename
, open_flags
| BDRV_O_RDWR
,
856 /* try to re-open read-only */
857 bs_ro
= bdrv_new("");
858 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
,
862 /* drive not functional anymore */
866 bs
->backing_hd
= bs_ro
;
869 bs
->backing_hd
= bs_rw
;
872 total_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
873 buf
= qemu_malloc(COMMIT_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
875 for (sector
= 0; sector
< total_sectors
; sector
+= n
) {
876 if (drv
->bdrv_is_allocated(bs
, sector
, COMMIT_BUF_SECTORS
, &n
)) {
878 if (bdrv_read(bs
, sector
, buf
, n
) != 0) {
883 if (bdrv_write(bs
->backing_hd
, sector
, buf
, n
) != 0) {
890 if (drv
->bdrv_make_empty
) {
891 ret
= drv
->bdrv_make_empty(bs
);
896 * Make sure all data we wrote to the backing device is actually
900 bdrv_flush(bs
->backing_hd
);
907 bdrv_delete(bs
->backing_hd
);
908 bs
->backing_hd
= NULL
;
909 bs_ro
= bdrv_new("");
910 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
,
914 /* drive not functional anymore */
918 bs
->backing_hd
= bs_ro
;
919 bs
->backing_hd
->keep_read_only
= 0;
925 void bdrv_commit_all(void)
927 BlockDriverState
*bs
;
929 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
937 * -EINVAL - backing format specified, but no file
938 * -ENOSPC - can't update the backing file because no space is left in the
940 * -ENOTSUP - format driver doesn't support changing the backing file
942 int bdrv_change_backing_file(BlockDriverState
*bs
,
943 const char *backing_file
, const char *backing_fmt
)
945 BlockDriver
*drv
= bs
->drv
;
947 if (drv
->bdrv_change_backing_file
!= NULL
) {
948 return drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
954 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
959 if (!bdrv_is_inserted(bs
))
965 len
= bdrv_getlength(bs
);
970 if ((offset
> len
) || (len
- offset
< size
))
976 static int bdrv_check_request(BlockDriverState
*bs
, int64_t sector_num
,
979 return bdrv_check_byte_request(bs
, sector_num
* BDRV_SECTOR_SIZE
,
980 nb_sectors
* BDRV_SECTOR_SIZE
);
983 static inline bool bdrv_has_async_rw(BlockDriver
*drv
)
985 return drv
->bdrv_co_readv
!= bdrv_co_readv_em
986 || drv
->bdrv_aio_readv
!= bdrv_aio_readv_em
;
989 static inline bool bdrv_has_async_flush(BlockDriver
*drv
)
991 return drv
->bdrv_aio_flush
!= bdrv_aio_flush_em
;
994 /* return < 0 if error. See bdrv_write() for the return codes */
995 int bdrv_read(BlockDriverState
*bs
, int64_t sector_num
,
996 uint8_t *buf
, int nb_sectors
)
998 BlockDriver
*drv
= bs
->drv
;
1003 if (bdrv_has_async_rw(drv
) && qemu_in_coroutine()) {
1005 struct iovec iov
= {
1006 .iov_base
= (void *)buf
,
1007 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
1010 qemu_iovec_init_external(&qiov
, &iov
, 1);
1011 return bdrv_co_readv(bs
, sector_num
, nb_sectors
, &qiov
);
1014 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1017 return drv
->bdrv_read(bs
, sector_num
, buf
, nb_sectors
);
1020 static void set_dirty_bitmap(BlockDriverState
*bs
, int64_t sector_num
,
1021 int nb_sectors
, int dirty
)
1024 unsigned long val
, idx
, bit
;
1026 start
= sector_num
/ BDRV_SECTORS_PER_DIRTY_CHUNK
;
1027 end
= (sector_num
+ nb_sectors
- 1) / BDRV_SECTORS_PER_DIRTY_CHUNK
;
1029 for (; start
<= end
; start
++) {
1030 idx
= start
/ (sizeof(unsigned long) * 8);
1031 bit
= start
% (sizeof(unsigned long) * 8);
1032 val
= bs
->dirty_bitmap
[idx
];
1034 if (!(val
& (1UL << bit
))) {
1039 if (val
& (1UL << bit
)) {
1041 val
&= ~(1UL << bit
);
1044 bs
->dirty_bitmap
[idx
] = val
;
1048 /* Return < 0 if error. Important errors are:
1049 -EIO generic I/O error (may happen for all errors)
1050 -ENOMEDIUM No media inserted.
1051 -EINVAL Invalid sector number or nb_sectors
1052 -EACCES Trying to write a read-only device
1054 int bdrv_write(BlockDriverState
*bs
, int64_t sector_num
,
1055 const uint8_t *buf
, int nb_sectors
)
1057 BlockDriver
*drv
= bs
->drv
;
1062 if (bdrv_has_async_rw(drv
) && qemu_in_coroutine()) {
1064 struct iovec iov
= {
1065 .iov_base
= (void *)buf
,
1066 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
1069 qemu_iovec_init_external(&qiov
, &iov
, 1);
1070 return bdrv_co_writev(bs
, sector_num
, nb_sectors
, &qiov
);
1075 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1078 if (bs
->dirty_bitmap
) {
1079 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1082 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1083 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1086 return drv
->bdrv_write(bs
, sector_num
, buf
, nb_sectors
);
1089 int bdrv_pread(BlockDriverState
*bs
, int64_t offset
,
1090 void *buf
, int count1
)
1092 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1093 int len
, nb_sectors
, count
;
1098 /* first read to align to sector start */
1099 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1102 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1104 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1106 memcpy(buf
, tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), len
);
1114 /* read the sectors "in place" */
1115 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1116 if (nb_sectors
> 0) {
1117 if ((ret
= bdrv_read(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1119 sector_num
+= nb_sectors
;
1120 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1125 /* add data from the last sector */
1127 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1129 memcpy(buf
, tmp_buf
, count
);
1134 int bdrv_pwrite(BlockDriverState
*bs
, int64_t offset
,
1135 const void *buf
, int count1
)
1137 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1138 int len
, nb_sectors
, count
;
1143 /* first write to align to sector start */
1144 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1147 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1149 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1151 memcpy(tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), buf
, len
);
1152 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1161 /* write the sectors "in place" */
1162 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1163 if (nb_sectors
> 0) {
1164 if ((ret
= bdrv_write(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1166 sector_num
+= nb_sectors
;
1167 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1172 /* add data from the last sector */
1174 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1176 memcpy(tmp_buf
, buf
, count
);
1177 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1184 * Writes to the file and ensures that no writes are reordered across this
1185 * request (acts as a barrier)
1187 * Returns 0 on success, -errno in error cases.
1189 int bdrv_pwrite_sync(BlockDriverState
*bs
, int64_t offset
,
1190 const void *buf
, int count
)
1194 ret
= bdrv_pwrite(bs
, offset
, buf
, count
);
1199 /* No flush needed for cache=writethrough, it uses O_DSYNC */
1200 if ((bs
->open_flags
& BDRV_O_CACHE_MASK
) != 0) {
1207 int coroutine_fn
bdrv_co_readv(BlockDriverState
*bs
, int64_t sector_num
,
1208 int nb_sectors
, QEMUIOVector
*qiov
)
1210 BlockDriver
*drv
= bs
->drv
;
1212 trace_bdrv_co_readv(bs
, sector_num
, nb_sectors
);
1217 if (bdrv_check_request(bs
, sector_num
, nb_sectors
)) {
1221 return drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1224 int coroutine_fn
bdrv_co_writev(BlockDriverState
*bs
, int64_t sector_num
,
1225 int nb_sectors
, QEMUIOVector
*qiov
)
1227 BlockDriver
*drv
= bs
->drv
;
1229 trace_bdrv_co_writev(bs
, sector_num
, nb_sectors
);
1234 if (bs
->read_only
) {
1237 if (bdrv_check_request(bs
, sector_num
, nb_sectors
)) {
1241 if (bs
->dirty_bitmap
) {
1242 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1245 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1246 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1249 return drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
);
1253 * Truncate file to 'offset' bytes (needed only for file protocols)
1255 int bdrv_truncate(BlockDriverState
*bs
, int64_t offset
)
1257 BlockDriver
*drv
= bs
->drv
;
1261 if (!drv
->bdrv_truncate
)
1265 if (bdrv_in_use(bs
))
1267 ret
= drv
->bdrv_truncate(bs
, offset
);
1269 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
1270 if (bs
->change_cb
) {
1271 bs
->change_cb(bs
->change_opaque
, CHANGE_SIZE
);
1278 * Length of a allocated file in bytes. Sparse files are counted by actual
1279 * allocated space. Return < 0 if error or unknown.
1281 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
1283 BlockDriver
*drv
= bs
->drv
;
1287 if (drv
->bdrv_get_allocated_file_size
) {
1288 return drv
->bdrv_get_allocated_file_size(bs
);
1291 return bdrv_get_allocated_file_size(bs
->file
);
1297 * Length of a file in bytes. Return < 0 if error or unknown.
1299 int64_t bdrv_getlength(BlockDriverState
*bs
)
1301 BlockDriver
*drv
= bs
->drv
;
1305 if (bs
->growable
|| bs
->removable
) {
1306 if (drv
->bdrv_getlength
) {
1307 return drv
->bdrv_getlength(bs
);
1310 return bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1313 /* return 0 as number of sectors if no device present or error */
1314 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
1317 length
= bdrv_getlength(bs
);
1321 length
= length
>> BDRV_SECTOR_BITS
;
1322 *nb_sectors_ptr
= length
;
1326 uint8_t boot_ind
; /* 0x80 - active */
1327 uint8_t head
; /* starting head */
1328 uint8_t sector
; /* starting sector */
1329 uint8_t cyl
; /* starting cylinder */
1330 uint8_t sys_ind
; /* What partition type */
1331 uint8_t end_head
; /* end head */
1332 uint8_t end_sector
; /* end sector */
1333 uint8_t end_cyl
; /* end cylinder */
1334 uint32_t start_sect
; /* starting sector counting from 0 */
1335 uint32_t nr_sects
; /* nr of sectors in partition */
1336 } __attribute__((packed
));
1338 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1339 static int guess_disk_lchs(BlockDriverState
*bs
,
1340 int *pcylinders
, int *pheads
, int *psectors
)
1342 uint8_t buf
[BDRV_SECTOR_SIZE
];
1343 int ret
, i
, heads
, sectors
, cylinders
;
1344 struct partition
*p
;
1346 uint64_t nb_sectors
;
1348 bdrv_get_geometry(bs
, &nb_sectors
);
1350 ret
= bdrv_read(bs
, 0, buf
, 1);
1353 /* test msdos magic */
1354 if (buf
[510] != 0x55 || buf
[511] != 0xaa)
1356 for(i
= 0; i
< 4; i
++) {
1357 p
= ((struct partition
*)(buf
+ 0x1be)) + i
;
1358 nr_sects
= le32_to_cpu(p
->nr_sects
);
1359 if (nr_sects
&& p
->end_head
) {
1360 /* We make the assumption that the partition terminates on
1361 a cylinder boundary */
1362 heads
= p
->end_head
+ 1;
1363 sectors
= p
->end_sector
& 63;
1366 cylinders
= nb_sectors
/ (heads
* sectors
);
1367 if (cylinders
< 1 || cylinders
> 16383)
1370 *psectors
= sectors
;
1371 *pcylinders
= cylinders
;
1373 printf("guessed geometry: LCHS=%d %d %d\n",
1374 cylinders
, heads
, sectors
);
1382 void bdrv_guess_geometry(BlockDriverState
*bs
, int *pcyls
, int *pheads
, int *psecs
)
1384 int translation
, lba_detected
= 0;
1385 int cylinders
, heads
, secs
;
1386 uint64_t nb_sectors
;
1388 /* if a geometry hint is available, use it */
1389 bdrv_get_geometry(bs
, &nb_sectors
);
1390 bdrv_get_geometry_hint(bs
, &cylinders
, &heads
, &secs
);
1391 translation
= bdrv_get_translation_hint(bs
);
1392 if (cylinders
!= 0) {
1397 if (guess_disk_lchs(bs
, &cylinders
, &heads
, &secs
) == 0) {
1399 /* if heads > 16, it means that a BIOS LBA
1400 translation was active, so the default
1401 hardware geometry is OK */
1403 goto default_geometry
;
1408 /* disable any translation to be in sync with
1409 the logical geometry */
1410 if (translation
== BIOS_ATA_TRANSLATION_AUTO
) {
1411 bdrv_set_translation_hint(bs
,
1412 BIOS_ATA_TRANSLATION_NONE
);
1417 /* if no geometry, use a standard physical disk geometry */
1418 cylinders
= nb_sectors
/ (16 * 63);
1420 if (cylinders
> 16383)
1422 else if (cylinders
< 2)
1427 if ((lba_detected
== 1) && (translation
== BIOS_ATA_TRANSLATION_AUTO
)) {
1428 if ((*pcyls
* *pheads
) <= 131072) {
1429 bdrv_set_translation_hint(bs
,
1430 BIOS_ATA_TRANSLATION_LARGE
);
1432 bdrv_set_translation_hint(bs
,
1433 BIOS_ATA_TRANSLATION_LBA
);
1437 bdrv_set_geometry_hint(bs
, *pcyls
, *pheads
, *psecs
);
1441 void bdrv_set_geometry_hint(BlockDriverState
*bs
,
1442 int cyls
, int heads
, int secs
)
1449 void bdrv_set_translation_hint(BlockDriverState
*bs
, int translation
)
1451 bs
->translation
= translation
;
1454 void bdrv_get_geometry_hint(BlockDriverState
*bs
,
1455 int *pcyls
, int *pheads
, int *psecs
)
1458 *pheads
= bs
->heads
;
1462 /* Recognize floppy formats */
1463 typedef struct FDFormat
{
1470 static const FDFormat fd_formats
[] = {
1471 /* First entry is default format */
1472 /* 1.44 MB 3"1/2 floppy disks */
1473 { FDRIVE_DRV_144
, 18, 80, 1, },
1474 { FDRIVE_DRV_144
, 20, 80, 1, },
1475 { FDRIVE_DRV_144
, 21, 80, 1, },
1476 { FDRIVE_DRV_144
, 21, 82, 1, },
1477 { FDRIVE_DRV_144
, 21, 83, 1, },
1478 { FDRIVE_DRV_144
, 22, 80, 1, },
1479 { FDRIVE_DRV_144
, 23, 80, 1, },
1480 { FDRIVE_DRV_144
, 24, 80, 1, },
1481 /* 2.88 MB 3"1/2 floppy disks */
1482 { FDRIVE_DRV_288
, 36, 80, 1, },
1483 { FDRIVE_DRV_288
, 39, 80, 1, },
1484 { FDRIVE_DRV_288
, 40, 80, 1, },
1485 { FDRIVE_DRV_288
, 44, 80, 1, },
1486 { FDRIVE_DRV_288
, 48, 80, 1, },
1487 /* 720 kB 3"1/2 floppy disks */
1488 { FDRIVE_DRV_144
, 9, 80, 1, },
1489 { FDRIVE_DRV_144
, 10, 80, 1, },
1490 { FDRIVE_DRV_144
, 10, 82, 1, },
1491 { FDRIVE_DRV_144
, 10, 83, 1, },
1492 { FDRIVE_DRV_144
, 13, 80, 1, },
1493 { FDRIVE_DRV_144
, 14, 80, 1, },
1494 /* 1.2 MB 5"1/4 floppy disks */
1495 { FDRIVE_DRV_120
, 15, 80, 1, },
1496 { FDRIVE_DRV_120
, 18, 80, 1, },
1497 { FDRIVE_DRV_120
, 18, 82, 1, },
1498 { FDRIVE_DRV_120
, 18, 83, 1, },
1499 { FDRIVE_DRV_120
, 20, 80, 1, },
1500 /* 720 kB 5"1/4 floppy disks */
1501 { FDRIVE_DRV_120
, 9, 80, 1, },
1502 { FDRIVE_DRV_120
, 11, 80, 1, },
1503 /* 360 kB 5"1/4 floppy disks */
1504 { FDRIVE_DRV_120
, 9, 40, 1, },
1505 { FDRIVE_DRV_120
, 9, 40, 0, },
1506 { FDRIVE_DRV_120
, 10, 41, 1, },
1507 { FDRIVE_DRV_120
, 10, 42, 1, },
1508 /* 320 kB 5"1/4 floppy disks */
1509 { FDRIVE_DRV_120
, 8, 40, 1, },
1510 { FDRIVE_DRV_120
, 8, 40, 0, },
1511 /* 360 kB must match 5"1/4 better than 3"1/2... */
1512 { FDRIVE_DRV_144
, 9, 80, 0, },
1514 { FDRIVE_DRV_NONE
, -1, -1, 0, },
1517 void bdrv_get_floppy_geometry_hint(BlockDriverState
*bs
, int *nb_heads
,
1518 int *max_track
, int *last_sect
,
1519 FDriveType drive_in
, FDriveType
*drive
)
1521 const FDFormat
*parse
;
1522 uint64_t nb_sectors
, size
;
1523 int i
, first_match
, match
;
1525 bdrv_get_geometry_hint(bs
, nb_heads
, max_track
, last_sect
);
1526 if (*nb_heads
!= 0 && *max_track
!= 0 && *last_sect
!= 0) {
1527 /* User defined disk */
1529 bdrv_get_geometry(bs
, &nb_sectors
);
1532 for (i
= 0; ; i
++) {
1533 parse
= &fd_formats
[i
];
1534 if (parse
->drive
== FDRIVE_DRV_NONE
) {
1537 if (drive_in
== parse
->drive
||
1538 drive_in
== FDRIVE_DRV_NONE
) {
1539 size
= (parse
->max_head
+ 1) * parse
->max_track
*
1541 if (nb_sectors
== size
) {
1545 if (first_match
== -1) {
1551 if (first_match
== -1) {
1554 match
= first_match
;
1556 parse
= &fd_formats
[match
];
1558 *nb_heads
= parse
->max_head
+ 1;
1559 *max_track
= parse
->max_track
;
1560 *last_sect
= parse
->last_sect
;
1561 *drive
= parse
->drive
;
1565 int bdrv_get_translation_hint(BlockDriverState
*bs
)
1567 return bs
->translation
;
1570 void bdrv_set_on_error(BlockDriverState
*bs
, BlockErrorAction on_read_error
,
1571 BlockErrorAction on_write_error
)
1573 bs
->on_read_error
= on_read_error
;
1574 bs
->on_write_error
= on_write_error
;
1577 BlockErrorAction
bdrv_get_on_error(BlockDriverState
*bs
, int is_read
)
1579 return is_read
? bs
->on_read_error
: bs
->on_write_error
;
1582 void bdrv_set_removable(BlockDriverState
*bs
, int removable
)
1584 bs
->removable
= removable
;
1585 if (removable
&& bs
== bs_snapshots
) {
1586 bs_snapshots
= NULL
;
1590 int bdrv_is_removable(BlockDriverState
*bs
)
1592 return bs
->removable
;
1595 int bdrv_is_read_only(BlockDriverState
*bs
)
1597 return bs
->read_only
;
1600 int bdrv_is_sg(BlockDriverState
*bs
)
1605 int bdrv_enable_write_cache(BlockDriverState
*bs
)
1607 return bs
->enable_write_cache
;
1610 /* XXX: no longer used */
1611 void bdrv_set_change_cb(BlockDriverState
*bs
,
1612 void (*change_cb
)(void *opaque
, int reason
),
1615 bs
->change_cb
= change_cb
;
1616 bs
->change_opaque
= opaque
;
1619 int bdrv_is_encrypted(BlockDriverState
*bs
)
1621 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1623 return bs
->encrypted
;
1626 int bdrv_key_required(BlockDriverState
*bs
)
1628 BlockDriverState
*backing_hd
= bs
->backing_hd
;
1630 if (backing_hd
&& backing_hd
->encrypted
&& !backing_hd
->valid_key
)
1632 return (bs
->encrypted
&& !bs
->valid_key
);
1635 int bdrv_set_key(BlockDriverState
*bs
, const char *key
)
1638 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
) {
1639 ret
= bdrv_set_key(bs
->backing_hd
, key
);
1645 if (!bs
->encrypted
) {
1647 } else if (!bs
->drv
|| !bs
->drv
->bdrv_set_key
) {
1650 ret
= bs
->drv
->bdrv_set_key(bs
, key
);
1653 } else if (!bs
->valid_key
) {
1655 /* call the change callback now, we skipped it on open */
1656 bs
->media_changed
= 1;
1658 bs
->change_cb(bs
->change_opaque
, CHANGE_MEDIA
);
1663 void bdrv_get_format(BlockDriverState
*bs
, char *buf
, int buf_size
)
1668 pstrcpy(buf
, buf_size
, bs
->drv
->format_name
);
1672 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
1677 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
1678 it(opaque
, drv
->format_name
);
1682 BlockDriverState
*bdrv_find(const char *name
)
1684 BlockDriverState
*bs
;
1686 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1687 if (!strcmp(name
, bs
->device_name
)) {
1694 BlockDriverState
*bdrv_next(BlockDriverState
*bs
)
1697 return QTAILQ_FIRST(&bdrv_states
);
1699 return QTAILQ_NEXT(bs
, list
);
1702 void bdrv_iterate(void (*it
)(void *opaque
, BlockDriverState
*bs
), void *opaque
)
1704 BlockDriverState
*bs
;
1706 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1711 const char *bdrv_get_device_name(BlockDriverState
*bs
)
1713 return bs
->device_name
;
1716 int bdrv_flush(BlockDriverState
*bs
)
1718 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
1722 if (bs
->drv
&& bdrv_has_async_flush(bs
->drv
) && qemu_in_coroutine()) {
1723 return bdrv_co_flush_em(bs
);
1726 if (bs
->drv
&& bs
->drv
->bdrv_flush
) {
1727 return bs
->drv
->bdrv_flush(bs
);
1731 * Some block drivers always operate in either writethrough or unsafe mode
1732 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1733 * the server works (because the behaviour is hardcoded or depends on
1734 * server-side configuration), so we can't ensure that everything is safe
1735 * on disk. Returning an error doesn't work because that would break guests
1736 * even if the server operates in writethrough mode.
1738 * Let's hope the user knows what he's doing.
1743 void bdrv_flush_all(void)
1745 BlockDriverState
*bs
;
1747 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1748 if (bs
->drv
&& !bdrv_is_read_only(bs
) &&
1749 (!bdrv_is_removable(bs
) || bdrv_is_inserted(bs
))) {
1755 int bdrv_has_zero_init(BlockDriverState
*bs
)
1759 if (bs
->drv
->bdrv_has_zero_init
) {
1760 return bs
->drv
->bdrv_has_zero_init(bs
);
1766 int bdrv_discard(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
)
1771 if (!bs
->drv
->bdrv_discard
) {
1774 return bs
->drv
->bdrv_discard(bs
, sector_num
, nb_sectors
);
1778 * Returns true iff the specified sector is present in the disk image. Drivers
1779 * not implementing the functionality are assumed to not support backing files,
1780 * hence all their sectors are reported as allocated.
1782 * 'pnum' is set to the number of sectors (including and immediately following
1783 * the specified sector) that are known to be in the same
1784 * allocated/unallocated state.
1786 * 'nb_sectors' is the max value 'pnum' should be set to.
1788 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
,
1792 if (!bs
->drv
->bdrv_is_allocated
) {
1793 if (sector_num
>= bs
->total_sectors
) {
1797 n
= bs
->total_sectors
- sector_num
;
1798 *pnum
= (n
< nb_sectors
) ? (n
) : (nb_sectors
);
1801 return bs
->drv
->bdrv_is_allocated(bs
, sector_num
, nb_sectors
, pnum
);
1804 void bdrv_mon_event(const BlockDriverState
*bdrv
,
1805 BlockMonEventAction action
, int is_read
)
1808 const char *action_str
;
1811 case BDRV_ACTION_REPORT
:
1812 action_str
= "report";
1814 case BDRV_ACTION_IGNORE
:
1815 action_str
= "ignore";
1817 case BDRV_ACTION_STOP
:
1818 action_str
= "stop";
1824 data
= qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1827 is_read
? "read" : "write");
1828 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR
, data
);
1830 qobject_decref(data
);
1833 static void bdrv_print_dict(QObject
*obj
, void *opaque
)
1836 Monitor
*mon
= opaque
;
1838 bs_dict
= qobject_to_qdict(obj
);
1840 monitor_printf(mon
, "%s: removable=%d",
1841 qdict_get_str(bs_dict
, "device"),
1842 qdict_get_bool(bs_dict
, "removable"));
1844 if (qdict_get_bool(bs_dict
, "removable")) {
1845 monitor_printf(mon
, " locked=%d", qdict_get_bool(bs_dict
, "locked"));
1848 if (qdict_haskey(bs_dict
, "inserted")) {
1849 QDict
*qdict
= qobject_to_qdict(qdict_get(bs_dict
, "inserted"));
1851 monitor_printf(mon
, " file=");
1852 monitor_print_filename(mon
, qdict_get_str(qdict
, "file"));
1853 if (qdict_haskey(qdict
, "backing_file")) {
1854 monitor_printf(mon
, " backing_file=");
1855 monitor_print_filename(mon
, qdict_get_str(qdict
, "backing_file"));
1857 monitor_printf(mon
, " ro=%d drv=%s encrypted=%d",
1858 qdict_get_bool(qdict
, "ro"),
1859 qdict_get_str(qdict
, "drv"),
1860 qdict_get_bool(qdict
, "encrypted"));
1862 monitor_printf(mon
, " [not inserted]");
1865 monitor_printf(mon
, "\n");
1868 void bdrv_info_print(Monitor
*mon
, const QObject
*data
)
1870 qlist_iter(qobject_to_qlist(data
), bdrv_print_dict
, mon
);
1873 void bdrv_info(Monitor
*mon
, QObject
**ret_data
)
1876 BlockDriverState
*bs
;
1878 bs_list
= qlist_new();
1880 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1883 bs_obj
= qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
1884 "'removable': %i, 'locked': %i }",
1885 bs
->device_name
, bs
->removable
,
1890 QDict
*bs_dict
= qobject_to_qdict(bs_obj
);
1892 obj
= qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1893 "'encrypted': %i }",
1894 bs
->filename
, bs
->read_only
,
1895 bs
->drv
->format_name
,
1896 bdrv_is_encrypted(bs
));
1897 if (bs
->backing_file
[0] != '\0') {
1898 QDict
*qdict
= qobject_to_qdict(obj
);
1899 qdict_put(qdict
, "backing_file",
1900 qstring_from_str(bs
->backing_file
));
1903 qdict_put_obj(bs_dict
, "inserted", obj
);
1905 qlist_append_obj(bs_list
, bs_obj
);
1908 *ret_data
= QOBJECT(bs_list
);
1911 static void bdrv_stats_iter(QObject
*data
, void *opaque
)
1914 Monitor
*mon
= opaque
;
1916 qdict
= qobject_to_qdict(data
);
1917 monitor_printf(mon
, "%s:", qdict_get_str(qdict
, "device"));
1919 qdict
= qobject_to_qdict(qdict_get(qdict
, "stats"));
1920 monitor_printf(mon
, " rd_bytes=%" PRId64
1921 " wr_bytes=%" PRId64
1922 " rd_operations=%" PRId64
1923 " wr_operations=%" PRId64
1925 qdict_get_int(qdict
, "rd_bytes"),
1926 qdict_get_int(qdict
, "wr_bytes"),
1927 qdict_get_int(qdict
, "rd_operations"),
1928 qdict_get_int(qdict
, "wr_operations"));
1931 void bdrv_stats_print(Monitor
*mon
, const QObject
*data
)
1933 qlist_iter(qobject_to_qlist(data
), bdrv_stats_iter
, mon
);
1936 static QObject
* bdrv_info_stats_bs(BlockDriverState
*bs
)
1941 res
= qobject_from_jsonf("{ 'stats': {"
1942 "'rd_bytes': %" PRId64
","
1943 "'wr_bytes': %" PRId64
","
1944 "'rd_operations': %" PRId64
","
1945 "'wr_operations': %" PRId64
","
1946 "'wr_highest_offset': %" PRId64
1948 bs
->rd_bytes
, bs
->wr_bytes
,
1949 bs
->rd_ops
, bs
->wr_ops
,
1950 bs
->wr_highest_sector
*
1951 (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 void bdrv_get_image_filename(BlockDriverState
*bs
,
2003 char *filename
, int filename_size
)
2005 if (!bs
->image_file
) {
2006 pstrcpy(filename
, filename_size
, "");
2008 pstrcpy(filename
, filename_size
, bs
->image_file
);
2012 int bdrv_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
2013 const uint8_t *buf
, int nb_sectors
)
2015 BlockDriver
*drv
= bs
->drv
;
2018 if (!drv
->bdrv_write_compressed
)
2020 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2023 if (bs
->dirty_bitmap
) {
2024 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
2027 return drv
->bdrv_write_compressed(bs
, sector_num
, buf
, nb_sectors
);
2030 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2032 BlockDriver
*drv
= bs
->drv
;
2035 if (!drv
->bdrv_get_info
)
2037 memset(bdi
, 0, sizeof(*bdi
));
2038 return drv
->bdrv_get_info(bs
, bdi
);
2041 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2042 int64_t pos
, int size
)
2044 BlockDriver
*drv
= bs
->drv
;
2047 if (drv
->bdrv_save_vmstate
)
2048 return drv
->bdrv_save_vmstate(bs
, buf
, pos
, size
);
2050 return bdrv_save_vmstate(bs
->file
, buf
, pos
, size
);
2054 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2055 int64_t pos
, int size
)
2057 BlockDriver
*drv
= bs
->drv
;
2060 if (drv
->bdrv_load_vmstate
)
2061 return drv
->bdrv_load_vmstate(bs
, buf
, pos
, size
);
2063 return bdrv_load_vmstate(bs
->file
, buf
, pos
, size
);
2067 void bdrv_debug_event(BlockDriverState
*bs
, BlkDebugEvent event
)
2069 BlockDriver
*drv
= bs
->drv
;
2071 if (!drv
|| !drv
->bdrv_debug_event
) {
2075 return drv
->bdrv_debug_event(bs
, event
);
2079 /**************************************************************/
2080 /* handling of snapshots */
2082 int bdrv_can_snapshot(BlockDriverState
*bs
)
2084 BlockDriver
*drv
= bs
->drv
;
2085 if (!drv
|| bdrv_is_removable(bs
) || bdrv_is_read_only(bs
)) {
2089 if (!drv
->bdrv_snapshot_create
) {
2090 if (bs
->file
!= NULL
) {
2091 return bdrv_can_snapshot(bs
->file
);
2099 int bdrv_is_snapshot(BlockDriverState
*bs
)
2101 return !!(bs
->open_flags
& BDRV_O_SNAPSHOT
);
2104 BlockDriverState
*bdrv_snapshots(void)
2106 BlockDriverState
*bs
;
2109 return bs_snapshots
;
2113 while ((bs
= bdrv_next(bs
))) {
2114 if (bdrv_can_snapshot(bs
)) {
2122 int bdrv_snapshot_create(BlockDriverState
*bs
,
2123 QEMUSnapshotInfo
*sn_info
)
2125 BlockDriver
*drv
= bs
->drv
;
2128 if (drv
->bdrv_snapshot_create
)
2129 return drv
->bdrv_snapshot_create(bs
, sn_info
);
2131 return bdrv_snapshot_create(bs
->file
, sn_info
);
2135 int bdrv_snapshot_goto(BlockDriverState
*bs
,
2136 const char *snapshot_id
)
2138 BlockDriver
*drv
= bs
->drv
;
2143 if (drv
->bdrv_snapshot_goto
)
2144 return drv
->bdrv_snapshot_goto(bs
, snapshot_id
);
2147 drv
->bdrv_close(bs
);
2148 ret
= bdrv_snapshot_goto(bs
->file
, snapshot_id
);
2149 open_ret
= drv
->bdrv_open(bs
, bs
->open_flags
);
2151 bdrv_delete(bs
->file
);
2161 int bdrv_snapshot_delete(BlockDriverState
*bs
, const char *snapshot_id
)
2163 BlockDriver
*drv
= bs
->drv
;
2166 if (drv
->bdrv_snapshot_delete
)
2167 return drv
->bdrv_snapshot_delete(bs
, snapshot_id
);
2169 return bdrv_snapshot_delete(bs
->file
, snapshot_id
);
2173 int bdrv_snapshot_list(BlockDriverState
*bs
,
2174 QEMUSnapshotInfo
**psn_info
)
2176 BlockDriver
*drv
= bs
->drv
;
2179 if (drv
->bdrv_snapshot_list
)
2180 return drv
->bdrv_snapshot_list(bs
, psn_info
);
2182 return bdrv_snapshot_list(bs
->file
, psn_info
);
2186 int bdrv_snapshot_load_tmp(BlockDriverState
*bs
,
2187 const char *snapshot_name
)
2189 BlockDriver
*drv
= bs
->drv
;
2193 if (!bs
->read_only
) {
2196 if (drv
->bdrv_snapshot_load_tmp
) {
2197 return drv
->bdrv_snapshot_load_tmp(bs
, snapshot_name
);
2202 #define NB_SUFFIXES 4
2204 char *get_human_readable_size(char *buf
, int buf_size
, int64_t size
)
2206 static const char suffixes
[NB_SUFFIXES
] = "KMGT";
2211 snprintf(buf
, buf_size
, "%" PRId64
, size
);
2214 for(i
= 0; i
< NB_SUFFIXES
; i
++) {
2215 if (size
< (10 * base
)) {
2216 snprintf(buf
, buf_size
, "%0.1f%c",
2217 (double)size
/ base
,
2220 } else if (size
< (1000 * base
) || i
== (NB_SUFFIXES
- 1)) {
2221 snprintf(buf
, buf_size
, "%" PRId64
"%c",
2222 ((size
+ (base
>> 1)) / base
),
2232 char *bdrv_snapshot_dump(char *buf
, int buf_size
, QEMUSnapshotInfo
*sn
)
2234 char buf1
[128], date_buf
[128], clock_buf
[128];
2244 snprintf(buf
, buf_size
,
2245 "%-10s%-20s%7s%20s%15s",
2246 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2250 ptm
= localtime(&ti
);
2251 strftime(date_buf
, sizeof(date_buf
),
2252 "%Y-%m-%d %H:%M:%S", ptm
);
2254 localtime_r(&ti
, &tm
);
2255 strftime(date_buf
, sizeof(date_buf
),
2256 "%Y-%m-%d %H:%M:%S", &tm
);
2258 secs
= sn
->vm_clock_nsec
/ 1000000000;
2259 snprintf(clock_buf
, sizeof(clock_buf
),
2260 "%02d:%02d:%02d.%03d",
2262 (int)((secs
/ 60) % 60),
2264 (int)((sn
->vm_clock_nsec
/ 1000000) % 1000));
2265 snprintf(buf
, buf_size
,
2266 "%-10s%-20s%7s%20s%15s",
2267 sn
->id_str
, sn
->name
,
2268 get_human_readable_size(buf1
, sizeof(buf1
), sn
->vm_state_size
),
2276 /**************************************************************/
2279 BlockDriverAIOCB
*bdrv_aio_readv(BlockDriverState
*bs
, int64_t sector_num
,
2280 QEMUIOVector
*qiov
, int nb_sectors
,
2281 BlockDriverCompletionFunc
*cb
, void *opaque
)
2283 BlockDriver
*drv
= bs
->drv
;
2284 BlockDriverAIOCB
*ret
;
2286 trace_bdrv_aio_readv(bs
, sector_num
, nb_sectors
, opaque
);
2290 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2293 ret
= drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
2297 /* Update stats even though technically transfer has not happened. */
2298 bs
->rd_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
2305 typedef struct BlockCompleteData
{
2306 BlockDriverCompletionFunc
*cb
;
2308 BlockDriverState
*bs
;
2311 } BlockCompleteData
;
2313 static void block_complete_cb(void *opaque
, int ret
)
2315 BlockCompleteData
*b
= opaque
;
2317 if (b
->bs
->dirty_bitmap
) {
2318 set_dirty_bitmap(b
->bs
, b
->sector_num
, b
->nb_sectors
, 1);
2320 b
->cb(b
->opaque
, ret
);
2324 static BlockCompleteData
*blk_dirty_cb_alloc(BlockDriverState
*bs
,
2327 BlockDriverCompletionFunc
*cb
,
2330 BlockCompleteData
*blkdata
= qemu_mallocz(sizeof(BlockCompleteData
));
2334 blkdata
->opaque
= opaque
;
2335 blkdata
->sector_num
= sector_num
;
2336 blkdata
->nb_sectors
= nb_sectors
;
2341 BlockDriverAIOCB
*bdrv_aio_writev(BlockDriverState
*bs
, int64_t sector_num
,
2342 QEMUIOVector
*qiov
, int nb_sectors
,
2343 BlockDriverCompletionFunc
*cb
, void *opaque
)
2345 BlockDriver
*drv
= bs
->drv
;
2346 BlockDriverAIOCB
*ret
;
2347 BlockCompleteData
*blk_cb_data
;
2349 trace_bdrv_aio_writev(bs
, sector_num
, nb_sectors
, opaque
);
2355 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2358 if (bs
->dirty_bitmap
) {
2359 blk_cb_data
= blk_dirty_cb_alloc(bs
, sector_num
, nb_sectors
, cb
,
2361 cb
= &block_complete_cb
;
2362 opaque
= blk_cb_data
;
2365 ret
= drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
2369 /* Update stats even though technically transfer has not happened. */
2370 bs
->wr_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
2372 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
2373 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
2381 typedef struct MultiwriteCB
{
2386 BlockDriverCompletionFunc
*cb
;
2388 QEMUIOVector
*free_qiov
;
2393 static void multiwrite_user_cb(MultiwriteCB
*mcb
)
2397 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2398 mcb
->callbacks
[i
].cb(mcb
->callbacks
[i
].opaque
, mcb
->error
);
2399 if (mcb
->callbacks
[i
].free_qiov
) {
2400 qemu_iovec_destroy(mcb
->callbacks
[i
].free_qiov
);
2402 qemu_free(mcb
->callbacks
[i
].free_qiov
);
2403 qemu_vfree(mcb
->callbacks
[i
].free_buf
);
2407 static void multiwrite_cb(void *opaque
, int ret
)
2409 MultiwriteCB
*mcb
= opaque
;
2411 trace_multiwrite_cb(mcb
, ret
);
2413 if (ret
< 0 && !mcb
->error
) {
2417 mcb
->num_requests
--;
2418 if (mcb
->num_requests
== 0) {
2419 multiwrite_user_cb(mcb
);
2424 static int multiwrite_req_compare(const void *a
, const void *b
)
2426 const BlockRequest
*req1
= a
, *req2
= b
;
2429 * Note that we can't simply subtract req2->sector from req1->sector
2430 * here as that could overflow the return value.
2432 if (req1
->sector
> req2
->sector
) {
2434 } else if (req1
->sector
< req2
->sector
) {
2442 * Takes a bunch of requests and tries to merge them. Returns the number of
2443 * requests that remain after merging.
2445 static int multiwrite_merge(BlockDriverState
*bs
, BlockRequest
*reqs
,
2446 int num_reqs
, MultiwriteCB
*mcb
)
2450 // Sort requests by start sector
2451 qsort(reqs
, num_reqs
, sizeof(*reqs
), &multiwrite_req_compare
);
2453 // Check if adjacent requests touch the same clusters. If so, combine them,
2454 // filling up gaps with zero sectors.
2456 for (i
= 1; i
< num_reqs
; i
++) {
2458 int64_t oldreq_last
= reqs
[outidx
].sector
+ reqs
[outidx
].nb_sectors
;
2460 // This handles the cases that are valid for all block drivers, namely
2461 // exactly sequential writes and overlapping writes.
2462 if (reqs
[i
].sector
<= oldreq_last
) {
2466 // The block driver may decide that it makes sense to combine requests
2467 // even if there is a gap of some sectors between them. In this case,
2468 // the gap is filled with zeros (therefore only applicable for yet
2469 // unused space in format like qcow2).
2470 if (!merge
&& bs
->drv
->bdrv_merge_requests
) {
2471 merge
= bs
->drv
->bdrv_merge_requests(bs
, &reqs
[outidx
], &reqs
[i
]);
2474 if (reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1 > IOV_MAX
) {
2480 QEMUIOVector
*qiov
= qemu_mallocz(sizeof(*qiov
));
2481 qemu_iovec_init(qiov
,
2482 reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1);
2484 // Add the first request to the merged one. If the requests are
2485 // overlapping, drop the last sectors of the first request.
2486 size
= (reqs
[i
].sector
- reqs
[outidx
].sector
) << 9;
2487 qemu_iovec_concat(qiov
, reqs
[outidx
].qiov
, size
);
2489 // We might need to add some zeros between the two requests
2490 if (reqs
[i
].sector
> oldreq_last
) {
2491 size_t zero_bytes
= (reqs
[i
].sector
- oldreq_last
) << 9;
2492 uint8_t *buf
= qemu_blockalign(bs
, zero_bytes
);
2493 memset(buf
, 0, zero_bytes
);
2494 qemu_iovec_add(qiov
, buf
, zero_bytes
);
2495 mcb
->callbacks
[i
].free_buf
= buf
;
2498 // Add the second request
2499 qemu_iovec_concat(qiov
, reqs
[i
].qiov
, reqs
[i
].qiov
->size
);
2501 reqs
[outidx
].nb_sectors
= qiov
->size
>> 9;
2502 reqs
[outidx
].qiov
= qiov
;
2504 mcb
->callbacks
[i
].free_qiov
= reqs
[outidx
].qiov
;
2507 reqs
[outidx
].sector
= reqs
[i
].sector
;
2508 reqs
[outidx
].nb_sectors
= reqs
[i
].nb_sectors
;
2509 reqs
[outidx
].qiov
= reqs
[i
].qiov
;
2517 * Submit multiple AIO write requests at once.
2519 * On success, the function returns 0 and all requests in the reqs array have
2520 * been submitted. In error case this function returns -1, and any of the
2521 * requests may or may not be submitted yet. In particular, this means that the
2522 * callback will be called for some of the requests, for others it won't. The
2523 * caller must check the error field of the BlockRequest to wait for the right
2524 * callbacks (if error != 0, no callback will be called).
2526 * The implementation may modify the contents of the reqs array, e.g. to merge
2527 * requests. However, the fields opaque and error are left unmodified as they
2528 * are used to signal failure for a single request to the caller.
2530 int bdrv_aio_multiwrite(BlockDriverState
*bs
, BlockRequest
*reqs
, int num_reqs
)
2532 BlockDriverAIOCB
*acb
;
2536 /* don't submit writes if we don't have a medium */
2537 if (bs
->drv
== NULL
) {
2538 for (i
= 0; i
< num_reqs
; i
++) {
2539 reqs
[i
].error
= -ENOMEDIUM
;
2544 if (num_reqs
== 0) {
2548 // Create MultiwriteCB structure
2549 mcb
= qemu_mallocz(sizeof(*mcb
) + num_reqs
* sizeof(*mcb
->callbacks
));
2550 mcb
->num_requests
= 0;
2551 mcb
->num_callbacks
= num_reqs
;
2553 for (i
= 0; i
< num_reqs
; i
++) {
2554 mcb
->callbacks
[i
].cb
= reqs
[i
].cb
;
2555 mcb
->callbacks
[i
].opaque
= reqs
[i
].opaque
;
2558 // Check for mergable requests
2559 num_reqs
= multiwrite_merge(bs
, reqs
, num_reqs
, mcb
);
2561 trace_bdrv_aio_multiwrite(mcb
, mcb
->num_callbacks
, num_reqs
);
2564 * Run the aio requests. As soon as one request can't be submitted
2565 * successfully, fail all requests that are not yet submitted (we must
2566 * return failure for all requests anyway)
2568 * num_requests cannot be set to the right value immediately: If
2569 * bdrv_aio_writev fails for some request, num_requests would be too high
2570 * and therefore multiwrite_cb() would never recognize the multiwrite
2571 * request as completed. We also cannot use the loop variable i to set it
2572 * when the first request fails because the callback may already have been
2573 * called for previously submitted requests. Thus, num_requests must be
2574 * incremented for each request that is submitted.
2576 * The problem that callbacks may be called early also means that we need
2577 * to take care that num_requests doesn't become 0 before all requests are
2578 * submitted - multiwrite_cb() would consider the multiwrite request
2579 * completed. A dummy request that is "completed" by a manual call to
2580 * multiwrite_cb() takes care of this.
2582 mcb
->num_requests
= 1;
2584 // Run the aio requests
2585 for (i
= 0; i
< num_reqs
; i
++) {
2586 mcb
->num_requests
++;
2587 acb
= bdrv_aio_writev(bs
, reqs
[i
].sector
, reqs
[i
].qiov
,
2588 reqs
[i
].nb_sectors
, multiwrite_cb
, mcb
);
2591 // We can only fail the whole thing if no request has been
2592 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2593 // complete and report the error in the callback.
2595 trace_bdrv_aio_multiwrite_earlyfail(mcb
);
2598 trace_bdrv_aio_multiwrite_latefail(mcb
, i
);
2599 multiwrite_cb(mcb
, -EIO
);
2605 /* Complete the dummy request */
2606 multiwrite_cb(mcb
, 0);
2611 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2612 reqs
[i
].error
= -EIO
;
2618 BlockDriverAIOCB
*bdrv_aio_flush(BlockDriverState
*bs
,
2619 BlockDriverCompletionFunc
*cb
, void *opaque
)
2621 BlockDriver
*drv
= bs
->drv
;
2623 trace_bdrv_aio_flush(bs
, opaque
);
2625 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2626 return bdrv_aio_noop_em(bs
, cb
, opaque
);
2631 return drv
->bdrv_aio_flush(bs
, cb
, opaque
);
2634 void bdrv_aio_cancel(BlockDriverAIOCB
*acb
)
2636 acb
->pool
->cancel(acb
);
2640 /**************************************************************/
2641 /* async block device emulation */
2643 typedef struct BlockDriverAIOCBSync
{
2644 BlockDriverAIOCB common
;
2647 /* vector translation state */
2651 } BlockDriverAIOCBSync
;
2653 static void bdrv_aio_cancel_em(BlockDriverAIOCB
*blockacb
)
2655 BlockDriverAIOCBSync
*acb
=
2656 container_of(blockacb
, BlockDriverAIOCBSync
, common
);
2657 qemu_bh_delete(acb
->bh
);
2659 qemu_aio_release(acb
);
2662 static AIOPool bdrv_em_aio_pool
= {
2663 .aiocb_size
= sizeof(BlockDriverAIOCBSync
),
2664 .cancel
= bdrv_aio_cancel_em
,
2667 static void bdrv_aio_bh_cb(void *opaque
)
2669 BlockDriverAIOCBSync
*acb
= opaque
;
2672 qemu_iovec_from_buffer(acb
->qiov
, acb
->bounce
, acb
->qiov
->size
);
2673 qemu_vfree(acb
->bounce
);
2674 acb
->common
.cb(acb
->common
.opaque
, acb
->ret
);
2675 qemu_bh_delete(acb
->bh
);
2677 qemu_aio_release(acb
);
2680 static BlockDriverAIOCB
*bdrv_aio_rw_vector(BlockDriverState
*bs
,
2684 BlockDriverCompletionFunc
*cb
,
2689 BlockDriverAIOCBSync
*acb
;
2691 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2692 acb
->is_write
= is_write
;
2694 acb
->bounce
= qemu_blockalign(bs
, qiov
->size
);
2697 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2700 qemu_iovec_to_buffer(acb
->qiov
, acb
->bounce
);
2701 acb
->ret
= bdrv_write(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2703 acb
->ret
= bdrv_read(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2706 qemu_bh_schedule(acb
->bh
);
2708 return &acb
->common
;
2711 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
2712 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2713 BlockDriverCompletionFunc
*cb
, void *opaque
)
2715 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 0);
2718 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
2719 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2720 BlockDriverCompletionFunc
*cb
, void *opaque
)
2722 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 1);
2726 typedef struct BlockDriverAIOCBCoroutine
{
2727 BlockDriverAIOCB common
;
2731 } BlockDriverAIOCBCoroutine
;
2733 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB
*blockacb
)
2738 static AIOPool bdrv_em_co_aio_pool
= {
2739 .aiocb_size
= sizeof(BlockDriverAIOCBCoroutine
),
2740 .cancel
= bdrv_aio_co_cancel_em
,
2743 static void bdrv_co_rw_bh(void *opaque
)
2745 BlockDriverAIOCBCoroutine
*acb
= opaque
;
2747 acb
->common
.cb(acb
->common
.opaque
, acb
->req
.error
);
2748 qemu_bh_delete(acb
->bh
);
2749 qemu_aio_release(acb
);
2752 static void coroutine_fn
bdrv_co_rw(void *opaque
)
2754 BlockDriverAIOCBCoroutine
*acb
= opaque
;
2755 BlockDriverState
*bs
= acb
->common
.bs
;
2757 if (!acb
->is_write
) {
2758 acb
->req
.error
= bs
->drv
->bdrv_co_readv(bs
, acb
->req
.sector
,
2759 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2761 acb
->req
.error
= bs
->drv
->bdrv_co_writev(bs
, acb
->req
.sector
,
2762 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2765 acb
->bh
= qemu_bh_new(bdrv_co_rw_bh
, acb
);
2766 qemu_bh_schedule(acb
->bh
);
2769 static BlockDriverAIOCB
*bdrv_co_aio_rw_vector(BlockDriverState
*bs
,
2773 BlockDriverCompletionFunc
*cb
,
2778 BlockDriverAIOCBCoroutine
*acb
;
2780 acb
= qemu_aio_get(&bdrv_em_co_aio_pool
, bs
, cb
, opaque
);
2781 acb
->req
.sector
= sector_num
;
2782 acb
->req
.nb_sectors
= nb_sectors
;
2783 acb
->req
.qiov
= qiov
;
2784 acb
->is_write
= is_write
;
2786 co
= qemu_coroutine_create(bdrv_co_rw
);
2787 qemu_coroutine_enter(co
, acb
);
2789 return &acb
->common
;
2792 static BlockDriverAIOCB
*bdrv_co_aio_readv_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_co_aio_writev_em(BlockDriverState
*bs
,
2801 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2802 BlockDriverCompletionFunc
*cb
, void *opaque
)
2804 return bdrv_co_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
,
2808 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
2809 BlockDriverCompletionFunc
*cb
, void *opaque
)
2811 BlockDriverAIOCBSync
*acb
;
2813 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2814 acb
->is_write
= 1; /* don't bounce in the completion hadler */
2820 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2823 qemu_bh_schedule(acb
->bh
);
2824 return &acb
->common
;
2827 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
2828 BlockDriverCompletionFunc
*cb
, void *opaque
)
2830 BlockDriverAIOCBSync
*acb
;
2832 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2833 acb
->is_write
= 1; /* don't bounce in the completion handler */
2839 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2842 qemu_bh_schedule(acb
->bh
);
2843 return &acb
->common
;
2846 /**************************************************************/
2847 /* sync block device emulation */
2849 static void bdrv_rw_em_cb(void *opaque
, int ret
)
2851 *(int *)opaque
= ret
;
2854 #define NOT_DONE 0x7fffffff
2856 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
2857 uint8_t *buf
, int nb_sectors
)
2860 BlockDriverAIOCB
*acb
;
2864 async_ret
= NOT_DONE
;
2865 iov
.iov_base
= (void *)buf
;
2866 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2867 qemu_iovec_init_external(&qiov
, &iov
, 1);
2868 acb
= bdrv_aio_readv(bs
, sector_num
, &qiov
, nb_sectors
,
2869 bdrv_rw_em_cb
, &async_ret
);
2875 while (async_ret
== NOT_DONE
) {
2884 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
2885 const uint8_t *buf
, int nb_sectors
)
2888 BlockDriverAIOCB
*acb
;
2892 async_ret
= NOT_DONE
;
2893 iov
.iov_base
= (void *)buf
;
2894 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2895 qemu_iovec_init_external(&qiov
, &iov
, 1);
2896 acb
= bdrv_aio_writev(bs
, sector_num
, &qiov
, nb_sectors
,
2897 bdrv_rw_em_cb
, &async_ret
);
2902 while (async_ret
== NOT_DONE
) {
2910 void bdrv_init(void)
2912 module_call_init(MODULE_INIT_BLOCK
);
2915 void bdrv_init_with_whitelist(void)
2917 use_bdrv_whitelist
= 1;
2921 void *qemu_aio_get(AIOPool
*pool
, BlockDriverState
*bs
,
2922 BlockDriverCompletionFunc
*cb
, void *opaque
)
2924 BlockDriverAIOCB
*acb
;
2926 if (pool
->free_aiocb
) {
2927 acb
= pool
->free_aiocb
;
2928 pool
->free_aiocb
= acb
->next
;
2930 acb
= qemu_mallocz(pool
->aiocb_size
);
2935 acb
->opaque
= opaque
;
2939 void qemu_aio_release(void *p
)
2941 BlockDriverAIOCB
*acb
= (BlockDriverAIOCB
*)p
;
2942 AIOPool
*pool
= acb
->pool
;
2943 acb
->next
= pool
->free_aiocb
;
2944 pool
->free_aiocb
= acb
;
2947 /**************************************************************/
2948 /* Coroutine block device emulation */
2950 typedef struct CoroutineIOCompletion
{
2951 Coroutine
*coroutine
;
2953 } CoroutineIOCompletion
;
2955 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
2957 CoroutineIOCompletion
*co
= opaque
;
2960 qemu_coroutine_enter(co
->coroutine
, NULL
);
2963 static int coroutine_fn
bdrv_co_io_em(BlockDriverState
*bs
, int64_t sector_num
,
2964 int nb_sectors
, QEMUIOVector
*iov
,
2967 CoroutineIOCompletion co
= {
2968 .coroutine
= qemu_coroutine_self(),
2970 BlockDriverAIOCB
*acb
;
2973 acb
= bdrv_aio_writev(bs
, sector_num
, iov
, nb_sectors
,
2974 bdrv_co_io_em_complete
, &co
);
2976 acb
= bdrv_aio_readv(bs
, sector_num
, iov
, nb_sectors
,
2977 bdrv_co_io_em_complete
, &co
);
2980 trace_bdrv_co_io(is_write
, acb
);
2984 qemu_coroutine_yield();
2989 static int coroutine_fn
bdrv_co_readv_em(BlockDriverState
*bs
,
2990 int64_t sector_num
, int nb_sectors
,
2993 return bdrv_co_io_em(bs
, sector_num
, nb_sectors
, iov
, false);
2996 static int coroutine_fn
bdrv_co_writev_em(BlockDriverState
*bs
,
2997 int64_t sector_num
, int nb_sectors
,
3000 return bdrv_co_io_em(bs
, sector_num
, nb_sectors
, iov
, true);
3003 static int coroutine_fn
bdrv_co_flush_em(BlockDriverState
*bs
)
3005 CoroutineIOCompletion co
= {
3006 .coroutine
= qemu_coroutine_self(),
3008 BlockDriverAIOCB
*acb
;
3010 acb
= bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
3014 qemu_coroutine_yield();
3018 /**************************************************************/
3019 /* removable device support */
3022 * Return TRUE if the media is present
3024 int bdrv_is_inserted(BlockDriverState
*bs
)
3026 BlockDriver
*drv
= bs
->drv
;
3030 if (!drv
->bdrv_is_inserted
)
3031 return !bs
->tray_open
;
3032 ret
= drv
->bdrv_is_inserted(bs
);
3037 * Return TRUE if the media changed since the last call to this
3038 * function. It is currently only used for floppy disks
3040 int bdrv_media_changed(BlockDriverState
*bs
)
3042 BlockDriver
*drv
= bs
->drv
;
3045 if (!drv
|| !drv
->bdrv_media_changed
)
3048 ret
= drv
->bdrv_media_changed(bs
);
3049 if (ret
== -ENOTSUP
)
3050 ret
= bs
->media_changed
;
3051 bs
->media_changed
= 0;
3056 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3058 int bdrv_eject(BlockDriverState
*bs
, int eject_flag
)
3060 BlockDriver
*drv
= bs
->drv
;
3062 if (eject_flag
&& bs
->locked
) {
3066 if (drv
&& drv
->bdrv_eject
) {
3067 drv
->bdrv_eject(bs
, eject_flag
);
3069 bs
->tray_open
= eject_flag
;
3073 int bdrv_is_locked(BlockDriverState
*bs
)
3079 * Lock or unlock the media (if it is locked, the user won't be able
3080 * to eject it manually).
3082 void bdrv_set_locked(BlockDriverState
*bs
, int locked
)
3084 BlockDriver
*drv
= bs
->drv
;
3086 trace_bdrv_set_locked(bs
, locked
);
3088 bs
->locked
= locked
;
3089 if (drv
&& drv
->bdrv_set_locked
) {
3090 drv
->bdrv_set_locked(bs
, locked
);
3094 /* needed for generic scsi interface */
3096 int bdrv_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
3098 BlockDriver
*drv
= bs
->drv
;
3100 if (drv
&& drv
->bdrv_ioctl
)
3101 return drv
->bdrv_ioctl(bs
, req
, buf
);
3105 BlockDriverAIOCB
*bdrv_aio_ioctl(BlockDriverState
*bs
,
3106 unsigned long int req
, void *buf
,
3107 BlockDriverCompletionFunc
*cb
, void *opaque
)
3109 BlockDriver
*drv
= bs
->drv
;
3111 if (drv
&& drv
->bdrv_aio_ioctl
)
3112 return drv
->bdrv_aio_ioctl(bs
, req
, buf
, cb
, opaque
);
3118 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
3120 return qemu_memalign((bs
&& bs
->buffer_alignment
) ? bs
->buffer_alignment
: 512, size
);
3123 void bdrv_set_dirty_tracking(BlockDriverState
*bs
, int enable
)
3125 int64_t bitmap_size
;
3127 bs
->dirty_count
= 0;
3129 if (!bs
->dirty_bitmap
) {
3130 bitmap_size
= (bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
) +
3131 BDRV_SECTORS_PER_DIRTY_CHUNK
* 8 - 1;
3132 bitmap_size
/= BDRV_SECTORS_PER_DIRTY_CHUNK
* 8;
3134 bs
->dirty_bitmap
= qemu_mallocz(bitmap_size
);
3137 if (bs
->dirty_bitmap
) {
3138 qemu_free(bs
->dirty_bitmap
);
3139 bs
->dirty_bitmap
= NULL
;
3144 int bdrv_get_dirty(BlockDriverState
*bs
, int64_t sector
)
3146 int64_t chunk
= sector
/ (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK
;
3148 if (bs
->dirty_bitmap
&&
3149 (sector
<< BDRV_SECTOR_BITS
) < bdrv_getlength(bs
)) {
3150 return !!(bs
->dirty_bitmap
[chunk
/ (sizeof(unsigned long) * 8)] &
3151 (1UL << (chunk
% (sizeof(unsigned long) * 8))));
3157 void bdrv_reset_dirty(BlockDriverState
*bs
, int64_t cur_sector
,
3160 set_dirty_bitmap(bs
, cur_sector
, nr_sectors
, 0);
3163 int64_t bdrv_get_dirty_count(BlockDriverState
*bs
)
3165 return bs
->dirty_count
;
3168 void bdrv_set_in_use(BlockDriverState
*bs
, int in_use
)
3170 assert(bs
->in_use
!= in_use
);
3171 bs
->in_use
= in_use
;
3174 int bdrv_in_use(BlockDriverState
*bs
)
3179 int bdrv_img_create(const char *filename
, const char *fmt
,
3180 const char *base_filename
, const char *base_fmt
,
3181 char *options
, uint64_t img_size
, int flags
)
3183 QEMUOptionParameter
*param
= NULL
, *create_options
= NULL
;
3184 QEMUOptionParameter
*cow_create_options
= NULL
;
3185 QEMUOptionParameter
*backing_fmt
, *backing_file
, *size
;
3186 QEMUOptionParameter
*image_file
;
3187 BlockDriverState
*bs
= NULL
;
3188 BlockDriver
*drv
, *proto_drv
, *cow_drv
;
3189 BlockDriver
*backing_drv
= NULL
;
3192 /* Find driver and parse its options */
3193 drv
= bdrv_find_format(fmt
);
3195 error_report("Unknown file format '%s'", fmt
);
3200 proto_drv
= bdrv_find_protocol(filename
);
3202 error_report("Unknown protocol '%s'", filename
);
3207 create_options
= append_option_parameters(create_options
,
3208 drv
->create_options
);
3209 create_options
= append_option_parameters(create_options
,
3210 proto_drv
->create_options
);
3212 /* Just support raw format now*/
3213 cow_drv
= bdrv_find_format("raw");
3214 cow_create_options
= append_option_parameters(cow_create_options
,
3215 cow_drv
->create_options
);
3217 /* Create parameter list with default values */
3218 param
= parse_option_parameters("", create_options
, param
);
3220 set_option_parameter_int(param
, BLOCK_OPT_SIZE
, img_size
);
3221 set_option_parameter_int(cow_create_options
, BLOCK_OPT_SIZE
, img_size
);
3223 /* Parse -o options */
3225 param
= parse_option_parameters(options
, create_options
, param
);
3226 if (param
== NULL
) {
3227 error_report("Invalid options for file format '%s'.", fmt
);
3233 if (base_filename
) {
3234 if (set_option_parameter(param
, BLOCK_OPT_BACKING_FILE
,
3236 error_report("Backing file not supported for file format '%s'",
3244 if (set_option_parameter(param
, BLOCK_OPT_BACKING_FMT
, base_fmt
)) {
3245 error_report("Backing file format not supported for file "
3246 "format '%s'", fmt
);
3252 backing_file
= get_option_parameter(param
, BLOCK_OPT_BACKING_FILE
);
3253 if (backing_file
&& backing_file
->value
.s
) {
3254 if (!strcmp(filename
, backing_file
->value
.s
)) {
3255 error_report("Error: Trying to create an image with the "
3256 "same filename as the backing file");
3262 image_file
= get_option_parameter(param
, BLOCK_OPT_IMAGE_FILE
);
3263 if (image_file
&& image_file
->value
.s
) {
3264 if (!strcmp(filename
, image_file
->value
.s
)) {
3265 error_report("Error: Trying to create an cow file with the "
3266 "same filename as the backing file");
3271 if (backing_file
&& backing_file
->value
.s
) {
3272 if (!strcmp(image_file
->value
.s
, backing_file
->value
.s
)) {
3273 error_report("Error: Trying to create an cow file with the "
3274 "same filename as the backing file");
3281 backing_fmt
= get_option_parameter(param
, BLOCK_OPT_BACKING_FMT
);
3282 if (backing_fmt
&& backing_fmt
->value
.s
) {
3283 backing_drv
= bdrv_find_format(backing_fmt
->value
.s
);
3285 error_report("Unknown backing file format '%s'",
3286 backing_fmt
->value
.s
);
3292 // The size for the image must always be specified, with one exception:
3293 // If we are using a backing file, we can obtain the size from there
3294 size
= get_option_parameter(param
, BLOCK_OPT_SIZE
);
3295 if (size
&& size
->value
.n
== -1) {
3296 if (backing_file
&& backing_file
->value
.s
) {
3302 ret
= bdrv_open(bs
, backing_file
->value
.s
, flags
, backing_drv
);
3304 error_report("Could not open '%s'", backing_file
->value
.s
);
3307 bdrv_get_geometry(bs
, &size
);
3310 snprintf(buf
, sizeof(buf
), "%" PRId64
, size
);
3311 set_option_parameter(param
, BLOCK_OPT_SIZE
, buf
);
3312 set_option_parameter(cow_create_options
, BLOCK_OPT_SIZE
, buf
);
3314 error_report("Image creation needs a size parameter");
3320 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
3321 print_option_parameters(param
);
3324 ret
= bdrv_create(drv
, filename
, param
);
3327 if (ret
== -ENOTSUP
) {
3328 error_report("Formatting or formatting option not supported for "
3329 "file format '%s'", fmt
);
3330 } else if (ret
== -EFBIG
) {
3331 error_report("The image size is too large for file format '%s'",
3334 error_report("%s: error while creating %s: %s", filename
, fmt
,
3339 if (!strcmp(fmt
, "add-cow") && image_file
&& image_file
->value
.s
) {
3340 printf("Formatting '%s', fmt= raw ", image_file
->value
.s
);
3341 print_option_parameters(cow_create_options
);
3343 ret
= bdrv_create(cow_drv
, image_file
->value
.s
, cow_create_options
);
3347 free_option_parameters(create_options
);
3348 free_option_parameters(param
);
3349 free_option_parameters(cow_create_options
);