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 void bdrv_dev_change_media_cb(BlockDriverState
*bs
);
48 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
49 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
50 BlockDriverCompletionFunc
*cb
, void *opaque
);
51 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
52 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
53 BlockDriverCompletionFunc
*cb
, void *opaque
);
54 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
55 BlockDriverCompletionFunc
*cb
, void *opaque
);
56 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
57 BlockDriverCompletionFunc
*cb
, void *opaque
);
58 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
59 uint8_t *buf
, int nb_sectors
);
60 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
61 const uint8_t *buf
, int nb_sectors
);
62 static BlockDriverAIOCB
*bdrv_co_aio_readv_em(BlockDriverState
*bs
,
63 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
64 BlockDriverCompletionFunc
*cb
, void *opaque
);
65 static BlockDriverAIOCB
*bdrv_co_aio_writev_em(BlockDriverState
*bs
,
66 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
67 BlockDriverCompletionFunc
*cb
, void *opaque
);
68 static int coroutine_fn
bdrv_co_readv_em(BlockDriverState
*bs
,
69 int64_t sector_num
, int nb_sectors
,
71 static int coroutine_fn
bdrv_co_writev_em(BlockDriverState
*bs
,
72 int64_t sector_num
, int nb_sectors
,
74 static int coroutine_fn
bdrv_co_flush_em(BlockDriverState
*bs
);
76 static QTAILQ_HEAD(, BlockDriverState
) bdrv_states
=
77 QTAILQ_HEAD_INITIALIZER(bdrv_states
);
79 static QLIST_HEAD(, BlockDriver
) bdrv_drivers
=
80 QLIST_HEAD_INITIALIZER(bdrv_drivers
);
82 /* The device to use for VM snapshots */
83 static BlockDriverState
*bs_snapshots
;
85 /* If non-zero, use only whitelisted block drivers */
86 static int use_bdrv_whitelist
;
89 static int is_windows_drive_prefix(const char *filename
)
91 return (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
92 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
96 int is_windows_drive(const char *filename
)
98 if (is_windows_drive_prefix(filename
) &&
101 if (strstart(filename
, "\\\\.\\", NULL
) ||
102 strstart(filename
, "//./", NULL
))
108 /* check if the path starts with "<protocol>:" */
109 static int path_has_protocol(const char *path
)
112 if (is_windows_drive(path
) ||
113 is_windows_drive_prefix(path
)) {
118 return strchr(path
, ':') != NULL
;
121 int path_is_absolute(const char *path
)
125 /* specific case for names like: "\\.\d:" */
126 if (*path
== '/' || *path
== '\\')
129 p
= strchr(path
, ':');
135 return (*p
== '/' || *p
== '\\');
141 /* if filename is absolute, just copy it to dest. Otherwise, build a
142 path to it by considering it is relative to base_path. URL are
144 void path_combine(char *dest
, int dest_size
,
145 const char *base_path
,
146 const char *filename
)
153 if (path_is_absolute(filename
)) {
154 pstrcpy(dest
, dest_size
, filename
);
156 p
= strchr(base_path
, ':');
161 p1
= strrchr(base_path
, '/');
165 p2
= strrchr(base_path
, '\\');
177 if (len
> dest_size
- 1)
179 memcpy(dest
, base_path
, len
);
181 pstrcat(dest
, dest_size
, filename
);
185 void bdrv_register(BlockDriver
*bdrv
)
187 if (bdrv
->bdrv_co_readv
) {
188 /* Emulate AIO by coroutines, and sync by AIO */
189 bdrv
->bdrv_aio_readv
= bdrv_co_aio_readv_em
;
190 bdrv
->bdrv_aio_writev
= bdrv_co_aio_writev_em
;
191 bdrv
->bdrv_read
= bdrv_read_em
;
192 bdrv
->bdrv_write
= bdrv_write_em
;
194 bdrv
->bdrv_co_readv
= bdrv_co_readv_em
;
195 bdrv
->bdrv_co_writev
= bdrv_co_writev_em
;
197 if (!bdrv
->bdrv_aio_readv
) {
198 /* add AIO emulation layer */
199 bdrv
->bdrv_aio_readv
= bdrv_aio_readv_em
;
200 bdrv
->bdrv_aio_writev
= bdrv_aio_writev_em
;
201 } else if (!bdrv
->bdrv_read
) {
202 /* add synchronous IO emulation layer */
203 bdrv
->bdrv_read
= bdrv_read_em
;
204 bdrv
->bdrv_write
= bdrv_write_em
;
208 if (!bdrv
->bdrv_aio_flush
)
209 bdrv
->bdrv_aio_flush
= bdrv_aio_flush_em
;
211 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
214 /* create a new block device (by default it is empty) */
215 BlockDriverState
*bdrv_new(const char *device_name
)
217 BlockDriverState
*bs
;
219 bs
= g_malloc0(sizeof(BlockDriverState
));
220 pstrcpy(bs
->device_name
, sizeof(bs
->device_name
), device_name
);
221 if (device_name
[0] != '\0') {
222 QTAILQ_INSERT_TAIL(&bdrv_states
, bs
, list
);
227 BlockDriver
*bdrv_find_format(const char *format_name
)
230 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
231 if (!strcmp(drv1
->format_name
, format_name
)) {
238 static int bdrv_is_whitelisted(BlockDriver
*drv
)
240 static const char *whitelist
[] = {
241 CONFIG_BDRV_WHITELIST
246 return 1; /* no whitelist, anything goes */
248 for (p
= whitelist
; *p
; p
++) {
249 if (!strcmp(drv
->format_name
, *p
)) {
256 BlockDriver
*bdrv_find_whitelisted_format(const char *format_name
)
258 BlockDriver
*drv
= bdrv_find_format(format_name
);
259 return drv
&& bdrv_is_whitelisted(drv
) ? drv
: NULL
;
262 int bdrv_create(BlockDriver
*drv
, const char* filename
,
263 QEMUOptionParameter
*options
)
265 if (!drv
->bdrv_create
)
268 return drv
->bdrv_create(filename
, options
);
271 int bdrv_create_file(const char* filename
, QEMUOptionParameter
*options
)
275 drv
= bdrv_find_protocol(filename
);
280 return bdrv_create(drv
, filename
, options
);
284 void get_tmp_filename(char *filename
, int size
)
286 char temp_dir
[MAX_PATH
];
288 GetTempPath(MAX_PATH
, temp_dir
);
289 GetTempFileName(temp_dir
, "qem", 0, filename
);
292 void get_tmp_filename(char *filename
, int size
)
296 /* XXX: race condition possible */
297 tmpdir
= getenv("TMPDIR");
300 snprintf(filename
, size
, "%s/vl.XXXXXX", tmpdir
);
301 fd
= mkstemp(filename
);
307 * Detect host devices. By convention, /dev/cdrom[N] is always
308 * recognized as a host CDROM.
310 static BlockDriver
*find_hdev_driver(const char *filename
)
312 int score_max
= 0, score
;
313 BlockDriver
*drv
= NULL
, *d
;
315 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
316 if (d
->bdrv_probe_device
) {
317 score
= d
->bdrv_probe_device(filename
);
318 if (score
> score_max
) {
328 BlockDriver
*bdrv_find_protocol(const char *filename
)
335 /* TODO Drivers without bdrv_file_open must be specified explicitly */
338 * XXX(hch): we really should not let host device detection
339 * override an explicit protocol specification, but moving this
340 * later breaks access to device names with colons in them.
341 * Thanks to the brain-dead persistent naming schemes on udev-
342 * based Linux systems those actually are quite common.
344 drv1
= find_hdev_driver(filename
);
349 if (!path_has_protocol(filename
)) {
350 return bdrv_find_format("file");
352 p
= strchr(filename
, ':');
355 if (len
> sizeof(protocol
) - 1)
356 len
= sizeof(protocol
) - 1;
357 memcpy(protocol
, filename
, len
);
358 protocol
[len
] = '\0';
359 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
360 if (drv1
->protocol_name
&&
361 !strcmp(drv1
->protocol_name
, protocol
)) {
368 static int find_image_format(const char *filename
, BlockDriver
**pdrv
)
370 int ret
, score
, score_max
;
371 BlockDriver
*drv1
, *drv
;
373 BlockDriverState
*bs
;
375 ret
= bdrv_file_open(&bs
, filename
, 0);
381 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
382 if (bs
->sg
|| !bdrv_is_inserted(bs
)) {
384 drv
= bdrv_find_format("raw");
392 ret
= bdrv_pread(bs
, 0, buf
, sizeof(buf
));
401 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
402 if (drv1
->bdrv_probe
) {
403 score
= drv1
->bdrv_probe(buf
, ret
, filename
);
404 if (score
> score_max
) {
418 * Set the current 'total_sectors' value
420 static int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
422 BlockDriver
*drv
= bs
->drv
;
424 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
428 /* query actual device if possible, otherwise just trust the hint */
429 if (drv
->bdrv_getlength
) {
430 int64_t length
= drv
->bdrv_getlength(bs
);
434 hint
= length
>> BDRV_SECTOR_BITS
;
437 bs
->total_sectors
= hint
;
442 * Set open flags for a given cache mode
444 * Return 0 on success, -1 if the cache mode was invalid.
446 int bdrv_parse_cache_flags(const char *mode
, int *flags
)
448 *flags
&= ~BDRV_O_CACHE_MASK
;
450 if (!strcmp(mode
, "off") || !strcmp(mode
, "none")) {
451 *flags
|= BDRV_O_NOCACHE
| BDRV_O_CACHE_WB
;
452 } else if (!strcmp(mode
, "directsync")) {
453 *flags
|= BDRV_O_NOCACHE
;
454 } else if (!strcmp(mode
, "writeback")) {
455 *flags
|= BDRV_O_CACHE_WB
;
456 } else if (!strcmp(mode
, "unsafe")) {
457 *flags
|= BDRV_O_CACHE_WB
;
458 *flags
|= BDRV_O_NO_FLUSH
;
459 } else if (!strcmp(mode
, "writethrough")) {
460 /* this is the default */
469 * Common part for opening disk images and files
471 static int bdrv_open_common(BlockDriverState
*bs
, const char *filename
,
472 int flags
, BlockDriver
*drv
)
479 bs
->total_sectors
= 0;
482 bs
->open_flags
= flags
;
483 /* buffer_alignment defaulted to 512, drivers can change this value */
484 bs
->buffer_alignment
= 512;
486 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
488 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
)) {
493 bs
->opaque
= g_malloc0(drv
->instance_size
);
495 if (flags
& BDRV_O_CACHE_WB
)
496 bs
->enable_write_cache
= 1;
499 * Clear flags that are internal to the block layer before opening the
502 open_flags
= flags
& ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
505 * Snapshots should be writable.
507 if (bs
->is_temporary
) {
508 open_flags
|= BDRV_O_RDWR
;
511 /* Open the image, either directly or using a protocol */
512 if (drv
->bdrv_file_open
) {
513 ret
= drv
->bdrv_file_open(bs
, filename
, open_flags
);
515 ret
= bdrv_file_open(&bs
->file
, filename
, open_flags
);
517 ret
= drv
->bdrv_open(bs
, open_flags
);
525 bs
->keep_read_only
= bs
->read_only
= !(open_flags
& BDRV_O_RDWR
);
527 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
533 if (bs
->is_temporary
) {
541 bdrv_delete(bs
->file
);
551 * Opens a file using a protocol (file, host_device, nbd, ...)
553 int bdrv_file_open(BlockDriverState
**pbs
, const char *filename
, int flags
)
555 BlockDriverState
*bs
;
559 drv
= bdrv_find_protocol(filename
);
565 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
576 * Opens a disk image (raw, qcow2, vmdk, ...)
578 int bdrv_open(BlockDriverState
*bs
, const char *filename
, int flags
,
583 if (flags
& BDRV_O_SNAPSHOT
) {
584 BlockDriverState
*bs1
;
587 BlockDriver
*bdrv_qcow2
;
588 QEMUOptionParameter
*options
;
589 char tmp_filename
[PATH_MAX
];
590 char backing_filename
[PATH_MAX
];
592 /* if snapshot, we create a temporary backing file and open it
593 instead of opening 'filename' directly */
595 /* if there is a backing file, use it */
597 ret
= bdrv_open(bs1
, filename
, 0, drv
);
602 total_size
= bdrv_getlength(bs1
) & BDRV_SECTOR_MASK
;
604 if (bs1
->drv
&& bs1
->drv
->protocol_name
)
609 get_tmp_filename(tmp_filename
, sizeof(tmp_filename
));
611 /* Real path is meaningless for protocols */
613 snprintf(backing_filename
, sizeof(backing_filename
),
615 else if (!realpath(filename
, backing_filename
))
618 bdrv_qcow2
= bdrv_find_format("qcow2");
619 options
= parse_option_parameters("", bdrv_qcow2
->create_options
, NULL
);
621 set_option_parameter_int(options
, BLOCK_OPT_SIZE
, total_size
);
622 set_option_parameter(options
, BLOCK_OPT_BACKING_FILE
, backing_filename
);
624 set_option_parameter(options
, BLOCK_OPT_BACKING_FMT
,
628 ret
= bdrv_create(bdrv_qcow2
, tmp_filename
, options
);
629 free_option_parameters(options
);
634 filename
= tmp_filename
;
636 bs
->is_temporary
= 1;
639 /* Find the right image format driver */
641 ret
= find_image_format(filename
, &drv
);
645 goto unlink_and_fail
;
649 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
651 goto unlink_and_fail
;
654 /* If there is a backing file, use it */
655 if ((flags
& BDRV_O_NO_BACKING
) == 0 && bs
->backing_file
[0] != '\0') {
656 char backing_filename
[PATH_MAX
];
658 BlockDriver
*back_drv
= NULL
;
660 bs
->backing_hd
= bdrv_new("");
662 if (path_has_protocol(bs
->backing_file
)) {
663 pstrcpy(backing_filename
, sizeof(backing_filename
),
666 path_combine(backing_filename
, sizeof(backing_filename
),
667 filename
, bs
->backing_file
);
670 if (bs
->backing_format
[0] != '\0') {
671 back_drv
= bdrv_find_format(bs
->backing_format
);
674 /* backing files always opened read-only */
676 flags
& ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
678 ret
= bdrv_open(bs
->backing_hd
, backing_filename
, back_flags
, back_drv
);
683 if (bs
->is_temporary
) {
684 bs
->backing_hd
->keep_read_only
= !(flags
& BDRV_O_RDWR
);
686 /* base image inherits from "parent" */
687 bs
->backing_hd
->keep_read_only
= bs
->keep_read_only
;
691 if (!bdrv_key_required(bs
)) {
692 bdrv_dev_change_media_cb(bs
);
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 bdrv_dev_change_media_cb(bs
);
732 void bdrv_close_all(void)
734 BlockDriverState
*bs
;
736 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
741 /* make a BlockDriverState anonymous by removing from bdrv_state list.
742 Also, NULL terminate the device_name to prevent double remove */
743 void bdrv_make_anon(BlockDriverState
*bs
)
745 if (bs
->device_name
[0] != '\0') {
746 QTAILQ_REMOVE(&bdrv_states
, bs
, list
);
748 bs
->device_name
[0] = '\0';
751 void bdrv_delete(BlockDriverState
*bs
)
755 /* remove from list, if necessary */
759 if (bs
->file
!= NULL
) {
760 bdrv_delete(bs
->file
);
763 assert(bs
!= bs_snapshots
);
767 int bdrv_attach_dev(BlockDriverState
*bs
, void *dev
)
768 /* TODO change to DeviceState *dev when all users are qdevified */
777 /* TODO qdevified devices don't use this, remove when devices are qdevified */
778 void bdrv_attach_dev_nofail(BlockDriverState
*bs
, void *dev
)
780 if (bdrv_attach_dev(bs
, dev
) < 0) {
785 void bdrv_detach_dev(BlockDriverState
*bs
, void *dev
)
786 /* TODO change to DeviceState *dev when all users are qdevified */
788 assert(bs
->dev
== dev
);
791 bs
->dev_opaque
= NULL
;
794 /* TODO change to return DeviceState * when all users are qdevified */
795 void *bdrv_get_attached_dev(BlockDriverState
*bs
)
800 void bdrv_set_dev_ops(BlockDriverState
*bs
, const BlockDevOps
*ops
,
804 bs
->dev_opaque
= opaque
;
805 if (bdrv_dev_has_removable_media(bs
) && bs
== bs_snapshots
) {
810 static void bdrv_dev_change_media_cb(BlockDriverState
*bs
)
812 if (bs
->dev_ops
&& bs
->dev_ops
->change_media_cb
) {
813 bs
->dev_ops
->change_media_cb(bs
->dev_opaque
);
817 bool bdrv_dev_has_removable_media(BlockDriverState
*bs
)
819 return !bs
->dev
|| (bs
->dev_ops
&& bs
->dev_ops
->change_media_cb
);
822 static void bdrv_dev_resize_cb(BlockDriverState
*bs
)
824 if (bs
->dev_ops
&& bs
->dev_ops
->resize_cb
) {
825 bs
->dev_ops
->resize_cb(bs
->dev_opaque
);
829 bool bdrv_dev_is_medium_locked(BlockDriverState
*bs
)
831 if (bs
->dev_ops
&& bs
->dev_ops
->is_medium_locked
) {
832 return bs
->dev_ops
->is_medium_locked(bs
->dev_opaque
);
838 * Run consistency checks on an image
840 * Returns 0 if the check could be completed (it doesn't mean that the image is
841 * free of errors) or -errno when an internal error occurred. The results of the
842 * check are stored in res.
844 int bdrv_check(BlockDriverState
*bs
, BdrvCheckResult
*res
)
846 if (bs
->drv
->bdrv_check
== NULL
) {
850 memset(res
, 0, sizeof(*res
));
851 return bs
->drv
->bdrv_check(bs
, res
);
854 #define COMMIT_BUF_SECTORS 2048
856 /* commit COW file into the raw image */
857 int bdrv_commit(BlockDriverState
*bs
)
859 BlockDriver
*drv
= bs
->drv
;
860 BlockDriver
*backing_drv
;
861 int64_t sector
, total_sectors
;
862 int n
, ro
, open_flags
;
863 int ret
= 0, rw_ret
= 0;
866 BlockDriverState
*bs_rw
, *bs_ro
;
871 if (!bs
->backing_hd
) {
875 if (bs
->backing_hd
->keep_read_only
) {
879 backing_drv
= bs
->backing_hd
->drv
;
880 ro
= bs
->backing_hd
->read_only
;
881 strncpy(filename
, bs
->backing_hd
->filename
, sizeof(filename
));
882 open_flags
= bs
->backing_hd
->open_flags
;
886 bdrv_delete(bs
->backing_hd
);
887 bs
->backing_hd
= NULL
;
888 bs_rw
= bdrv_new("");
889 rw_ret
= bdrv_open(bs_rw
, filename
, open_flags
| BDRV_O_RDWR
,
893 /* try to re-open read-only */
894 bs_ro
= bdrv_new("");
895 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
,
899 /* drive not functional anymore */
903 bs
->backing_hd
= bs_ro
;
906 bs
->backing_hd
= bs_rw
;
909 total_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
910 buf
= g_malloc(COMMIT_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
912 for (sector
= 0; sector
< total_sectors
; sector
+= n
) {
913 if (drv
->bdrv_is_allocated(bs
, sector
, COMMIT_BUF_SECTORS
, &n
)) {
915 if (bdrv_read(bs
, sector
, buf
, n
) != 0) {
920 if (bdrv_write(bs
->backing_hd
, sector
, buf
, n
) != 0) {
927 if (drv
->bdrv_make_empty
) {
928 ret
= drv
->bdrv_make_empty(bs
);
933 * Make sure all data we wrote to the backing device is actually
937 bdrv_flush(bs
->backing_hd
);
944 bdrv_delete(bs
->backing_hd
);
945 bs
->backing_hd
= NULL
;
946 bs_ro
= bdrv_new("");
947 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
,
951 /* drive not functional anymore */
955 bs
->backing_hd
= bs_ro
;
956 bs
->backing_hd
->keep_read_only
= 0;
962 void bdrv_commit_all(void)
964 BlockDriverState
*bs
;
966 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
974 * -EINVAL - backing format specified, but no file
975 * -ENOSPC - can't update the backing file because no space is left in the
977 * -ENOTSUP - format driver doesn't support changing the backing file
979 int bdrv_change_backing_file(BlockDriverState
*bs
,
980 const char *backing_file
, const char *backing_fmt
)
982 BlockDriver
*drv
= bs
->drv
;
984 if (drv
->bdrv_change_backing_file
!= NULL
) {
985 return drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
991 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
996 if (!bdrv_is_inserted(bs
))
1002 len
= bdrv_getlength(bs
);
1007 if ((offset
> len
) || (len
- offset
< size
))
1013 static int bdrv_check_request(BlockDriverState
*bs
, int64_t sector_num
,
1016 return bdrv_check_byte_request(bs
, sector_num
* BDRV_SECTOR_SIZE
,
1017 nb_sectors
* BDRV_SECTOR_SIZE
);
1020 static inline bool bdrv_has_async_rw(BlockDriver
*drv
)
1022 return drv
->bdrv_co_readv
!= bdrv_co_readv_em
1023 || drv
->bdrv_aio_readv
!= bdrv_aio_readv_em
;
1026 static inline bool bdrv_has_async_flush(BlockDriver
*drv
)
1028 return drv
->bdrv_aio_flush
!= bdrv_aio_flush_em
;
1031 /* return < 0 if error. See bdrv_write() for the return codes */
1032 int bdrv_read(BlockDriverState
*bs
, int64_t sector_num
,
1033 uint8_t *buf
, int nb_sectors
)
1035 BlockDriver
*drv
= bs
->drv
;
1040 if (bdrv_has_async_rw(drv
) && qemu_in_coroutine()) {
1042 struct iovec iov
= {
1043 .iov_base
= (void *)buf
,
1044 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
1047 qemu_iovec_init_external(&qiov
, &iov
, 1);
1048 return bdrv_co_readv(bs
, sector_num
, nb_sectors
, &qiov
);
1051 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1054 return drv
->bdrv_read(bs
, sector_num
, buf
, nb_sectors
);
1057 static void set_dirty_bitmap(BlockDriverState
*bs
, int64_t sector_num
,
1058 int nb_sectors
, int dirty
)
1061 unsigned long val
, idx
, bit
;
1063 start
= sector_num
/ BDRV_SECTORS_PER_DIRTY_CHUNK
;
1064 end
= (sector_num
+ nb_sectors
- 1) / BDRV_SECTORS_PER_DIRTY_CHUNK
;
1066 for (; start
<= end
; start
++) {
1067 idx
= start
/ (sizeof(unsigned long) * 8);
1068 bit
= start
% (sizeof(unsigned long) * 8);
1069 val
= bs
->dirty_bitmap
[idx
];
1071 if (!(val
& (1UL << bit
))) {
1076 if (val
& (1UL << bit
)) {
1078 val
&= ~(1UL << bit
);
1081 bs
->dirty_bitmap
[idx
] = val
;
1085 /* Return < 0 if error. Important errors are:
1086 -EIO generic I/O error (may happen for all errors)
1087 -ENOMEDIUM No media inserted.
1088 -EINVAL Invalid sector number or nb_sectors
1089 -EACCES Trying to write a read-only device
1091 int bdrv_write(BlockDriverState
*bs
, int64_t sector_num
,
1092 const uint8_t *buf
, int nb_sectors
)
1094 BlockDriver
*drv
= bs
->drv
;
1099 if (bdrv_has_async_rw(drv
) && qemu_in_coroutine()) {
1101 struct iovec iov
= {
1102 .iov_base
= (void *)buf
,
1103 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
1106 qemu_iovec_init_external(&qiov
, &iov
, 1);
1107 return bdrv_co_writev(bs
, sector_num
, nb_sectors
, &qiov
);
1112 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1115 if (bs
->dirty_bitmap
) {
1116 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1119 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1120 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1123 return drv
->bdrv_write(bs
, sector_num
, buf
, nb_sectors
);
1126 int bdrv_pread(BlockDriverState
*bs
, int64_t offset
,
1127 void *buf
, int count1
)
1129 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1130 int len
, nb_sectors
, count
;
1135 /* first read 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(buf
, tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), len
);
1151 /* read the sectors "in place" */
1152 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1153 if (nb_sectors
> 0) {
1154 if ((ret
= bdrv_read(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1156 sector_num
+= nb_sectors
;
1157 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1162 /* add data from the last sector */
1164 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1166 memcpy(buf
, tmp_buf
, count
);
1171 int bdrv_pwrite(BlockDriverState
*bs
, int64_t offset
,
1172 const void *buf
, int count1
)
1174 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1175 int len
, nb_sectors
, count
;
1180 /* first write to align to sector start */
1181 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1184 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1186 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1188 memcpy(tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), buf
, len
);
1189 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1198 /* write the sectors "in place" */
1199 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1200 if (nb_sectors
> 0) {
1201 if ((ret
= bdrv_write(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1203 sector_num
+= nb_sectors
;
1204 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1209 /* add data from the last sector */
1211 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1213 memcpy(tmp_buf
, buf
, count
);
1214 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1221 * Writes to the file and ensures that no writes are reordered across this
1222 * request (acts as a barrier)
1224 * Returns 0 on success, -errno in error cases.
1226 int bdrv_pwrite_sync(BlockDriverState
*bs
, int64_t offset
,
1227 const void *buf
, int count
)
1231 ret
= bdrv_pwrite(bs
, offset
, buf
, count
);
1236 /* No flush needed for cache modes that use O_DSYNC */
1237 if ((bs
->open_flags
& BDRV_O_CACHE_WB
) != 0) {
1244 int coroutine_fn
bdrv_co_readv(BlockDriverState
*bs
, int64_t sector_num
,
1245 int nb_sectors
, QEMUIOVector
*qiov
)
1247 BlockDriver
*drv
= bs
->drv
;
1249 trace_bdrv_co_readv(bs
, sector_num
, nb_sectors
);
1254 if (bdrv_check_request(bs
, sector_num
, nb_sectors
)) {
1258 return drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1261 int coroutine_fn
bdrv_co_writev(BlockDriverState
*bs
, int64_t sector_num
,
1262 int nb_sectors
, QEMUIOVector
*qiov
)
1264 BlockDriver
*drv
= bs
->drv
;
1266 trace_bdrv_co_writev(bs
, sector_num
, nb_sectors
);
1271 if (bs
->read_only
) {
1274 if (bdrv_check_request(bs
, sector_num
, nb_sectors
)) {
1278 if (bs
->dirty_bitmap
) {
1279 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1282 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1283 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1286 return drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
);
1290 * Truncate file to 'offset' bytes (needed only for file protocols)
1292 int bdrv_truncate(BlockDriverState
*bs
, int64_t offset
)
1294 BlockDriver
*drv
= bs
->drv
;
1298 if (!drv
->bdrv_truncate
)
1302 if (bdrv_in_use(bs
))
1304 ret
= drv
->bdrv_truncate(bs
, offset
);
1306 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
1307 bdrv_dev_resize_cb(bs
);
1313 * Length of a allocated file in bytes. Sparse files are counted by actual
1314 * allocated space. Return < 0 if error or unknown.
1316 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
1318 BlockDriver
*drv
= bs
->drv
;
1322 if (drv
->bdrv_get_allocated_file_size
) {
1323 return drv
->bdrv_get_allocated_file_size(bs
);
1326 return bdrv_get_allocated_file_size(bs
->file
);
1332 * Length of a file in bytes. Return < 0 if error or unknown.
1334 int64_t bdrv_getlength(BlockDriverState
*bs
)
1336 BlockDriver
*drv
= bs
->drv
;
1340 if (bs
->growable
|| bdrv_dev_has_removable_media(bs
)) {
1341 if (drv
->bdrv_getlength
) {
1342 return drv
->bdrv_getlength(bs
);
1345 return bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1348 /* return 0 as number of sectors if no device present or error */
1349 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
1352 length
= bdrv_getlength(bs
);
1356 length
= length
>> BDRV_SECTOR_BITS
;
1357 *nb_sectors_ptr
= length
;
1361 uint8_t boot_ind
; /* 0x80 - active */
1362 uint8_t head
; /* starting head */
1363 uint8_t sector
; /* starting sector */
1364 uint8_t cyl
; /* starting cylinder */
1365 uint8_t sys_ind
; /* What partition type */
1366 uint8_t end_head
; /* end head */
1367 uint8_t end_sector
; /* end sector */
1368 uint8_t end_cyl
; /* end cylinder */
1369 uint32_t start_sect
; /* starting sector counting from 0 */
1370 uint32_t nr_sects
; /* nr of sectors in partition */
1373 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1374 static int guess_disk_lchs(BlockDriverState
*bs
,
1375 int *pcylinders
, int *pheads
, int *psectors
)
1377 uint8_t buf
[BDRV_SECTOR_SIZE
];
1378 int ret
, i
, heads
, sectors
, cylinders
;
1379 struct partition
*p
;
1381 uint64_t nb_sectors
;
1383 bdrv_get_geometry(bs
, &nb_sectors
);
1385 ret
= bdrv_read(bs
, 0, buf
, 1);
1388 /* test msdos magic */
1389 if (buf
[510] != 0x55 || buf
[511] != 0xaa)
1391 for(i
= 0; i
< 4; i
++) {
1392 p
= ((struct partition
*)(buf
+ 0x1be)) + i
;
1393 nr_sects
= le32_to_cpu(p
->nr_sects
);
1394 if (nr_sects
&& p
->end_head
) {
1395 /* We make the assumption that the partition terminates on
1396 a cylinder boundary */
1397 heads
= p
->end_head
+ 1;
1398 sectors
= p
->end_sector
& 63;
1401 cylinders
= nb_sectors
/ (heads
* sectors
);
1402 if (cylinders
< 1 || cylinders
> 16383)
1405 *psectors
= sectors
;
1406 *pcylinders
= cylinders
;
1408 printf("guessed geometry: LCHS=%d %d %d\n",
1409 cylinders
, heads
, sectors
);
1417 void bdrv_guess_geometry(BlockDriverState
*bs
, int *pcyls
, int *pheads
, int *psecs
)
1419 int translation
, lba_detected
= 0;
1420 int cylinders
, heads
, secs
;
1421 uint64_t nb_sectors
;
1423 /* if a geometry hint is available, use it */
1424 bdrv_get_geometry(bs
, &nb_sectors
);
1425 bdrv_get_geometry_hint(bs
, &cylinders
, &heads
, &secs
);
1426 translation
= bdrv_get_translation_hint(bs
);
1427 if (cylinders
!= 0) {
1432 if (guess_disk_lchs(bs
, &cylinders
, &heads
, &secs
) == 0) {
1434 /* if heads > 16, it means that a BIOS LBA
1435 translation was active, so the default
1436 hardware geometry is OK */
1438 goto default_geometry
;
1443 /* disable any translation to be in sync with
1444 the logical geometry */
1445 if (translation
== BIOS_ATA_TRANSLATION_AUTO
) {
1446 bdrv_set_translation_hint(bs
,
1447 BIOS_ATA_TRANSLATION_NONE
);
1452 /* if no geometry, use a standard physical disk geometry */
1453 cylinders
= nb_sectors
/ (16 * 63);
1455 if (cylinders
> 16383)
1457 else if (cylinders
< 2)
1462 if ((lba_detected
== 1) && (translation
== BIOS_ATA_TRANSLATION_AUTO
)) {
1463 if ((*pcyls
* *pheads
) <= 131072) {
1464 bdrv_set_translation_hint(bs
,
1465 BIOS_ATA_TRANSLATION_LARGE
);
1467 bdrv_set_translation_hint(bs
,
1468 BIOS_ATA_TRANSLATION_LBA
);
1472 bdrv_set_geometry_hint(bs
, *pcyls
, *pheads
, *psecs
);
1476 void bdrv_set_geometry_hint(BlockDriverState
*bs
,
1477 int cyls
, int heads
, int secs
)
1484 void bdrv_set_translation_hint(BlockDriverState
*bs
, int translation
)
1486 bs
->translation
= translation
;
1489 void bdrv_get_geometry_hint(BlockDriverState
*bs
,
1490 int *pcyls
, int *pheads
, int *psecs
)
1493 *pheads
= bs
->heads
;
1497 /* Recognize floppy formats */
1498 typedef struct FDFormat
{
1505 static const FDFormat fd_formats
[] = {
1506 /* First entry is default format */
1507 /* 1.44 MB 3"1/2 floppy disks */
1508 { FDRIVE_DRV_144
, 18, 80, 1, },
1509 { FDRIVE_DRV_144
, 20, 80, 1, },
1510 { FDRIVE_DRV_144
, 21, 80, 1, },
1511 { FDRIVE_DRV_144
, 21, 82, 1, },
1512 { FDRIVE_DRV_144
, 21, 83, 1, },
1513 { FDRIVE_DRV_144
, 22, 80, 1, },
1514 { FDRIVE_DRV_144
, 23, 80, 1, },
1515 { FDRIVE_DRV_144
, 24, 80, 1, },
1516 /* 2.88 MB 3"1/2 floppy disks */
1517 { FDRIVE_DRV_288
, 36, 80, 1, },
1518 { FDRIVE_DRV_288
, 39, 80, 1, },
1519 { FDRIVE_DRV_288
, 40, 80, 1, },
1520 { FDRIVE_DRV_288
, 44, 80, 1, },
1521 { FDRIVE_DRV_288
, 48, 80, 1, },
1522 /* 720 kB 3"1/2 floppy disks */
1523 { FDRIVE_DRV_144
, 9, 80, 1, },
1524 { FDRIVE_DRV_144
, 10, 80, 1, },
1525 { FDRIVE_DRV_144
, 10, 82, 1, },
1526 { FDRIVE_DRV_144
, 10, 83, 1, },
1527 { FDRIVE_DRV_144
, 13, 80, 1, },
1528 { FDRIVE_DRV_144
, 14, 80, 1, },
1529 /* 1.2 MB 5"1/4 floppy disks */
1530 { FDRIVE_DRV_120
, 15, 80, 1, },
1531 { FDRIVE_DRV_120
, 18, 80, 1, },
1532 { FDRIVE_DRV_120
, 18, 82, 1, },
1533 { FDRIVE_DRV_120
, 18, 83, 1, },
1534 { FDRIVE_DRV_120
, 20, 80, 1, },
1535 /* 720 kB 5"1/4 floppy disks */
1536 { FDRIVE_DRV_120
, 9, 80, 1, },
1537 { FDRIVE_DRV_120
, 11, 80, 1, },
1538 /* 360 kB 5"1/4 floppy disks */
1539 { FDRIVE_DRV_120
, 9, 40, 1, },
1540 { FDRIVE_DRV_120
, 9, 40, 0, },
1541 { FDRIVE_DRV_120
, 10, 41, 1, },
1542 { FDRIVE_DRV_120
, 10, 42, 1, },
1543 /* 320 kB 5"1/4 floppy disks */
1544 { FDRIVE_DRV_120
, 8, 40, 1, },
1545 { FDRIVE_DRV_120
, 8, 40, 0, },
1546 /* 360 kB must match 5"1/4 better than 3"1/2... */
1547 { FDRIVE_DRV_144
, 9, 80, 0, },
1549 { FDRIVE_DRV_NONE
, -1, -1, 0, },
1552 void bdrv_get_floppy_geometry_hint(BlockDriverState
*bs
, int *nb_heads
,
1553 int *max_track
, int *last_sect
,
1554 FDriveType drive_in
, FDriveType
*drive
)
1556 const FDFormat
*parse
;
1557 uint64_t nb_sectors
, size
;
1558 int i
, first_match
, match
;
1560 bdrv_get_geometry_hint(bs
, nb_heads
, max_track
, last_sect
);
1561 if (*nb_heads
!= 0 && *max_track
!= 0 && *last_sect
!= 0) {
1562 /* User defined disk */
1564 bdrv_get_geometry(bs
, &nb_sectors
);
1567 for (i
= 0; ; i
++) {
1568 parse
= &fd_formats
[i
];
1569 if (parse
->drive
== FDRIVE_DRV_NONE
) {
1572 if (drive_in
== parse
->drive
||
1573 drive_in
== FDRIVE_DRV_NONE
) {
1574 size
= (parse
->max_head
+ 1) * parse
->max_track
*
1576 if (nb_sectors
== size
) {
1580 if (first_match
== -1) {
1586 if (first_match
== -1) {
1589 match
= first_match
;
1591 parse
= &fd_formats
[match
];
1593 *nb_heads
= parse
->max_head
+ 1;
1594 *max_track
= parse
->max_track
;
1595 *last_sect
= parse
->last_sect
;
1596 *drive
= parse
->drive
;
1600 int bdrv_get_translation_hint(BlockDriverState
*bs
)
1602 return bs
->translation
;
1605 void bdrv_set_on_error(BlockDriverState
*bs
, BlockErrorAction on_read_error
,
1606 BlockErrorAction on_write_error
)
1608 bs
->on_read_error
= on_read_error
;
1609 bs
->on_write_error
= on_write_error
;
1612 BlockErrorAction
bdrv_get_on_error(BlockDriverState
*bs
, int is_read
)
1614 return is_read
? bs
->on_read_error
: bs
->on_write_error
;
1617 void bdrv_set_removable(BlockDriverState
*bs
, int removable
)
1619 bs
->removable
= removable
;
1620 if (removable
&& bs
== bs_snapshots
) {
1621 bs_snapshots
= NULL
;
1625 int bdrv_is_read_only(BlockDriverState
*bs
)
1627 return bs
->read_only
;
1630 int bdrv_is_sg(BlockDriverState
*bs
)
1635 int bdrv_enable_write_cache(BlockDriverState
*bs
)
1637 return bs
->enable_write_cache
;
1640 int bdrv_is_encrypted(BlockDriverState
*bs
)
1642 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1644 return bs
->encrypted
;
1647 int bdrv_key_required(BlockDriverState
*bs
)
1649 BlockDriverState
*backing_hd
= bs
->backing_hd
;
1651 if (backing_hd
&& backing_hd
->encrypted
&& !backing_hd
->valid_key
)
1653 return (bs
->encrypted
&& !bs
->valid_key
);
1656 int bdrv_set_key(BlockDriverState
*bs
, const char *key
)
1659 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
) {
1660 ret
= bdrv_set_key(bs
->backing_hd
, key
);
1666 if (!bs
->encrypted
) {
1668 } else if (!bs
->drv
|| !bs
->drv
->bdrv_set_key
) {
1671 ret
= bs
->drv
->bdrv_set_key(bs
, key
);
1674 } else if (!bs
->valid_key
) {
1676 /* call the change callback now, we skipped it on open */
1677 bdrv_dev_change_media_cb(bs
);
1682 void bdrv_get_format(BlockDriverState
*bs
, char *buf
, int buf_size
)
1687 pstrcpy(buf
, buf_size
, bs
->drv
->format_name
);
1691 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
1696 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
1697 it(opaque
, drv
->format_name
);
1701 BlockDriverState
*bdrv_find(const char *name
)
1703 BlockDriverState
*bs
;
1705 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1706 if (!strcmp(name
, bs
->device_name
)) {
1713 BlockDriverState
*bdrv_next(BlockDriverState
*bs
)
1716 return QTAILQ_FIRST(&bdrv_states
);
1718 return QTAILQ_NEXT(bs
, list
);
1721 void bdrv_iterate(void (*it
)(void *opaque
, BlockDriverState
*bs
), void *opaque
)
1723 BlockDriverState
*bs
;
1725 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1730 const char *bdrv_get_device_name(BlockDriverState
*bs
)
1732 return bs
->device_name
;
1735 int bdrv_flush(BlockDriverState
*bs
)
1737 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
1741 if (bs
->drv
&& bdrv_has_async_flush(bs
->drv
) && qemu_in_coroutine()) {
1742 return bdrv_co_flush_em(bs
);
1745 if (bs
->drv
&& bs
->drv
->bdrv_flush
) {
1746 return bs
->drv
->bdrv_flush(bs
);
1750 * Some block drivers always operate in either writethrough or unsafe mode
1751 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1752 * the server works (because the behaviour is hardcoded or depends on
1753 * server-side configuration), so we can't ensure that everything is safe
1754 * on disk. Returning an error doesn't work because that would break guests
1755 * even if the server operates in writethrough mode.
1757 * Let's hope the user knows what he's doing.
1762 void bdrv_flush_all(void)
1764 BlockDriverState
*bs
;
1766 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1767 if (!bdrv_is_read_only(bs
) && bdrv_is_inserted(bs
)) {
1773 int bdrv_has_zero_init(BlockDriverState
*bs
)
1777 if (bs
->drv
->bdrv_has_zero_init
) {
1778 return bs
->drv
->bdrv_has_zero_init(bs
);
1784 int bdrv_discard(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
)
1789 if (!bs
->drv
->bdrv_discard
) {
1792 return bs
->drv
->bdrv_discard(bs
, sector_num
, nb_sectors
);
1796 * Returns true iff the specified sector is present in the disk image. Drivers
1797 * not implementing the functionality are assumed to not support backing files,
1798 * hence all their sectors are reported as allocated.
1800 * 'pnum' is set to the number of sectors (including and immediately following
1801 * the specified sector) that are known to be in the same
1802 * allocated/unallocated state.
1804 * 'nb_sectors' is the max value 'pnum' should be set to.
1806 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
,
1810 if (!bs
->drv
->bdrv_is_allocated
) {
1811 if (sector_num
>= bs
->total_sectors
) {
1815 n
= bs
->total_sectors
- sector_num
;
1816 *pnum
= (n
< nb_sectors
) ? (n
) : (nb_sectors
);
1819 return bs
->drv
->bdrv_is_allocated(bs
, sector_num
, nb_sectors
, pnum
);
1822 void bdrv_mon_event(const BlockDriverState
*bdrv
,
1823 BlockMonEventAction action
, int is_read
)
1826 const char *action_str
;
1829 case BDRV_ACTION_REPORT
:
1830 action_str
= "report";
1832 case BDRV_ACTION_IGNORE
:
1833 action_str
= "ignore";
1835 case BDRV_ACTION_STOP
:
1836 action_str
= "stop";
1842 data
= qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1845 is_read
? "read" : "write");
1846 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR
, data
);
1848 qobject_decref(data
);
1851 static void bdrv_print_dict(QObject
*obj
, void *opaque
)
1854 Monitor
*mon
= opaque
;
1856 bs_dict
= qobject_to_qdict(obj
);
1858 monitor_printf(mon
, "%s: removable=%d",
1859 qdict_get_str(bs_dict
, "device"),
1860 qdict_get_bool(bs_dict
, "removable"));
1862 if (qdict_get_bool(bs_dict
, "removable")) {
1863 monitor_printf(mon
, " locked=%d", qdict_get_bool(bs_dict
, "locked"));
1866 if (qdict_haskey(bs_dict
, "inserted")) {
1867 QDict
*qdict
= qobject_to_qdict(qdict_get(bs_dict
, "inserted"));
1869 monitor_printf(mon
, " file=");
1870 monitor_print_filename(mon
, qdict_get_str(qdict
, "file"));
1871 if (qdict_haskey(qdict
, "backing_file")) {
1872 monitor_printf(mon
, " backing_file=");
1873 monitor_print_filename(mon
, qdict_get_str(qdict
, "backing_file"));
1875 monitor_printf(mon
, " ro=%d drv=%s encrypted=%d",
1876 qdict_get_bool(qdict
, "ro"),
1877 qdict_get_str(qdict
, "drv"),
1878 qdict_get_bool(qdict
, "encrypted"));
1880 monitor_printf(mon
, " [not inserted]");
1883 monitor_printf(mon
, "\n");
1886 void bdrv_info_print(Monitor
*mon
, const QObject
*data
)
1888 qlist_iter(qobject_to_qlist(data
), bdrv_print_dict
, mon
);
1891 void bdrv_info(Monitor
*mon
, QObject
**ret_data
)
1894 BlockDriverState
*bs
;
1896 bs_list
= qlist_new();
1898 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1901 bs_obj
= qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
1902 "'removable': %i, 'locked': %i }",
1904 bdrv_dev_has_removable_media(bs
),
1905 bdrv_dev_is_medium_locked(bs
));
1909 QDict
*bs_dict
= qobject_to_qdict(bs_obj
);
1911 obj
= qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1912 "'encrypted': %i }",
1913 bs
->filename
, bs
->read_only
,
1914 bs
->drv
->format_name
,
1915 bdrv_is_encrypted(bs
));
1916 if (bs
->backing_file
[0] != '\0') {
1917 QDict
*qdict
= qobject_to_qdict(obj
);
1918 qdict_put(qdict
, "backing_file",
1919 qstring_from_str(bs
->backing_file
));
1922 qdict_put_obj(bs_dict
, "inserted", obj
);
1924 qlist_append_obj(bs_list
, bs_obj
);
1927 *ret_data
= QOBJECT(bs_list
);
1930 static void bdrv_stats_iter(QObject
*data
, void *opaque
)
1933 Monitor
*mon
= opaque
;
1935 qdict
= qobject_to_qdict(data
);
1936 monitor_printf(mon
, "%s:", qdict_get_str(qdict
, "device"));
1938 qdict
= qobject_to_qdict(qdict_get(qdict
, "stats"));
1939 monitor_printf(mon
, " rd_bytes=%" PRId64
1940 " wr_bytes=%" PRId64
1941 " rd_operations=%" PRId64
1942 " wr_operations=%" PRId64
1943 " flush_operations=%" PRId64
1944 " wr_total_time_ns=%" PRId64
1945 " rd_total_time_ns=%" PRId64
1946 " flush_total_time_ns=%" PRId64
1948 qdict_get_int(qdict
, "rd_bytes"),
1949 qdict_get_int(qdict
, "wr_bytes"),
1950 qdict_get_int(qdict
, "rd_operations"),
1951 qdict_get_int(qdict
, "wr_operations"),
1952 qdict_get_int(qdict
, "flush_operations"),
1953 qdict_get_int(qdict
, "wr_total_time_ns"),
1954 qdict_get_int(qdict
, "rd_total_time_ns"),
1955 qdict_get_int(qdict
, "flush_total_time_ns"));
1958 void bdrv_stats_print(Monitor
*mon
, const QObject
*data
)
1960 qlist_iter(qobject_to_qlist(data
), bdrv_stats_iter
, mon
);
1963 static QObject
* bdrv_info_stats_bs(BlockDriverState
*bs
)
1968 res
= qobject_from_jsonf("{ 'stats': {"
1969 "'rd_bytes': %" PRId64
","
1970 "'wr_bytes': %" PRId64
","
1971 "'rd_operations': %" PRId64
","
1972 "'wr_operations': %" PRId64
","
1973 "'wr_highest_offset': %" PRId64
","
1974 "'flush_operations': %" PRId64
","
1975 "'wr_total_time_ns': %" PRId64
","
1976 "'rd_total_time_ns': %" PRId64
","
1977 "'flush_total_time_ns': %" PRId64
1979 bs
->nr_bytes
[BDRV_ACCT_READ
],
1980 bs
->nr_bytes
[BDRV_ACCT_WRITE
],
1981 bs
->nr_ops
[BDRV_ACCT_READ
],
1982 bs
->nr_ops
[BDRV_ACCT_WRITE
],
1983 bs
->wr_highest_sector
*
1984 (uint64_t)BDRV_SECTOR_SIZE
,
1985 bs
->nr_ops
[BDRV_ACCT_FLUSH
],
1986 bs
->total_time_ns
[BDRV_ACCT_WRITE
],
1987 bs
->total_time_ns
[BDRV_ACCT_READ
],
1988 bs
->total_time_ns
[BDRV_ACCT_FLUSH
]);
1989 dict
= qobject_to_qdict(res
);
1991 if (*bs
->device_name
) {
1992 qdict_put(dict
, "device", qstring_from_str(bs
->device_name
));
1996 QObject
*parent
= bdrv_info_stats_bs(bs
->file
);
1997 qdict_put_obj(dict
, "parent", parent
);
2003 void bdrv_info_stats(Monitor
*mon
, QObject
**ret_data
)
2007 BlockDriverState
*bs
;
2009 devices
= qlist_new();
2011 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
2012 obj
= bdrv_info_stats_bs(bs
);
2013 qlist_append_obj(devices
, obj
);
2016 *ret_data
= QOBJECT(devices
);
2019 const char *bdrv_get_encrypted_filename(BlockDriverState
*bs
)
2021 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
2022 return bs
->backing_file
;
2023 else if (bs
->encrypted
)
2024 return bs
->filename
;
2029 void bdrv_get_backing_filename(BlockDriverState
*bs
,
2030 char *filename
, int filename_size
)
2032 if (!bs
->backing_file
) {
2033 pstrcpy(filename
, filename_size
, "");
2035 pstrcpy(filename
, filename_size
, bs
->backing_file
);
2039 int bdrv_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
2040 const uint8_t *buf
, int nb_sectors
)
2042 BlockDriver
*drv
= bs
->drv
;
2045 if (!drv
->bdrv_write_compressed
)
2047 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2050 if (bs
->dirty_bitmap
) {
2051 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
2054 return drv
->bdrv_write_compressed(bs
, sector_num
, buf
, nb_sectors
);
2057 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2059 BlockDriver
*drv
= bs
->drv
;
2062 if (!drv
->bdrv_get_info
)
2064 memset(bdi
, 0, sizeof(*bdi
));
2065 return drv
->bdrv_get_info(bs
, bdi
);
2068 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2069 int64_t pos
, int size
)
2071 BlockDriver
*drv
= bs
->drv
;
2074 if (drv
->bdrv_save_vmstate
)
2075 return drv
->bdrv_save_vmstate(bs
, buf
, pos
, size
);
2077 return bdrv_save_vmstate(bs
->file
, buf
, pos
, size
);
2081 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2082 int64_t pos
, int size
)
2084 BlockDriver
*drv
= bs
->drv
;
2087 if (drv
->bdrv_load_vmstate
)
2088 return drv
->bdrv_load_vmstate(bs
, buf
, pos
, size
);
2090 return bdrv_load_vmstate(bs
->file
, buf
, pos
, size
);
2094 void bdrv_debug_event(BlockDriverState
*bs
, BlkDebugEvent event
)
2096 BlockDriver
*drv
= bs
->drv
;
2098 if (!drv
|| !drv
->bdrv_debug_event
) {
2102 return drv
->bdrv_debug_event(bs
, event
);
2106 /**************************************************************/
2107 /* handling of snapshots */
2109 int bdrv_can_snapshot(BlockDriverState
*bs
)
2111 BlockDriver
*drv
= bs
->drv
;
2112 if (!drv
|| !bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
)) {
2116 if (!drv
->bdrv_snapshot_create
) {
2117 if (bs
->file
!= NULL
) {
2118 return bdrv_can_snapshot(bs
->file
);
2126 int bdrv_is_snapshot(BlockDriverState
*bs
)
2128 return !!(bs
->open_flags
& BDRV_O_SNAPSHOT
);
2131 BlockDriverState
*bdrv_snapshots(void)
2133 BlockDriverState
*bs
;
2136 return bs_snapshots
;
2140 while ((bs
= bdrv_next(bs
))) {
2141 if (bdrv_can_snapshot(bs
)) {
2149 int bdrv_snapshot_create(BlockDriverState
*bs
,
2150 QEMUSnapshotInfo
*sn_info
)
2152 BlockDriver
*drv
= bs
->drv
;
2155 if (drv
->bdrv_snapshot_create
)
2156 return drv
->bdrv_snapshot_create(bs
, sn_info
);
2158 return bdrv_snapshot_create(bs
->file
, sn_info
);
2162 int bdrv_snapshot_goto(BlockDriverState
*bs
,
2163 const char *snapshot_id
)
2165 BlockDriver
*drv
= bs
->drv
;
2170 if (drv
->bdrv_snapshot_goto
)
2171 return drv
->bdrv_snapshot_goto(bs
, snapshot_id
);
2174 drv
->bdrv_close(bs
);
2175 ret
= bdrv_snapshot_goto(bs
->file
, snapshot_id
);
2176 open_ret
= drv
->bdrv_open(bs
, bs
->open_flags
);
2178 bdrv_delete(bs
->file
);
2188 int bdrv_snapshot_delete(BlockDriverState
*bs
, const char *snapshot_id
)
2190 BlockDriver
*drv
= bs
->drv
;
2193 if (drv
->bdrv_snapshot_delete
)
2194 return drv
->bdrv_snapshot_delete(bs
, snapshot_id
);
2196 return bdrv_snapshot_delete(bs
->file
, snapshot_id
);
2200 int bdrv_snapshot_list(BlockDriverState
*bs
,
2201 QEMUSnapshotInfo
**psn_info
)
2203 BlockDriver
*drv
= bs
->drv
;
2206 if (drv
->bdrv_snapshot_list
)
2207 return drv
->bdrv_snapshot_list(bs
, psn_info
);
2209 return bdrv_snapshot_list(bs
->file
, psn_info
);
2213 int bdrv_snapshot_load_tmp(BlockDriverState
*bs
,
2214 const char *snapshot_name
)
2216 BlockDriver
*drv
= bs
->drv
;
2220 if (!bs
->read_only
) {
2223 if (drv
->bdrv_snapshot_load_tmp
) {
2224 return drv
->bdrv_snapshot_load_tmp(bs
, snapshot_name
);
2229 #define NB_SUFFIXES 4
2231 char *get_human_readable_size(char *buf
, int buf_size
, int64_t size
)
2233 static const char suffixes
[NB_SUFFIXES
] = "KMGT";
2238 snprintf(buf
, buf_size
, "%" PRId64
, size
);
2241 for(i
= 0; i
< NB_SUFFIXES
; i
++) {
2242 if (size
< (10 * base
)) {
2243 snprintf(buf
, buf_size
, "%0.1f%c",
2244 (double)size
/ base
,
2247 } else if (size
< (1000 * base
) || i
== (NB_SUFFIXES
- 1)) {
2248 snprintf(buf
, buf_size
, "%" PRId64
"%c",
2249 ((size
+ (base
>> 1)) / base
),
2259 char *bdrv_snapshot_dump(char *buf
, int buf_size
, QEMUSnapshotInfo
*sn
)
2261 char buf1
[128], date_buf
[128], clock_buf
[128];
2271 snprintf(buf
, buf_size
,
2272 "%-10s%-20s%7s%20s%15s",
2273 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2277 ptm
= localtime(&ti
);
2278 strftime(date_buf
, sizeof(date_buf
),
2279 "%Y-%m-%d %H:%M:%S", ptm
);
2281 localtime_r(&ti
, &tm
);
2282 strftime(date_buf
, sizeof(date_buf
),
2283 "%Y-%m-%d %H:%M:%S", &tm
);
2285 secs
= sn
->vm_clock_nsec
/ 1000000000;
2286 snprintf(clock_buf
, sizeof(clock_buf
),
2287 "%02d:%02d:%02d.%03d",
2289 (int)((secs
/ 60) % 60),
2291 (int)((sn
->vm_clock_nsec
/ 1000000) % 1000));
2292 snprintf(buf
, buf_size
,
2293 "%-10s%-20s%7s%20s%15s",
2294 sn
->id_str
, sn
->name
,
2295 get_human_readable_size(buf1
, sizeof(buf1
), sn
->vm_state_size
),
2302 /**************************************************************/
2305 BlockDriverAIOCB
*bdrv_aio_readv(BlockDriverState
*bs
, int64_t sector_num
,
2306 QEMUIOVector
*qiov
, int nb_sectors
,
2307 BlockDriverCompletionFunc
*cb
, void *opaque
)
2309 BlockDriver
*drv
= bs
->drv
;
2311 trace_bdrv_aio_readv(bs
, sector_num
, nb_sectors
, opaque
);
2315 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2318 return drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
2322 typedef struct BlockCompleteData
{
2323 BlockDriverCompletionFunc
*cb
;
2325 BlockDriverState
*bs
;
2328 } BlockCompleteData
;
2330 static void block_complete_cb(void *opaque
, int ret
)
2332 BlockCompleteData
*b
= opaque
;
2334 if (b
->bs
->dirty_bitmap
) {
2335 set_dirty_bitmap(b
->bs
, b
->sector_num
, b
->nb_sectors
, 1);
2337 b
->cb(b
->opaque
, ret
);
2341 static BlockCompleteData
*blk_dirty_cb_alloc(BlockDriverState
*bs
,
2344 BlockDriverCompletionFunc
*cb
,
2347 BlockCompleteData
*blkdata
= g_malloc0(sizeof(BlockCompleteData
));
2351 blkdata
->opaque
= opaque
;
2352 blkdata
->sector_num
= sector_num
;
2353 blkdata
->nb_sectors
= nb_sectors
;
2358 BlockDriverAIOCB
*bdrv_aio_writev(BlockDriverState
*bs
, int64_t sector_num
,
2359 QEMUIOVector
*qiov
, int nb_sectors
,
2360 BlockDriverCompletionFunc
*cb
, void *opaque
)
2362 BlockDriver
*drv
= bs
->drv
;
2363 BlockDriverAIOCB
*ret
;
2364 BlockCompleteData
*blk_cb_data
;
2366 trace_bdrv_aio_writev(bs
, sector_num
, nb_sectors
, opaque
);
2372 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2375 if (bs
->dirty_bitmap
) {
2376 blk_cb_data
= blk_dirty_cb_alloc(bs
, sector_num
, nb_sectors
, cb
,
2378 cb
= &block_complete_cb
;
2379 opaque
= blk_cb_data
;
2382 ret
= drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
2386 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
2387 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
2395 typedef struct MultiwriteCB
{
2400 BlockDriverCompletionFunc
*cb
;
2402 QEMUIOVector
*free_qiov
;
2407 static void multiwrite_user_cb(MultiwriteCB
*mcb
)
2411 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2412 mcb
->callbacks
[i
].cb(mcb
->callbacks
[i
].opaque
, mcb
->error
);
2413 if (mcb
->callbacks
[i
].free_qiov
) {
2414 qemu_iovec_destroy(mcb
->callbacks
[i
].free_qiov
);
2416 g_free(mcb
->callbacks
[i
].free_qiov
);
2417 qemu_vfree(mcb
->callbacks
[i
].free_buf
);
2421 static void multiwrite_cb(void *opaque
, int ret
)
2423 MultiwriteCB
*mcb
= opaque
;
2425 trace_multiwrite_cb(mcb
, ret
);
2427 if (ret
< 0 && !mcb
->error
) {
2431 mcb
->num_requests
--;
2432 if (mcb
->num_requests
== 0) {
2433 multiwrite_user_cb(mcb
);
2438 static int multiwrite_req_compare(const void *a
, const void *b
)
2440 const BlockRequest
*req1
= a
, *req2
= b
;
2443 * Note that we can't simply subtract req2->sector from req1->sector
2444 * here as that could overflow the return value.
2446 if (req1
->sector
> req2
->sector
) {
2448 } else if (req1
->sector
< req2
->sector
) {
2456 * Takes a bunch of requests and tries to merge them. Returns the number of
2457 * requests that remain after merging.
2459 static int multiwrite_merge(BlockDriverState
*bs
, BlockRequest
*reqs
,
2460 int num_reqs
, MultiwriteCB
*mcb
)
2464 // Sort requests by start sector
2465 qsort(reqs
, num_reqs
, sizeof(*reqs
), &multiwrite_req_compare
);
2467 // Check if adjacent requests touch the same clusters. If so, combine them,
2468 // filling up gaps with zero sectors.
2470 for (i
= 1; i
< num_reqs
; i
++) {
2472 int64_t oldreq_last
= reqs
[outidx
].sector
+ reqs
[outidx
].nb_sectors
;
2474 // This handles the cases that are valid for all block drivers, namely
2475 // exactly sequential writes and overlapping writes.
2476 if (reqs
[i
].sector
<= oldreq_last
) {
2480 // The block driver may decide that it makes sense to combine requests
2481 // even if there is a gap of some sectors between them. In this case,
2482 // the gap is filled with zeros (therefore only applicable for yet
2483 // unused space in format like qcow2).
2484 if (!merge
&& bs
->drv
->bdrv_merge_requests
) {
2485 merge
= bs
->drv
->bdrv_merge_requests(bs
, &reqs
[outidx
], &reqs
[i
]);
2488 if (reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1 > IOV_MAX
) {
2494 QEMUIOVector
*qiov
= g_malloc0(sizeof(*qiov
));
2495 qemu_iovec_init(qiov
,
2496 reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1);
2498 // Add the first request to the merged one. If the requests are
2499 // overlapping, drop the last sectors of the first request.
2500 size
= (reqs
[i
].sector
- reqs
[outidx
].sector
) << 9;
2501 qemu_iovec_concat(qiov
, reqs
[outidx
].qiov
, size
);
2503 // We might need to add some zeros between the two requests
2504 if (reqs
[i
].sector
> oldreq_last
) {
2505 size_t zero_bytes
= (reqs
[i
].sector
- oldreq_last
) << 9;
2506 uint8_t *buf
= qemu_blockalign(bs
, zero_bytes
);
2507 memset(buf
, 0, zero_bytes
);
2508 qemu_iovec_add(qiov
, buf
, zero_bytes
);
2509 mcb
->callbacks
[i
].free_buf
= buf
;
2512 // Add the second request
2513 qemu_iovec_concat(qiov
, reqs
[i
].qiov
, reqs
[i
].qiov
->size
);
2515 reqs
[outidx
].nb_sectors
= qiov
->size
>> 9;
2516 reqs
[outidx
].qiov
= qiov
;
2518 mcb
->callbacks
[i
].free_qiov
= reqs
[outidx
].qiov
;
2521 reqs
[outidx
].sector
= reqs
[i
].sector
;
2522 reqs
[outidx
].nb_sectors
= reqs
[i
].nb_sectors
;
2523 reqs
[outidx
].qiov
= reqs
[i
].qiov
;
2531 * Submit multiple AIO write requests at once.
2533 * On success, the function returns 0 and all requests in the reqs array have
2534 * been submitted. In error case this function returns -1, and any of the
2535 * requests may or may not be submitted yet. In particular, this means that the
2536 * callback will be called for some of the requests, for others it won't. The
2537 * caller must check the error field of the BlockRequest to wait for the right
2538 * callbacks (if error != 0, no callback will be called).
2540 * The implementation may modify the contents of the reqs array, e.g. to merge
2541 * requests. However, the fields opaque and error are left unmodified as they
2542 * are used to signal failure for a single request to the caller.
2544 int bdrv_aio_multiwrite(BlockDriverState
*bs
, BlockRequest
*reqs
, int num_reqs
)
2546 BlockDriverAIOCB
*acb
;
2550 /* don't submit writes if we don't have a medium */
2551 if (bs
->drv
== NULL
) {
2552 for (i
= 0; i
< num_reqs
; i
++) {
2553 reqs
[i
].error
= -ENOMEDIUM
;
2558 if (num_reqs
== 0) {
2562 // Create MultiwriteCB structure
2563 mcb
= g_malloc0(sizeof(*mcb
) + num_reqs
* sizeof(*mcb
->callbacks
));
2564 mcb
->num_requests
= 0;
2565 mcb
->num_callbacks
= num_reqs
;
2567 for (i
= 0; i
< num_reqs
; i
++) {
2568 mcb
->callbacks
[i
].cb
= reqs
[i
].cb
;
2569 mcb
->callbacks
[i
].opaque
= reqs
[i
].opaque
;
2572 // Check for mergable requests
2573 num_reqs
= multiwrite_merge(bs
, reqs
, num_reqs
, mcb
);
2575 trace_bdrv_aio_multiwrite(mcb
, mcb
->num_callbacks
, num_reqs
);
2578 * Run the aio requests. As soon as one request can't be submitted
2579 * successfully, fail all requests that are not yet submitted (we must
2580 * return failure for all requests anyway)
2582 * num_requests cannot be set to the right value immediately: If
2583 * bdrv_aio_writev fails for some request, num_requests would be too high
2584 * and therefore multiwrite_cb() would never recognize the multiwrite
2585 * request as completed. We also cannot use the loop variable i to set it
2586 * when the first request fails because the callback may already have been
2587 * called for previously submitted requests. Thus, num_requests must be
2588 * incremented for each request that is submitted.
2590 * The problem that callbacks may be called early also means that we need
2591 * to take care that num_requests doesn't become 0 before all requests are
2592 * submitted - multiwrite_cb() would consider the multiwrite request
2593 * completed. A dummy request that is "completed" by a manual call to
2594 * multiwrite_cb() takes care of this.
2596 mcb
->num_requests
= 1;
2598 // Run the aio requests
2599 for (i
= 0; i
< num_reqs
; i
++) {
2600 mcb
->num_requests
++;
2601 acb
= bdrv_aio_writev(bs
, reqs
[i
].sector
, reqs
[i
].qiov
,
2602 reqs
[i
].nb_sectors
, multiwrite_cb
, mcb
);
2605 // We can only fail the whole thing if no request has been
2606 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2607 // complete and report the error in the callback.
2609 trace_bdrv_aio_multiwrite_earlyfail(mcb
);
2612 trace_bdrv_aio_multiwrite_latefail(mcb
, i
);
2613 multiwrite_cb(mcb
, -EIO
);
2619 /* Complete the dummy request */
2620 multiwrite_cb(mcb
, 0);
2625 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2626 reqs
[i
].error
= -EIO
;
2632 BlockDriverAIOCB
*bdrv_aio_flush(BlockDriverState
*bs
,
2633 BlockDriverCompletionFunc
*cb
, void *opaque
)
2635 BlockDriver
*drv
= bs
->drv
;
2637 trace_bdrv_aio_flush(bs
, opaque
);
2639 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2640 return bdrv_aio_noop_em(bs
, cb
, opaque
);
2645 return drv
->bdrv_aio_flush(bs
, cb
, opaque
);
2648 void bdrv_aio_cancel(BlockDriverAIOCB
*acb
)
2650 acb
->pool
->cancel(acb
);
2654 /**************************************************************/
2655 /* async block device emulation */
2657 typedef struct BlockDriverAIOCBSync
{
2658 BlockDriverAIOCB common
;
2661 /* vector translation state */
2665 } BlockDriverAIOCBSync
;
2667 static void bdrv_aio_cancel_em(BlockDriverAIOCB
*blockacb
)
2669 BlockDriverAIOCBSync
*acb
=
2670 container_of(blockacb
, BlockDriverAIOCBSync
, common
);
2671 qemu_bh_delete(acb
->bh
);
2673 qemu_aio_release(acb
);
2676 static AIOPool bdrv_em_aio_pool
= {
2677 .aiocb_size
= sizeof(BlockDriverAIOCBSync
),
2678 .cancel
= bdrv_aio_cancel_em
,
2681 static void bdrv_aio_bh_cb(void *opaque
)
2683 BlockDriverAIOCBSync
*acb
= opaque
;
2686 qemu_iovec_from_buffer(acb
->qiov
, acb
->bounce
, acb
->qiov
->size
);
2687 qemu_vfree(acb
->bounce
);
2688 acb
->common
.cb(acb
->common
.opaque
, acb
->ret
);
2689 qemu_bh_delete(acb
->bh
);
2691 qemu_aio_release(acb
);
2694 static BlockDriverAIOCB
*bdrv_aio_rw_vector(BlockDriverState
*bs
,
2698 BlockDriverCompletionFunc
*cb
,
2703 BlockDriverAIOCBSync
*acb
;
2705 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2706 acb
->is_write
= is_write
;
2708 acb
->bounce
= qemu_blockalign(bs
, qiov
->size
);
2711 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2714 qemu_iovec_to_buffer(acb
->qiov
, acb
->bounce
);
2715 acb
->ret
= bdrv_write(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2717 acb
->ret
= bdrv_read(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2720 qemu_bh_schedule(acb
->bh
);
2722 return &acb
->common
;
2725 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
2726 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2727 BlockDriverCompletionFunc
*cb
, void *opaque
)
2729 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 0);
2732 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
2733 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2734 BlockDriverCompletionFunc
*cb
, void *opaque
)
2736 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 1);
2740 typedef struct BlockDriverAIOCBCoroutine
{
2741 BlockDriverAIOCB common
;
2745 } BlockDriverAIOCBCoroutine
;
2747 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB
*blockacb
)
2752 static AIOPool bdrv_em_co_aio_pool
= {
2753 .aiocb_size
= sizeof(BlockDriverAIOCBCoroutine
),
2754 .cancel
= bdrv_aio_co_cancel_em
,
2757 static void bdrv_co_rw_bh(void *opaque
)
2759 BlockDriverAIOCBCoroutine
*acb
= opaque
;
2761 acb
->common
.cb(acb
->common
.opaque
, acb
->req
.error
);
2762 qemu_bh_delete(acb
->bh
);
2763 qemu_aio_release(acb
);
2766 static void coroutine_fn
bdrv_co_rw(void *opaque
)
2768 BlockDriverAIOCBCoroutine
*acb
= opaque
;
2769 BlockDriverState
*bs
= acb
->common
.bs
;
2771 if (!acb
->is_write
) {
2772 acb
->req
.error
= bs
->drv
->bdrv_co_readv(bs
, acb
->req
.sector
,
2773 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2775 acb
->req
.error
= bs
->drv
->bdrv_co_writev(bs
, acb
->req
.sector
,
2776 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2779 acb
->bh
= qemu_bh_new(bdrv_co_rw_bh
, acb
);
2780 qemu_bh_schedule(acb
->bh
);
2783 static BlockDriverAIOCB
*bdrv_co_aio_rw_vector(BlockDriverState
*bs
,
2787 BlockDriverCompletionFunc
*cb
,
2792 BlockDriverAIOCBCoroutine
*acb
;
2794 acb
= qemu_aio_get(&bdrv_em_co_aio_pool
, bs
, cb
, opaque
);
2795 acb
->req
.sector
= sector_num
;
2796 acb
->req
.nb_sectors
= nb_sectors
;
2797 acb
->req
.qiov
= qiov
;
2798 acb
->is_write
= is_write
;
2800 co
= qemu_coroutine_create(bdrv_co_rw
);
2801 qemu_coroutine_enter(co
, acb
);
2803 return &acb
->common
;
2806 static BlockDriverAIOCB
*bdrv_co_aio_readv_em(BlockDriverState
*bs
,
2807 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2808 BlockDriverCompletionFunc
*cb
, void *opaque
)
2810 return bdrv_co_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
,
2814 static BlockDriverAIOCB
*bdrv_co_aio_writev_em(BlockDriverState
*bs
,
2815 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2816 BlockDriverCompletionFunc
*cb
, void *opaque
)
2818 return bdrv_co_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
,
2822 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
2823 BlockDriverCompletionFunc
*cb
, void *opaque
)
2825 BlockDriverAIOCBSync
*acb
;
2827 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2828 acb
->is_write
= 1; /* don't bounce in the completion hadler */
2834 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2837 qemu_bh_schedule(acb
->bh
);
2838 return &acb
->common
;
2841 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
2842 BlockDriverCompletionFunc
*cb
, void *opaque
)
2844 BlockDriverAIOCBSync
*acb
;
2846 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2847 acb
->is_write
= 1; /* don't bounce in the completion handler */
2853 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2856 qemu_bh_schedule(acb
->bh
);
2857 return &acb
->common
;
2860 /**************************************************************/
2861 /* sync block device emulation */
2863 static void bdrv_rw_em_cb(void *opaque
, int ret
)
2865 *(int *)opaque
= ret
;
2868 #define NOT_DONE 0x7fffffff
2870 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
2871 uint8_t *buf
, int nb_sectors
)
2874 BlockDriverAIOCB
*acb
;
2878 async_ret
= NOT_DONE
;
2879 iov
.iov_base
= (void *)buf
;
2880 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2881 qemu_iovec_init_external(&qiov
, &iov
, 1);
2882 acb
= bdrv_aio_readv(bs
, sector_num
, &qiov
, nb_sectors
,
2883 bdrv_rw_em_cb
, &async_ret
);
2889 while (async_ret
== NOT_DONE
) {
2898 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
2899 const uint8_t *buf
, int nb_sectors
)
2902 BlockDriverAIOCB
*acb
;
2906 async_ret
= NOT_DONE
;
2907 iov
.iov_base
= (void *)buf
;
2908 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2909 qemu_iovec_init_external(&qiov
, &iov
, 1);
2910 acb
= bdrv_aio_writev(bs
, sector_num
, &qiov
, nb_sectors
,
2911 bdrv_rw_em_cb
, &async_ret
);
2916 while (async_ret
== NOT_DONE
) {
2924 void bdrv_init(void)
2926 module_call_init(MODULE_INIT_BLOCK
);
2929 void bdrv_init_with_whitelist(void)
2931 use_bdrv_whitelist
= 1;
2935 void *qemu_aio_get(AIOPool
*pool
, BlockDriverState
*bs
,
2936 BlockDriverCompletionFunc
*cb
, void *opaque
)
2938 BlockDriverAIOCB
*acb
;
2940 if (pool
->free_aiocb
) {
2941 acb
= pool
->free_aiocb
;
2942 pool
->free_aiocb
= acb
->next
;
2944 acb
= g_malloc0(pool
->aiocb_size
);
2949 acb
->opaque
= opaque
;
2953 void qemu_aio_release(void *p
)
2955 BlockDriverAIOCB
*acb
= (BlockDriverAIOCB
*)p
;
2956 AIOPool
*pool
= acb
->pool
;
2957 acb
->next
= pool
->free_aiocb
;
2958 pool
->free_aiocb
= acb
;
2961 /**************************************************************/
2962 /* Coroutine block device emulation */
2964 typedef struct CoroutineIOCompletion
{
2965 Coroutine
*coroutine
;
2967 } CoroutineIOCompletion
;
2969 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
2971 CoroutineIOCompletion
*co
= opaque
;
2974 qemu_coroutine_enter(co
->coroutine
, NULL
);
2977 static int coroutine_fn
bdrv_co_io_em(BlockDriverState
*bs
, int64_t sector_num
,
2978 int nb_sectors
, QEMUIOVector
*iov
,
2981 CoroutineIOCompletion co
= {
2982 .coroutine
= qemu_coroutine_self(),
2984 BlockDriverAIOCB
*acb
;
2987 acb
= bdrv_aio_writev(bs
, sector_num
, iov
, nb_sectors
,
2988 bdrv_co_io_em_complete
, &co
);
2990 acb
= bdrv_aio_readv(bs
, sector_num
, iov
, nb_sectors
,
2991 bdrv_co_io_em_complete
, &co
);
2994 trace_bdrv_co_io(is_write
, acb
);
2998 qemu_coroutine_yield();
3003 static int coroutine_fn
bdrv_co_readv_em(BlockDriverState
*bs
,
3004 int64_t sector_num
, int nb_sectors
,
3007 return bdrv_co_io_em(bs
, sector_num
, nb_sectors
, iov
, false);
3010 static int coroutine_fn
bdrv_co_writev_em(BlockDriverState
*bs
,
3011 int64_t sector_num
, int nb_sectors
,
3014 return bdrv_co_io_em(bs
, sector_num
, nb_sectors
, iov
, true);
3017 static int coroutine_fn
bdrv_co_flush_em(BlockDriverState
*bs
)
3019 CoroutineIOCompletion co
= {
3020 .coroutine
= qemu_coroutine_self(),
3022 BlockDriverAIOCB
*acb
;
3024 acb
= bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
3028 qemu_coroutine_yield();
3032 /**************************************************************/
3033 /* removable device support */
3036 * Return TRUE if the media is present
3038 int bdrv_is_inserted(BlockDriverState
*bs
)
3040 BlockDriver
*drv
= bs
->drv
;
3044 if (!drv
->bdrv_is_inserted
)
3046 return drv
->bdrv_is_inserted(bs
);
3050 * Return whether the media changed since the last call to this
3051 * function, or -ENOTSUP if we don't know. Most drivers don't know.
3053 int bdrv_media_changed(BlockDriverState
*bs
)
3055 BlockDriver
*drv
= bs
->drv
;
3057 if (drv
&& drv
->bdrv_media_changed
) {
3058 return drv
->bdrv_media_changed(bs
);
3064 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3066 void bdrv_eject(BlockDriverState
*bs
, int eject_flag
)
3068 BlockDriver
*drv
= bs
->drv
;
3070 if (drv
&& drv
->bdrv_eject
) {
3071 drv
->bdrv_eject(bs
, eject_flag
);
3076 * Lock or unlock the media (if it is locked, the user won't be able
3077 * to eject it manually).
3079 void bdrv_lock_medium(BlockDriverState
*bs
, bool locked
)
3081 BlockDriver
*drv
= bs
->drv
;
3083 trace_bdrv_lock_medium(bs
, locked
);
3085 if (drv
&& drv
->bdrv_lock_medium
) {
3086 drv
->bdrv_lock_medium(bs
, locked
);
3090 /* needed for generic scsi interface */
3092 int bdrv_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
3094 BlockDriver
*drv
= bs
->drv
;
3096 if (drv
&& drv
->bdrv_ioctl
)
3097 return drv
->bdrv_ioctl(bs
, req
, buf
);
3101 BlockDriverAIOCB
*bdrv_aio_ioctl(BlockDriverState
*bs
,
3102 unsigned long int req
, void *buf
,
3103 BlockDriverCompletionFunc
*cb
, void *opaque
)
3105 BlockDriver
*drv
= bs
->drv
;
3107 if (drv
&& drv
->bdrv_aio_ioctl
)
3108 return drv
->bdrv_aio_ioctl(bs
, req
, buf
, cb
, opaque
);
3114 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
3116 return qemu_memalign((bs
&& bs
->buffer_alignment
) ? bs
->buffer_alignment
: 512, size
);
3119 void bdrv_set_dirty_tracking(BlockDriverState
*bs
, int enable
)
3121 int64_t bitmap_size
;
3123 bs
->dirty_count
= 0;
3125 if (!bs
->dirty_bitmap
) {
3126 bitmap_size
= (bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
) +
3127 BDRV_SECTORS_PER_DIRTY_CHUNK
* 8 - 1;
3128 bitmap_size
/= BDRV_SECTORS_PER_DIRTY_CHUNK
* 8;
3130 bs
->dirty_bitmap
= g_malloc0(bitmap_size
);
3133 if (bs
->dirty_bitmap
) {
3134 g_free(bs
->dirty_bitmap
);
3135 bs
->dirty_bitmap
= NULL
;
3140 int bdrv_get_dirty(BlockDriverState
*bs
, int64_t sector
)
3142 int64_t chunk
= sector
/ (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK
;
3144 if (bs
->dirty_bitmap
&&
3145 (sector
<< BDRV_SECTOR_BITS
) < bdrv_getlength(bs
)) {
3146 return !!(bs
->dirty_bitmap
[chunk
/ (sizeof(unsigned long) * 8)] &
3147 (1UL << (chunk
% (sizeof(unsigned long) * 8))));
3153 void bdrv_reset_dirty(BlockDriverState
*bs
, int64_t cur_sector
,
3156 set_dirty_bitmap(bs
, cur_sector
, nr_sectors
, 0);
3159 int64_t bdrv_get_dirty_count(BlockDriverState
*bs
)
3161 return bs
->dirty_count
;
3164 void bdrv_set_in_use(BlockDriverState
*bs
, int in_use
)
3166 assert(bs
->in_use
!= in_use
);
3167 bs
->in_use
= in_use
;
3170 int bdrv_in_use(BlockDriverState
*bs
)
3176 bdrv_acct_start(BlockDriverState
*bs
, BlockAcctCookie
*cookie
, int64_t bytes
,
3177 enum BlockAcctType type
)
3179 assert(type
< BDRV_MAX_IOTYPE
);
3181 cookie
->bytes
= bytes
;
3182 cookie
->start_time_ns
= get_clock();
3183 cookie
->type
= type
;
3187 bdrv_acct_done(BlockDriverState
*bs
, BlockAcctCookie
*cookie
)
3189 assert(cookie
->type
< BDRV_MAX_IOTYPE
);
3191 bs
->nr_bytes
[cookie
->type
] += cookie
->bytes
;
3192 bs
->nr_ops
[cookie
->type
]++;
3193 bs
->total_time_ns
[cookie
->type
] += get_clock() - cookie
->start_time_ns
;
3196 int bdrv_img_create(const char *filename
, const char *fmt
,
3197 const char *base_filename
, const char *base_fmt
,
3198 char *options
, uint64_t img_size
, int flags
)
3200 QEMUOptionParameter
*param
= NULL
, *create_options
= NULL
;
3201 QEMUOptionParameter
*backing_fmt
, *backing_file
, *size
;
3202 BlockDriverState
*bs
= NULL
;
3203 BlockDriver
*drv
, *proto_drv
;
3204 BlockDriver
*backing_drv
= NULL
;
3207 /* Find driver and parse its options */
3208 drv
= bdrv_find_format(fmt
);
3210 error_report("Unknown file format '%s'", fmt
);
3215 proto_drv
= bdrv_find_protocol(filename
);
3217 error_report("Unknown protocol '%s'", filename
);
3222 create_options
= append_option_parameters(create_options
,
3223 drv
->create_options
);
3224 create_options
= append_option_parameters(create_options
,
3225 proto_drv
->create_options
);
3227 /* Create parameter list with default values */
3228 param
= parse_option_parameters("", create_options
, param
);
3230 set_option_parameter_int(param
, BLOCK_OPT_SIZE
, img_size
);
3232 /* Parse -o options */
3234 param
= parse_option_parameters(options
, create_options
, param
);
3235 if (param
== NULL
) {
3236 error_report("Invalid options for file format '%s'.", fmt
);
3242 if (base_filename
) {
3243 if (set_option_parameter(param
, BLOCK_OPT_BACKING_FILE
,
3245 error_report("Backing file not supported for file format '%s'",
3253 if (set_option_parameter(param
, BLOCK_OPT_BACKING_FMT
, base_fmt
)) {
3254 error_report("Backing file format not supported for file "
3255 "format '%s'", fmt
);
3261 backing_file
= get_option_parameter(param
, BLOCK_OPT_BACKING_FILE
);
3262 if (backing_file
&& backing_file
->value
.s
) {
3263 if (!strcmp(filename
, backing_file
->value
.s
)) {
3264 error_report("Error: Trying to create an image with the "
3265 "same filename as the backing file");
3271 backing_fmt
= get_option_parameter(param
, BLOCK_OPT_BACKING_FMT
);
3272 if (backing_fmt
&& backing_fmt
->value
.s
) {
3273 backing_drv
= bdrv_find_format(backing_fmt
->value
.s
);
3275 error_report("Unknown backing file format '%s'",
3276 backing_fmt
->value
.s
);
3282 // The size for the image must always be specified, with one exception:
3283 // If we are using a backing file, we can obtain the size from there
3284 size
= get_option_parameter(param
, BLOCK_OPT_SIZE
);
3285 if (size
&& size
->value
.n
== -1) {
3286 if (backing_file
&& backing_file
->value
.s
) {
3292 ret
= bdrv_open(bs
, backing_file
->value
.s
, flags
, backing_drv
);
3294 error_report("Could not open '%s'", backing_file
->value
.s
);
3297 bdrv_get_geometry(bs
, &size
);
3300 snprintf(buf
, sizeof(buf
), "%" PRId64
, size
);
3301 set_option_parameter(param
, BLOCK_OPT_SIZE
, buf
);
3303 error_report("Image creation needs a size parameter");
3309 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
3310 print_option_parameters(param
);
3313 ret
= bdrv_create(drv
, filename
, param
);
3316 if (ret
== -ENOTSUP
) {
3317 error_report("Formatting or formatting option not supported for "
3318 "file format '%s'", fmt
);
3319 } else if (ret
== -EFBIG
) {
3320 error_report("The image size is too large for file format '%s'",
3323 error_report("%s: error while creating %s: %s", filename
, fmt
,
3329 free_option_parameters(create_options
);
3330 free_option_parameters(param
);