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 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
49 static void bdrv_dev_change_media_cb(BlockDriverState
*bs
, bool load
);
50 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
51 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
52 BlockDriverCompletionFunc
*cb
, void *opaque
);
53 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
54 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
55 BlockDriverCompletionFunc
*cb
, void *opaque
);
56 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
57 BlockDriverCompletionFunc
*cb
, void *opaque
);
58 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
59 BlockDriverCompletionFunc
*cb
, void *opaque
);
60 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
61 uint8_t *buf
, int nb_sectors
);
62 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
63 const uint8_t *buf
, int nb_sectors
);
64 static BlockDriverAIOCB
*bdrv_co_aio_readv_em(BlockDriverState
*bs
,
65 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
66 BlockDriverCompletionFunc
*cb
, void *opaque
);
67 static BlockDriverAIOCB
*bdrv_co_aio_writev_em(BlockDriverState
*bs
,
68 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
69 BlockDriverCompletionFunc
*cb
, void *opaque
);
70 static int coroutine_fn
bdrv_co_readv_em(BlockDriverState
*bs
,
71 int64_t sector_num
, int nb_sectors
,
73 static int coroutine_fn
bdrv_co_writev_em(BlockDriverState
*bs
,
74 int64_t sector_num
, int nb_sectors
,
76 static int coroutine_fn
bdrv_co_flush_em(BlockDriverState
*bs
);
77 static int coroutine_fn
bdrv_co_do_readv(BlockDriverState
*bs
,
78 int64_t sector_num
, int nb_sectors
, QEMUIOVector
*qiov
);
79 static int coroutine_fn
bdrv_co_do_writev(BlockDriverState
*bs
,
80 int64_t sector_num
, int nb_sectors
, QEMUIOVector
*qiov
);
81 static BlockDriverAIOCB
*bdrv_co_aio_rw_vector(BlockDriverState
*bs
,
85 BlockDriverCompletionFunc
*cb
,
88 CoroutineEntry
*entry
);
89 static void coroutine_fn
bdrv_co_do_rw(void *opaque
);
91 static QTAILQ_HEAD(, BlockDriverState
) bdrv_states
=
92 QTAILQ_HEAD_INITIALIZER(bdrv_states
);
94 static QLIST_HEAD(, BlockDriver
) bdrv_drivers
=
95 QLIST_HEAD_INITIALIZER(bdrv_drivers
);
97 /* The device to use for VM snapshots */
98 static BlockDriverState
*bs_snapshots
;
100 /* If non-zero, use only whitelisted block drivers */
101 static int use_bdrv_whitelist
;
104 static int is_windows_drive_prefix(const char *filename
)
106 return (((filename
[0] >= 'a' && filename
[0] <= 'z') ||
107 (filename
[0] >= 'A' && filename
[0] <= 'Z')) &&
111 int is_windows_drive(const char *filename
)
113 if (is_windows_drive_prefix(filename
) &&
116 if (strstart(filename
, "\\\\.\\", NULL
) ||
117 strstart(filename
, "//./", NULL
))
123 /* check if the path starts with "<protocol>:" */
124 static int path_has_protocol(const char *path
)
127 if (is_windows_drive(path
) ||
128 is_windows_drive_prefix(path
)) {
133 return strchr(path
, ':') != NULL
;
136 int path_is_absolute(const char *path
)
140 /* specific case for names like: "\\.\d:" */
141 if (*path
== '/' || *path
== '\\')
144 p
= strchr(path
, ':');
150 return (*p
== '/' || *p
== '\\');
156 /* if filename is absolute, just copy it to dest. Otherwise, build a
157 path to it by considering it is relative to base_path. URL are
159 void path_combine(char *dest
, int dest_size
,
160 const char *base_path
,
161 const char *filename
)
168 if (path_is_absolute(filename
)) {
169 pstrcpy(dest
, dest_size
, filename
);
171 p
= strchr(base_path
, ':');
176 p1
= strrchr(base_path
, '/');
180 p2
= strrchr(base_path
, '\\');
192 if (len
> dest_size
- 1)
194 memcpy(dest
, base_path
, len
);
196 pstrcat(dest
, dest_size
, filename
);
200 void bdrv_register(BlockDriver
*bdrv
)
202 if (bdrv
->bdrv_co_readv
) {
203 /* Emulate AIO by coroutines, and sync by AIO */
204 bdrv
->bdrv_aio_readv
= bdrv_co_aio_readv_em
;
205 bdrv
->bdrv_aio_writev
= bdrv_co_aio_writev_em
;
206 bdrv
->bdrv_read
= bdrv_read_em
;
207 bdrv
->bdrv_write
= bdrv_write_em
;
209 bdrv
->bdrv_co_readv
= bdrv_co_readv_em
;
210 bdrv
->bdrv_co_writev
= bdrv_co_writev_em
;
212 if (!bdrv
->bdrv_aio_readv
) {
213 /* add AIO emulation layer */
214 bdrv
->bdrv_aio_readv
= bdrv_aio_readv_em
;
215 bdrv
->bdrv_aio_writev
= bdrv_aio_writev_em
;
216 } else if (!bdrv
->bdrv_read
) {
217 /* add synchronous IO emulation layer */
218 bdrv
->bdrv_read
= bdrv_read_em
;
219 bdrv
->bdrv_write
= bdrv_write_em
;
223 if (!bdrv
->bdrv_aio_flush
)
224 bdrv
->bdrv_aio_flush
= bdrv_aio_flush_em
;
226 QLIST_INSERT_HEAD(&bdrv_drivers
, bdrv
, list
);
229 /* create a new block device (by default it is empty) */
230 BlockDriverState
*bdrv_new(const char *device_name
)
232 BlockDriverState
*bs
;
234 bs
= g_malloc0(sizeof(BlockDriverState
));
235 pstrcpy(bs
->device_name
, sizeof(bs
->device_name
), device_name
);
236 if (device_name
[0] != '\0') {
237 QTAILQ_INSERT_TAIL(&bdrv_states
, bs
, list
);
239 bdrv_iostatus_disable(bs
);
243 BlockDriver
*bdrv_find_format(const char *format_name
)
246 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
247 if (!strcmp(drv1
->format_name
, format_name
)) {
254 static int bdrv_is_whitelisted(BlockDriver
*drv
)
256 static const char *whitelist
[] = {
257 CONFIG_BDRV_WHITELIST
262 return 1; /* no whitelist, anything goes */
264 for (p
= whitelist
; *p
; p
++) {
265 if (!strcmp(drv
->format_name
, *p
)) {
272 BlockDriver
*bdrv_find_whitelisted_format(const char *format_name
)
274 BlockDriver
*drv
= bdrv_find_format(format_name
);
275 return drv
&& bdrv_is_whitelisted(drv
) ? drv
: NULL
;
278 int bdrv_create(BlockDriver
*drv
, const char* filename
,
279 QEMUOptionParameter
*options
)
281 if (!drv
->bdrv_create
)
284 return drv
->bdrv_create(filename
, options
);
287 int bdrv_create_file(const char* filename
, QEMUOptionParameter
*options
)
291 drv
= bdrv_find_protocol(filename
);
296 return bdrv_create(drv
, filename
, options
);
300 void get_tmp_filename(char *filename
, int size
)
302 char temp_dir
[MAX_PATH
];
304 GetTempPath(MAX_PATH
, temp_dir
);
305 GetTempFileName(temp_dir
, "qem", 0, filename
);
308 void get_tmp_filename(char *filename
, int size
)
312 /* XXX: race condition possible */
313 tmpdir
= getenv("TMPDIR");
316 snprintf(filename
, size
, "%s/vl.XXXXXX", tmpdir
);
317 fd
= mkstemp(filename
);
323 * Detect host devices. By convention, /dev/cdrom[N] is always
324 * recognized as a host CDROM.
326 static BlockDriver
*find_hdev_driver(const char *filename
)
328 int score_max
= 0, score
;
329 BlockDriver
*drv
= NULL
, *d
;
331 QLIST_FOREACH(d
, &bdrv_drivers
, list
) {
332 if (d
->bdrv_probe_device
) {
333 score
= d
->bdrv_probe_device(filename
);
334 if (score
> score_max
) {
344 BlockDriver
*bdrv_find_protocol(const char *filename
)
351 /* TODO Drivers without bdrv_file_open must be specified explicitly */
354 * XXX(hch): we really should not let host device detection
355 * override an explicit protocol specification, but moving this
356 * later breaks access to device names with colons in them.
357 * Thanks to the brain-dead persistent naming schemes on udev-
358 * based Linux systems those actually are quite common.
360 drv1
= find_hdev_driver(filename
);
365 if (!path_has_protocol(filename
)) {
366 return bdrv_find_format("file");
368 p
= strchr(filename
, ':');
371 if (len
> sizeof(protocol
) - 1)
372 len
= sizeof(protocol
) - 1;
373 memcpy(protocol
, filename
, len
);
374 protocol
[len
] = '\0';
375 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
376 if (drv1
->protocol_name
&&
377 !strcmp(drv1
->protocol_name
, protocol
)) {
384 static int find_image_format(const char *filename
, BlockDriver
**pdrv
)
386 int ret
, score
, score_max
;
387 BlockDriver
*drv1
, *drv
;
389 BlockDriverState
*bs
;
391 ret
= bdrv_file_open(&bs
, filename
, 0);
397 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
398 if (bs
->sg
|| !bdrv_is_inserted(bs
)) {
400 drv
= bdrv_find_format("raw");
408 ret
= bdrv_pread(bs
, 0, buf
, sizeof(buf
));
417 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
418 if (drv1
->bdrv_probe
) {
419 score
= drv1
->bdrv_probe(buf
, ret
, filename
);
420 if (score
> score_max
) {
434 * Set the current 'total_sectors' value
436 static int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
438 BlockDriver
*drv
= bs
->drv
;
440 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
444 /* query actual device if possible, otherwise just trust the hint */
445 if (drv
->bdrv_getlength
) {
446 int64_t length
= drv
->bdrv_getlength(bs
);
450 hint
= length
>> BDRV_SECTOR_BITS
;
453 bs
->total_sectors
= hint
;
458 * Set open flags for a given cache mode
460 * Return 0 on success, -1 if the cache mode was invalid.
462 int bdrv_parse_cache_flags(const char *mode
, int *flags
)
464 *flags
&= ~BDRV_O_CACHE_MASK
;
466 if (!strcmp(mode
, "off") || !strcmp(mode
, "none")) {
467 *flags
|= BDRV_O_NOCACHE
| BDRV_O_CACHE_WB
;
468 } else if (!strcmp(mode
, "directsync")) {
469 *flags
|= BDRV_O_NOCACHE
;
470 } else if (!strcmp(mode
, "writeback")) {
471 *flags
|= BDRV_O_CACHE_WB
;
472 } else if (!strcmp(mode
, "unsafe")) {
473 *flags
|= BDRV_O_CACHE_WB
;
474 *flags
|= BDRV_O_NO_FLUSH
;
475 } else if (!strcmp(mode
, "writethrough")) {
476 /* this is the default */
485 * Common part for opening disk images and files
487 static int bdrv_open_common(BlockDriverState
*bs
, const char *filename
,
488 int flags
, BlockDriver
*drv
)
494 trace_bdrv_open_common(bs
, filename
, flags
, drv
->format_name
);
497 bs
->total_sectors
= 0;
500 bs
->open_flags
= flags
;
501 bs
->buffer_alignment
= 512;
503 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
505 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
)) {
510 bs
->opaque
= g_malloc0(drv
->instance_size
);
512 if (flags
& BDRV_O_CACHE_WB
)
513 bs
->enable_write_cache
= 1;
516 * Clear flags that are internal to the block layer before opening the
519 open_flags
= flags
& ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
522 * Snapshots should be writable.
524 if (bs
->is_temporary
) {
525 open_flags
|= BDRV_O_RDWR
;
528 /* Open the image, either directly or using a protocol */
529 if (drv
->bdrv_file_open
) {
530 ret
= drv
->bdrv_file_open(bs
, filename
, open_flags
);
532 ret
= bdrv_file_open(&bs
->file
, filename
, open_flags
);
534 ret
= drv
->bdrv_open(bs
, open_flags
);
542 bs
->keep_read_only
= bs
->read_only
= !(open_flags
& BDRV_O_RDWR
);
544 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
550 if (bs
->is_temporary
) {
558 bdrv_delete(bs
->file
);
568 * Opens a file using a protocol (file, host_device, nbd, ...)
570 int bdrv_file_open(BlockDriverState
**pbs
, const char *filename
, int flags
)
572 BlockDriverState
*bs
;
576 drv
= bdrv_find_protocol(filename
);
582 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
593 * Opens a disk image (raw, qcow2, vmdk, ...)
595 int bdrv_open(BlockDriverState
*bs
, const char *filename
, int flags
,
600 if (flags
& BDRV_O_SNAPSHOT
) {
601 BlockDriverState
*bs1
;
604 BlockDriver
*bdrv_qcow2
;
605 QEMUOptionParameter
*options
;
606 char tmp_filename
[PATH_MAX
];
607 char backing_filename
[PATH_MAX
];
609 /* if snapshot, we create a temporary backing file and open it
610 instead of opening 'filename' directly */
612 /* if there is a backing file, use it */
614 ret
= bdrv_open(bs1
, filename
, 0, drv
);
619 total_size
= bdrv_getlength(bs1
) & BDRV_SECTOR_MASK
;
621 if (bs1
->drv
&& bs1
->drv
->protocol_name
)
626 get_tmp_filename(tmp_filename
, sizeof(tmp_filename
));
628 /* Real path is meaningless for protocols */
630 snprintf(backing_filename
, sizeof(backing_filename
),
632 else if (!realpath(filename
, backing_filename
))
635 bdrv_qcow2
= bdrv_find_format("qcow2");
636 options
= parse_option_parameters("", bdrv_qcow2
->create_options
, NULL
);
638 set_option_parameter_int(options
, BLOCK_OPT_SIZE
, total_size
);
639 set_option_parameter(options
, BLOCK_OPT_BACKING_FILE
, backing_filename
);
641 set_option_parameter(options
, BLOCK_OPT_BACKING_FMT
,
645 ret
= bdrv_create(bdrv_qcow2
, tmp_filename
, options
);
646 free_option_parameters(options
);
651 filename
= tmp_filename
;
653 bs
->is_temporary
= 1;
656 /* Find the right image format driver */
658 ret
= find_image_format(filename
, &drv
);
662 goto unlink_and_fail
;
666 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
668 goto unlink_and_fail
;
671 /* If there is a backing file, use it */
672 if ((flags
& BDRV_O_NO_BACKING
) == 0 && bs
->backing_file
[0] != '\0') {
673 char backing_filename
[PATH_MAX
];
675 BlockDriver
*back_drv
= NULL
;
677 bs
->backing_hd
= bdrv_new("");
679 if (path_has_protocol(bs
->backing_file
)) {
680 pstrcpy(backing_filename
, sizeof(backing_filename
),
683 path_combine(backing_filename
, sizeof(backing_filename
),
684 filename
, bs
->backing_file
);
687 if (bs
->backing_format
[0] != '\0') {
688 back_drv
= bdrv_find_format(bs
->backing_format
);
691 /* backing files always opened read-only */
693 flags
& ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
695 ret
= bdrv_open(bs
->backing_hd
, backing_filename
, back_flags
, back_drv
);
700 if (bs
->is_temporary
) {
701 bs
->backing_hd
->keep_read_only
= !(flags
& BDRV_O_RDWR
);
703 /* base image inherits from "parent" */
704 bs
->backing_hd
->keep_read_only
= bs
->keep_read_only
;
708 if (!bdrv_key_required(bs
)) {
709 bdrv_dev_change_media_cb(bs
, true);
715 if (bs
->is_temporary
) {
721 void bdrv_close(BlockDriverState
*bs
)
724 if (bs
== bs_snapshots
) {
727 if (bs
->backing_hd
) {
728 bdrv_delete(bs
->backing_hd
);
729 bs
->backing_hd
= NULL
;
731 bs
->drv
->bdrv_close(bs
);
734 if (bs
->is_temporary
) {
735 unlink(bs
->filename
);
741 if (bs
->file
!= NULL
) {
742 bdrv_close(bs
->file
);
745 bdrv_dev_change_media_cb(bs
, false);
749 void bdrv_close_all(void)
751 BlockDriverState
*bs
;
753 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
758 /* make a BlockDriverState anonymous by removing from bdrv_state list.
759 Also, NULL terminate the device_name to prevent double remove */
760 void bdrv_make_anon(BlockDriverState
*bs
)
762 if (bs
->device_name
[0] != '\0') {
763 QTAILQ_REMOVE(&bdrv_states
, bs
, list
);
765 bs
->device_name
[0] = '\0';
768 void bdrv_delete(BlockDriverState
*bs
)
772 /* remove from list, if necessary */
776 if (bs
->file
!= NULL
) {
777 bdrv_delete(bs
->file
);
780 assert(bs
!= bs_snapshots
);
784 int bdrv_attach_dev(BlockDriverState
*bs
, void *dev
)
785 /* TODO change to DeviceState *dev when all users are qdevified */
791 bdrv_iostatus_reset(bs
);
795 /* TODO qdevified devices don't use this, remove when devices are qdevified */
796 void bdrv_attach_dev_nofail(BlockDriverState
*bs
, void *dev
)
798 if (bdrv_attach_dev(bs
, dev
) < 0) {
803 void bdrv_detach_dev(BlockDriverState
*bs
, void *dev
)
804 /* TODO change to DeviceState *dev when all users are qdevified */
806 assert(bs
->dev
== dev
);
809 bs
->dev_opaque
= NULL
;
810 bs
->buffer_alignment
= 512;
813 /* TODO change to return DeviceState * when all users are qdevified */
814 void *bdrv_get_attached_dev(BlockDriverState
*bs
)
819 void bdrv_set_dev_ops(BlockDriverState
*bs
, const BlockDevOps
*ops
,
823 bs
->dev_opaque
= opaque
;
824 if (bdrv_dev_has_removable_media(bs
) && bs
== bs_snapshots
) {
829 static void bdrv_dev_change_media_cb(BlockDriverState
*bs
, bool load
)
831 if (bs
->dev_ops
&& bs
->dev_ops
->change_media_cb
) {
832 bs
->dev_ops
->change_media_cb(bs
->dev_opaque
, load
);
836 bool bdrv_dev_has_removable_media(BlockDriverState
*bs
)
838 return !bs
->dev
|| (bs
->dev_ops
&& bs
->dev_ops
->change_media_cb
);
841 bool bdrv_dev_is_tray_open(BlockDriverState
*bs
)
843 if (bs
->dev_ops
&& bs
->dev_ops
->is_tray_open
) {
844 return bs
->dev_ops
->is_tray_open(bs
->dev_opaque
);
849 static void bdrv_dev_resize_cb(BlockDriverState
*bs
)
851 if (bs
->dev_ops
&& bs
->dev_ops
->resize_cb
) {
852 bs
->dev_ops
->resize_cb(bs
->dev_opaque
);
856 bool bdrv_dev_is_medium_locked(BlockDriverState
*bs
)
858 if (bs
->dev_ops
&& bs
->dev_ops
->is_medium_locked
) {
859 return bs
->dev_ops
->is_medium_locked(bs
->dev_opaque
);
865 * Run consistency checks on an image
867 * Returns 0 if the check could be completed (it doesn't mean that the image is
868 * free of errors) or -errno when an internal error occurred. The results of the
869 * check are stored in res.
871 int bdrv_check(BlockDriverState
*bs
, BdrvCheckResult
*res
)
873 if (bs
->drv
->bdrv_check
== NULL
) {
877 memset(res
, 0, sizeof(*res
));
878 return bs
->drv
->bdrv_check(bs
, res
);
881 #define COMMIT_BUF_SECTORS 2048
883 /* commit COW file into the raw image */
884 int bdrv_commit(BlockDriverState
*bs
)
886 BlockDriver
*drv
= bs
->drv
;
887 BlockDriver
*backing_drv
;
888 int64_t sector
, total_sectors
;
889 int n
, ro
, open_flags
;
890 int ret
= 0, rw_ret
= 0;
893 BlockDriverState
*bs_rw
, *bs_ro
;
898 if (!bs
->backing_hd
) {
902 if (bs
->backing_hd
->keep_read_only
) {
906 backing_drv
= bs
->backing_hd
->drv
;
907 ro
= bs
->backing_hd
->read_only
;
908 strncpy(filename
, bs
->backing_hd
->filename
, sizeof(filename
));
909 open_flags
= bs
->backing_hd
->open_flags
;
913 bdrv_delete(bs
->backing_hd
);
914 bs
->backing_hd
= NULL
;
915 bs_rw
= bdrv_new("");
916 rw_ret
= bdrv_open(bs_rw
, filename
, open_flags
| BDRV_O_RDWR
,
920 /* try to re-open read-only */
921 bs_ro
= bdrv_new("");
922 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
,
926 /* drive not functional anymore */
930 bs
->backing_hd
= bs_ro
;
933 bs
->backing_hd
= bs_rw
;
936 total_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
937 buf
= g_malloc(COMMIT_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
939 for (sector
= 0; sector
< total_sectors
; sector
+= n
) {
940 if (drv
->bdrv_is_allocated(bs
, sector
, COMMIT_BUF_SECTORS
, &n
)) {
942 if (bdrv_read(bs
, sector
, buf
, n
) != 0) {
947 if (bdrv_write(bs
->backing_hd
, sector
, buf
, n
) != 0) {
954 if (drv
->bdrv_make_empty
) {
955 ret
= drv
->bdrv_make_empty(bs
);
960 * Make sure all data we wrote to the backing device is actually
964 bdrv_flush(bs
->backing_hd
);
971 bdrv_delete(bs
->backing_hd
);
972 bs
->backing_hd
= NULL
;
973 bs_ro
= bdrv_new("");
974 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
,
978 /* drive not functional anymore */
982 bs
->backing_hd
= bs_ro
;
983 bs
->backing_hd
->keep_read_only
= 0;
989 void bdrv_commit_all(void)
991 BlockDriverState
*bs
;
993 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1001 * -EINVAL - backing format specified, but no file
1002 * -ENOSPC - can't update the backing file because no space is left in the
1004 * -ENOTSUP - format driver doesn't support changing the backing file
1006 int bdrv_change_backing_file(BlockDriverState
*bs
,
1007 const char *backing_file
, const char *backing_fmt
)
1009 BlockDriver
*drv
= bs
->drv
;
1011 if (drv
->bdrv_change_backing_file
!= NULL
) {
1012 return drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
1018 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
1023 if (!bdrv_is_inserted(bs
))
1029 len
= bdrv_getlength(bs
);
1034 if ((offset
> len
) || (len
- offset
< size
))
1040 static int bdrv_check_request(BlockDriverState
*bs
, int64_t sector_num
,
1043 return bdrv_check_byte_request(bs
, sector_num
* BDRV_SECTOR_SIZE
,
1044 nb_sectors
* BDRV_SECTOR_SIZE
);
1047 static inline bool bdrv_has_async_rw(BlockDriver
*drv
)
1049 return drv
->bdrv_co_readv
!= bdrv_co_readv_em
1050 || drv
->bdrv_aio_readv
!= bdrv_aio_readv_em
;
1053 static inline bool bdrv_has_async_flush(BlockDriver
*drv
)
1055 return drv
->bdrv_aio_flush
!= bdrv_aio_flush_em
;
1058 typedef struct RwCo
{
1059 BlockDriverState
*bs
;
1067 static void coroutine_fn
bdrv_rw_co_entry(void *opaque
)
1069 RwCo
*rwco
= opaque
;
1071 if (!rwco
->is_write
) {
1072 rwco
->ret
= bdrv_co_do_readv(rwco
->bs
, rwco
->sector_num
,
1073 rwco
->nb_sectors
, rwco
->qiov
);
1075 rwco
->ret
= bdrv_co_do_writev(rwco
->bs
, rwco
->sector_num
,
1076 rwco
->nb_sectors
, rwco
->qiov
);
1081 * Process a synchronous request using coroutines
1083 static int bdrv_rw_co(BlockDriverState
*bs
, int64_t sector_num
, uint8_t *buf
,
1084 int nb_sectors
, bool is_write
)
1087 struct iovec iov
= {
1088 .iov_base
= (void *)buf
,
1089 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
1094 .sector_num
= sector_num
,
1095 .nb_sectors
= nb_sectors
,
1097 .is_write
= is_write
,
1101 qemu_iovec_init_external(&qiov
, &iov
, 1);
1103 if (qemu_in_coroutine()) {
1104 /* Fast-path if already in coroutine context */
1105 bdrv_rw_co_entry(&rwco
);
1107 co
= qemu_coroutine_create(bdrv_rw_co_entry
);
1108 qemu_coroutine_enter(co
, &rwco
);
1109 while (rwco
.ret
== NOT_DONE
) {
1116 /* return < 0 if error. See bdrv_write() for the return codes */
1117 int bdrv_read(BlockDriverState
*bs
, int64_t sector_num
,
1118 uint8_t *buf
, int nb_sectors
)
1120 return bdrv_rw_co(bs
, sector_num
, buf
, nb_sectors
, false);
1123 static void set_dirty_bitmap(BlockDriverState
*bs
, int64_t sector_num
,
1124 int nb_sectors
, int dirty
)
1127 unsigned long val
, idx
, bit
;
1129 start
= sector_num
/ BDRV_SECTORS_PER_DIRTY_CHUNK
;
1130 end
= (sector_num
+ nb_sectors
- 1) / BDRV_SECTORS_PER_DIRTY_CHUNK
;
1132 for (; start
<= end
; start
++) {
1133 idx
= start
/ (sizeof(unsigned long) * 8);
1134 bit
= start
% (sizeof(unsigned long) * 8);
1135 val
= bs
->dirty_bitmap
[idx
];
1137 if (!(val
& (1UL << bit
))) {
1142 if (val
& (1UL << bit
)) {
1144 val
&= ~(1UL << bit
);
1147 bs
->dirty_bitmap
[idx
] = val
;
1151 /* Return < 0 if error. Important errors are:
1152 -EIO generic I/O error (may happen for all errors)
1153 -ENOMEDIUM No media inserted.
1154 -EINVAL Invalid sector number or nb_sectors
1155 -EACCES Trying to write a read-only device
1157 int bdrv_write(BlockDriverState
*bs
, int64_t sector_num
,
1158 const uint8_t *buf
, int nb_sectors
)
1160 return bdrv_rw_co(bs
, sector_num
, (uint8_t *)buf
, nb_sectors
, true);
1163 int bdrv_pread(BlockDriverState
*bs
, int64_t offset
,
1164 void *buf
, int count1
)
1166 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1167 int len
, nb_sectors
, count
;
1172 /* first read to align to sector start */
1173 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1176 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1178 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1180 memcpy(buf
, tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), len
);
1188 /* read the sectors "in place" */
1189 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1190 if (nb_sectors
> 0) {
1191 if ((ret
= bdrv_read(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1193 sector_num
+= nb_sectors
;
1194 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1199 /* add data from the last sector */
1201 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1203 memcpy(buf
, tmp_buf
, count
);
1208 int bdrv_pwrite(BlockDriverState
*bs
, int64_t offset
,
1209 const void *buf
, int count1
)
1211 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1212 int len
, nb_sectors
, count
;
1217 /* first write to align to sector start */
1218 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1221 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1223 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1225 memcpy(tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), buf
, len
);
1226 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1235 /* write the sectors "in place" */
1236 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1237 if (nb_sectors
> 0) {
1238 if ((ret
= bdrv_write(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1240 sector_num
+= nb_sectors
;
1241 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1246 /* add data from the last sector */
1248 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1250 memcpy(tmp_buf
, buf
, count
);
1251 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1258 * Writes to the file and ensures that no writes are reordered across this
1259 * request (acts as a barrier)
1261 * Returns 0 on success, -errno in error cases.
1263 int bdrv_pwrite_sync(BlockDriverState
*bs
, int64_t offset
,
1264 const void *buf
, int count
)
1268 ret
= bdrv_pwrite(bs
, offset
, buf
, count
);
1273 /* No flush needed for cache modes that use O_DSYNC */
1274 if ((bs
->open_flags
& BDRV_O_CACHE_WB
) != 0) {
1282 * Handle a read request in coroutine context
1284 static int coroutine_fn
bdrv_co_do_readv(BlockDriverState
*bs
,
1285 int64_t sector_num
, int nb_sectors
, QEMUIOVector
*qiov
)
1287 BlockDriver
*drv
= bs
->drv
;
1292 if (bdrv_check_request(bs
, sector_num
, nb_sectors
)) {
1296 return drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1299 int coroutine_fn
bdrv_co_readv(BlockDriverState
*bs
, int64_t sector_num
,
1300 int nb_sectors
, QEMUIOVector
*qiov
)
1302 trace_bdrv_co_readv(bs
, sector_num
, nb_sectors
);
1304 return bdrv_co_do_readv(bs
, sector_num
, nb_sectors
, qiov
);
1308 * Handle a write request in coroutine context
1310 static int coroutine_fn
bdrv_co_do_writev(BlockDriverState
*bs
,
1311 int64_t sector_num
, int nb_sectors
, QEMUIOVector
*qiov
)
1313 BlockDriver
*drv
= bs
->drv
;
1319 if (bs
->read_only
) {
1322 if (bdrv_check_request(bs
, sector_num
, nb_sectors
)) {
1326 ret
= drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
);
1328 if (bs
->dirty_bitmap
) {
1329 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1332 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1333 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1339 int coroutine_fn
bdrv_co_writev(BlockDriverState
*bs
, int64_t sector_num
,
1340 int nb_sectors
, QEMUIOVector
*qiov
)
1342 trace_bdrv_co_writev(bs
, sector_num
, nb_sectors
);
1344 return bdrv_co_do_writev(bs
, sector_num
, nb_sectors
, qiov
);
1348 * Truncate file to 'offset' bytes (needed only for file protocols)
1350 int bdrv_truncate(BlockDriverState
*bs
, int64_t offset
)
1352 BlockDriver
*drv
= bs
->drv
;
1356 if (!drv
->bdrv_truncate
)
1360 if (bdrv_in_use(bs
))
1362 ret
= drv
->bdrv_truncate(bs
, offset
);
1364 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
1365 bdrv_dev_resize_cb(bs
);
1371 * Length of a allocated file in bytes. Sparse files are counted by actual
1372 * allocated space. Return < 0 if error or unknown.
1374 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
1376 BlockDriver
*drv
= bs
->drv
;
1380 if (drv
->bdrv_get_allocated_file_size
) {
1381 return drv
->bdrv_get_allocated_file_size(bs
);
1384 return bdrv_get_allocated_file_size(bs
->file
);
1390 * Length of a file in bytes. Return < 0 if error or unknown.
1392 int64_t bdrv_getlength(BlockDriverState
*bs
)
1394 BlockDriver
*drv
= bs
->drv
;
1398 if (bs
->growable
|| bdrv_dev_has_removable_media(bs
)) {
1399 if (drv
->bdrv_getlength
) {
1400 return drv
->bdrv_getlength(bs
);
1403 return bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1406 /* return 0 as number of sectors if no device present or error */
1407 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
1410 length
= bdrv_getlength(bs
);
1414 length
= length
>> BDRV_SECTOR_BITS
;
1415 *nb_sectors_ptr
= length
;
1419 uint8_t boot_ind
; /* 0x80 - active */
1420 uint8_t head
; /* starting head */
1421 uint8_t sector
; /* starting sector */
1422 uint8_t cyl
; /* starting cylinder */
1423 uint8_t sys_ind
; /* What partition type */
1424 uint8_t end_head
; /* end head */
1425 uint8_t end_sector
; /* end sector */
1426 uint8_t end_cyl
; /* end cylinder */
1427 uint32_t start_sect
; /* starting sector counting from 0 */
1428 uint32_t nr_sects
; /* nr of sectors in partition */
1431 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1432 static int guess_disk_lchs(BlockDriverState
*bs
,
1433 int *pcylinders
, int *pheads
, int *psectors
)
1435 uint8_t buf
[BDRV_SECTOR_SIZE
];
1436 int ret
, i
, heads
, sectors
, cylinders
;
1437 struct partition
*p
;
1439 uint64_t nb_sectors
;
1441 bdrv_get_geometry(bs
, &nb_sectors
);
1443 ret
= bdrv_read(bs
, 0, buf
, 1);
1446 /* test msdos magic */
1447 if (buf
[510] != 0x55 || buf
[511] != 0xaa)
1449 for(i
= 0; i
< 4; i
++) {
1450 p
= ((struct partition
*)(buf
+ 0x1be)) + i
;
1451 nr_sects
= le32_to_cpu(p
->nr_sects
);
1452 if (nr_sects
&& p
->end_head
) {
1453 /* We make the assumption that the partition terminates on
1454 a cylinder boundary */
1455 heads
= p
->end_head
+ 1;
1456 sectors
= p
->end_sector
& 63;
1459 cylinders
= nb_sectors
/ (heads
* sectors
);
1460 if (cylinders
< 1 || cylinders
> 16383)
1463 *psectors
= sectors
;
1464 *pcylinders
= cylinders
;
1466 printf("guessed geometry: LCHS=%d %d %d\n",
1467 cylinders
, heads
, sectors
);
1475 void bdrv_guess_geometry(BlockDriverState
*bs
, int *pcyls
, int *pheads
, int *psecs
)
1477 int translation
, lba_detected
= 0;
1478 int cylinders
, heads
, secs
;
1479 uint64_t nb_sectors
;
1481 /* if a geometry hint is available, use it */
1482 bdrv_get_geometry(bs
, &nb_sectors
);
1483 bdrv_get_geometry_hint(bs
, &cylinders
, &heads
, &secs
);
1484 translation
= bdrv_get_translation_hint(bs
);
1485 if (cylinders
!= 0) {
1490 if (guess_disk_lchs(bs
, &cylinders
, &heads
, &secs
) == 0) {
1492 /* if heads > 16, it means that a BIOS LBA
1493 translation was active, so the default
1494 hardware geometry is OK */
1496 goto default_geometry
;
1501 /* disable any translation to be in sync with
1502 the logical geometry */
1503 if (translation
== BIOS_ATA_TRANSLATION_AUTO
) {
1504 bdrv_set_translation_hint(bs
,
1505 BIOS_ATA_TRANSLATION_NONE
);
1510 /* if no geometry, use a standard physical disk geometry */
1511 cylinders
= nb_sectors
/ (16 * 63);
1513 if (cylinders
> 16383)
1515 else if (cylinders
< 2)
1520 if ((lba_detected
== 1) && (translation
== BIOS_ATA_TRANSLATION_AUTO
)) {
1521 if ((*pcyls
* *pheads
) <= 131072) {
1522 bdrv_set_translation_hint(bs
,
1523 BIOS_ATA_TRANSLATION_LARGE
);
1525 bdrv_set_translation_hint(bs
,
1526 BIOS_ATA_TRANSLATION_LBA
);
1530 bdrv_set_geometry_hint(bs
, *pcyls
, *pheads
, *psecs
);
1534 void bdrv_set_geometry_hint(BlockDriverState
*bs
,
1535 int cyls
, int heads
, int secs
)
1542 void bdrv_set_translation_hint(BlockDriverState
*bs
, int translation
)
1544 bs
->translation
= translation
;
1547 void bdrv_get_geometry_hint(BlockDriverState
*bs
,
1548 int *pcyls
, int *pheads
, int *psecs
)
1551 *pheads
= bs
->heads
;
1555 /* Recognize floppy formats */
1556 typedef struct FDFormat
{
1563 static const FDFormat fd_formats
[] = {
1564 /* First entry is default format */
1565 /* 1.44 MB 3"1/2 floppy disks */
1566 { FDRIVE_DRV_144
, 18, 80, 1, },
1567 { FDRIVE_DRV_144
, 20, 80, 1, },
1568 { FDRIVE_DRV_144
, 21, 80, 1, },
1569 { FDRIVE_DRV_144
, 21, 82, 1, },
1570 { FDRIVE_DRV_144
, 21, 83, 1, },
1571 { FDRIVE_DRV_144
, 22, 80, 1, },
1572 { FDRIVE_DRV_144
, 23, 80, 1, },
1573 { FDRIVE_DRV_144
, 24, 80, 1, },
1574 /* 2.88 MB 3"1/2 floppy disks */
1575 { FDRIVE_DRV_288
, 36, 80, 1, },
1576 { FDRIVE_DRV_288
, 39, 80, 1, },
1577 { FDRIVE_DRV_288
, 40, 80, 1, },
1578 { FDRIVE_DRV_288
, 44, 80, 1, },
1579 { FDRIVE_DRV_288
, 48, 80, 1, },
1580 /* 720 kB 3"1/2 floppy disks */
1581 { FDRIVE_DRV_144
, 9, 80, 1, },
1582 { FDRIVE_DRV_144
, 10, 80, 1, },
1583 { FDRIVE_DRV_144
, 10, 82, 1, },
1584 { FDRIVE_DRV_144
, 10, 83, 1, },
1585 { FDRIVE_DRV_144
, 13, 80, 1, },
1586 { FDRIVE_DRV_144
, 14, 80, 1, },
1587 /* 1.2 MB 5"1/4 floppy disks */
1588 { FDRIVE_DRV_120
, 15, 80, 1, },
1589 { FDRIVE_DRV_120
, 18, 80, 1, },
1590 { FDRIVE_DRV_120
, 18, 82, 1, },
1591 { FDRIVE_DRV_120
, 18, 83, 1, },
1592 { FDRIVE_DRV_120
, 20, 80, 1, },
1593 /* 720 kB 5"1/4 floppy disks */
1594 { FDRIVE_DRV_120
, 9, 80, 1, },
1595 { FDRIVE_DRV_120
, 11, 80, 1, },
1596 /* 360 kB 5"1/4 floppy disks */
1597 { FDRIVE_DRV_120
, 9, 40, 1, },
1598 { FDRIVE_DRV_120
, 9, 40, 0, },
1599 { FDRIVE_DRV_120
, 10, 41, 1, },
1600 { FDRIVE_DRV_120
, 10, 42, 1, },
1601 /* 320 kB 5"1/4 floppy disks */
1602 { FDRIVE_DRV_120
, 8, 40, 1, },
1603 { FDRIVE_DRV_120
, 8, 40, 0, },
1604 /* 360 kB must match 5"1/4 better than 3"1/2... */
1605 { FDRIVE_DRV_144
, 9, 80, 0, },
1607 { FDRIVE_DRV_NONE
, -1, -1, 0, },
1610 void bdrv_get_floppy_geometry_hint(BlockDriverState
*bs
, int *nb_heads
,
1611 int *max_track
, int *last_sect
,
1612 FDriveType drive_in
, FDriveType
*drive
)
1614 const FDFormat
*parse
;
1615 uint64_t nb_sectors
, size
;
1616 int i
, first_match
, match
;
1618 bdrv_get_geometry_hint(bs
, nb_heads
, max_track
, last_sect
);
1619 if (*nb_heads
!= 0 && *max_track
!= 0 && *last_sect
!= 0) {
1620 /* User defined disk */
1622 bdrv_get_geometry(bs
, &nb_sectors
);
1625 for (i
= 0; ; i
++) {
1626 parse
= &fd_formats
[i
];
1627 if (parse
->drive
== FDRIVE_DRV_NONE
) {
1630 if (drive_in
== parse
->drive
||
1631 drive_in
== FDRIVE_DRV_NONE
) {
1632 size
= (parse
->max_head
+ 1) * parse
->max_track
*
1634 if (nb_sectors
== size
) {
1638 if (first_match
== -1) {
1644 if (first_match
== -1) {
1647 match
= first_match
;
1649 parse
= &fd_formats
[match
];
1651 *nb_heads
= parse
->max_head
+ 1;
1652 *max_track
= parse
->max_track
;
1653 *last_sect
= parse
->last_sect
;
1654 *drive
= parse
->drive
;
1658 int bdrv_get_translation_hint(BlockDriverState
*bs
)
1660 return bs
->translation
;
1663 void bdrv_set_on_error(BlockDriverState
*bs
, BlockErrorAction on_read_error
,
1664 BlockErrorAction on_write_error
)
1666 bs
->on_read_error
= on_read_error
;
1667 bs
->on_write_error
= on_write_error
;
1670 BlockErrorAction
bdrv_get_on_error(BlockDriverState
*bs
, int is_read
)
1672 return is_read
? bs
->on_read_error
: bs
->on_write_error
;
1675 int bdrv_is_read_only(BlockDriverState
*bs
)
1677 return bs
->read_only
;
1680 int bdrv_is_sg(BlockDriverState
*bs
)
1685 int bdrv_enable_write_cache(BlockDriverState
*bs
)
1687 return bs
->enable_write_cache
;
1690 int bdrv_is_encrypted(BlockDriverState
*bs
)
1692 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1694 return bs
->encrypted
;
1697 int bdrv_key_required(BlockDriverState
*bs
)
1699 BlockDriverState
*backing_hd
= bs
->backing_hd
;
1701 if (backing_hd
&& backing_hd
->encrypted
&& !backing_hd
->valid_key
)
1703 return (bs
->encrypted
&& !bs
->valid_key
);
1706 int bdrv_set_key(BlockDriverState
*bs
, const char *key
)
1709 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
) {
1710 ret
= bdrv_set_key(bs
->backing_hd
, key
);
1716 if (!bs
->encrypted
) {
1718 } else if (!bs
->drv
|| !bs
->drv
->bdrv_set_key
) {
1721 ret
= bs
->drv
->bdrv_set_key(bs
, key
);
1724 } else if (!bs
->valid_key
) {
1726 /* call the change callback now, we skipped it on open */
1727 bdrv_dev_change_media_cb(bs
, true);
1732 void bdrv_get_format(BlockDriverState
*bs
, char *buf
, int buf_size
)
1737 pstrcpy(buf
, buf_size
, bs
->drv
->format_name
);
1741 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
1746 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
1747 it(opaque
, drv
->format_name
);
1751 BlockDriverState
*bdrv_find(const char *name
)
1753 BlockDriverState
*bs
;
1755 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1756 if (!strcmp(name
, bs
->device_name
)) {
1763 BlockDriverState
*bdrv_next(BlockDriverState
*bs
)
1766 return QTAILQ_FIRST(&bdrv_states
);
1768 return QTAILQ_NEXT(bs
, list
);
1771 void bdrv_iterate(void (*it
)(void *opaque
, BlockDriverState
*bs
), void *opaque
)
1773 BlockDriverState
*bs
;
1775 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1780 const char *bdrv_get_device_name(BlockDriverState
*bs
)
1782 return bs
->device_name
;
1785 int bdrv_flush(BlockDriverState
*bs
)
1787 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
1791 if (bs
->drv
&& bdrv_has_async_flush(bs
->drv
) && qemu_in_coroutine()) {
1792 return bdrv_co_flush_em(bs
);
1795 if (bs
->drv
&& bs
->drv
->bdrv_flush
) {
1796 return bs
->drv
->bdrv_flush(bs
);
1800 * Some block drivers always operate in either writethrough or unsafe mode
1801 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1802 * the server works (because the behaviour is hardcoded or depends on
1803 * server-side configuration), so we can't ensure that everything is safe
1804 * on disk. Returning an error doesn't work because that would break guests
1805 * even if the server operates in writethrough mode.
1807 * Let's hope the user knows what he's doing.
1812 void bdrv_flush_all(void)
1814 BlockDriverState
*bs
;
1816 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1817 if (!bdrv_is_read_only(bs
) && bdrv_is_inserted(bs
)) {
1823 int bdrv_has_zero_init(BlockDriverState
*bs
)
1827 if (bs
->drv
->bdrv_has_zero_init
) {
1828 return bs
->drv
->bdrv_has_zero_init(bs
);
1834 int bdrv_discard(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
)
1839 if (!bs
->drv
->bdrv_discard
) {
1842 return bs
->drv
->bdrv_discard(bs
, sector_num
, nb_sectors
);
1846 * Returns true iff the specified sector is present in the disk image. Drivers
1847 * not implementing the functionality are assumed to not support backing files,
1848 * hence all their sectors are reported as allocated.
1850 * 'pnum' is set to the number of sectors (including and immediately following
1851 * the specified sector) that are known to be in the same
1852 * allocated/unallocated state.
1854 * 'nb_sectors' is the max value 'pnum' should be set to.
1856 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
,
1860 if (!bs
->drv
->bdrv_is_allocated
) {
1861 if (sector_num
>= bs
->total_sectors
) {
1865 n
= bs
->total_sectors
- sector_num
;
1866 *pnum
= (n
< nb_sectors
) ? (n
) : (nb_sectors
);
1869 return bs
->drv
->bdrv_is_allocated(bs
, sector_num
, nb_sectors
, pnum
);
1872 void bdrv_mon_event(const BlockDriverState
*bdrv
,
1873 BlockMonEventAction action
, int is_read
)
1876 const char *action_str
;
1879 case BDRV_ACTION_REPORT
:
1880 action_str
= "report";
1882 case BDRV_ACTION_IGNORE
:
1883 action_str
= "ignore";
1885 case BDRV_ACTION_STOP
:
1886 action_str
= "stop";
1892 data
= qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1895 is_read
? "read" : "write");
1896 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR
, data
);
1898 qobject_decref(data
);
1901 static void bdrv_print_dict(QObject
*obj
, void *opaque
)
1904 Monitor
*mon
= opaque
;
1906 bs_dict
= qobject_to_qdict(obj
);
1908 monitor_printf(mon
, "%s: removable=%d",
1909 qdict_get_str(bs_dict
, "device"),
1910 qdict_get_bool(bs_dict
, "removable"));
1912 if (qdict_get_bool(bs_dict
, "removable")) {
1913 monitor_printf(mon
, " locked=%d", qdict_get_bool(bs_dict
, "locked"));
1914 monitor_printf(mon
, " tray-open=%d",
1915 qdict_get_bool(bs_dict
, "tray-open"));
1918 if (qdict_haskey(bs_dict
, "io-status")) {
1919 monitor_printf(mon
, " io-status=%s", qdict_get_str(bs_dict
, "io-status"));
1922 if (qdict_haskey(bs_dict
, "inserted")) {
1923 QDict
*qdict
= qobject_to_qdict(qdict_get(bs_dict
, "inserted"));
1925 monitor_printf(mon
, " file=");
1926 monitor_print_filename(mon
, qdict_get_str(qdict
, "file"));
1927 if (qdict_haskey(qdict
, "backing_file")) {
1928 monitor_printf(mon
, " backing_file=");
1929 monitor_print_filename(mon
, qdict_get_str(qdict
, "backing_file"));
1931 monitor_printf(mon
, " ro=%d drv=%s encrypted=%d",
1932 qdict_get_bool(qdict
, "ro"),
1933 qdict_get_str(qdict
, "drv"),
1934 qdict_get_bool(qdict
, "encrypted"));
1936 monitor_printf(mon
, " [not inserted]");
1939 monitor_printf(mon
, "\n");
1942 void bdrv_info_print(Monitor
*mon
, const QObject
*data
)
1944 qlist_iter(qobject_to_qlist(data
), bdrv_print_dict
, mon
);
1947 static const char *const io_status_name
[BDRV_IOS_MAX
] = {
1948 [BDRV_IOS_OK
] = "ok",
1949 [BDRV_IOS_FAILED
] = "failed",
1950 [BDRV_IOS_ENOSPC
] = "nospace",
1953 void bdrv_info(Monitor
*mon
, QObject
**ret_data
)
1956 BlockDriverState
*bs
;
1958 bs_list
= qlist_new();
1960 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1964 bs_obj
= qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
1965 "'removable': %i, 'locked': %i }",
1967 bdrv_dev_has_removable_media(bs
),
1968 bdrv_dev_is_medium_locked(bs
));
1969 bs_dict
= qobject_to_qdict(bs_obj
);
1971 if (bdrv_dev_has_removable_media(bs
)) {
1972 qdict_put(bs_dict
, "tray-open",
1973 qbool_from_int(bdrv_dev_is_tray_open(bs
)));
1976 if (bdrv_iostatus_is_enabled(bs
)) {
1977 qdict_put(bs_dict
, "io-status",
1978 qstring_from_str(io_status_name
[bs
->iostatus
]));
1984 obj
= qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1985 "'encrypted': %i }",
1986 bs
->filename
, bs
->read_only
,
1987 bs
->drv
->format_name
,
1988 bdrv_is_encrypted(bs
));
1989 if (bs
->backing_file
[0] != '\0') {
1990 QDict
*qdict
= qobject_to_qdict(obj
);
1991 qdict_put(qdict
, "backing_file",
1992 qstring_from_str(bs
->backing_file
));
1995 qdict_put_obj(bs_dict
, "inserted", obj
);
1997 qlist_append_obj(bs_list
, bs_obj
);
2000 *ret_data
= QOBJECT(bs_list
);
2003 static void bdrv_stats_iter(QObject
*data
, void *opaque
)
2006 Monitor
*mon
= opaque
;
2008 qdict
= qobject_to_qdict(data
);
2009 monitor_printf(mon
, "%s:", qdict_get_str(qdict
, "device"));
2011 qdict
= qobject_to_qdict(qdict_get(qdict
, "stats"));
2012 monitor_printf(mon
, " rd_bytes=%" PRId64
2013 " wr_bytes=%" PRId64
2014 " rd_operations=%" PRId64
2015 " wr_operations=%" PRId64
2016 " flush_operations=%" PRId64
2017 " wr_total_time_ns=%" PRId64
2018 " rd_total_time_ns=%" PRId64
2019 " flush_total_time_ns=%" PRId64
2021 qdict_get_int(qdict
, "rd_bytes"),
2022 qdict_get_int(qdict
, "wr_bytes"),
2023 qdict_get_int(qdict
, "rd_operations"),
2024 qdict_get_int(qdict
, "wr_operations"),
2025 qdict_get_int(qdict
, "flush_operations"),
2026 qdict_get_int(qdict
, "wr_total_time_ns"),
2027 qdict_get_int(qdict
, "rd_total_time_ns"),
2028 qdict_get_int(qdict
, "flush_total_time_ns"));
2031 void bdrv_stats_print(Monitor
*mon
, const QObject
*data
)
2033 qlist_iter(qobject_to_qlist(data
), bdrv_stats_iter
, mon
);
2036 static QObject
* bdrv_info_stats_bs(BlockDriverState
*bs
)
2041 res
= qobject_from_jsonf("{ 'stats': {"
2042 "'rd_bytes': %" PRId64
","
2043 "'wr_bytes': %" PRId64
","
2044 "'rd_operations': %" PRId64
","
2045 "'wr_operations': %" PRId64
","
2046 "'wr_highest_offset': %" PRId64
","
2047 "'flush_operations': %" PRId64
","
2048 "'wr_total_time_ns': %" PRId64
","
2049 "'rd_total_time_ns': %" PRId64
","
2050 "'flush_total_time_ns': %" PRId64
2052 bs
->nr_bytes
[BDRV_ACCT_READ
],
2053 bs
->nr_bytes
[BDRV_ACCT_WRITE
],
2054 bs
->nr_ops
[BDRV_ACCT_READ
],
2055 bs
->nr_ops
[BDRV_ACCT_WRITE
],
2056 bs
->wr_highest_sector
*
2057 (uint64_t)BDRV_SECTOR_SIZE
,
2058 bs
->nr_ops
[BDRV_ACCT_FLUSH
],
2059 bs
->total_time_ns
[BDRV_ACCT_WRITE
],
2060 bs
->total_time_ns
[BDRV_ACCT_READ
],
2061 bs
->total_time_ns
[BDRV_ACCT_FLUSH
]);
2062 dict
= qobject_to_qdict(res
);
2064 if (*bs
->device_name
) {
2065 qdict_put(dict
, "device", qstring_from_str(bs
->device_name
));
2069 QObject
*parent
= bdrv_info_stats_bs(bs
->file
);
2070 qdict_put_obj(dict
, "parent", parent
);
2076 void bdrv_info_stats(Monitor
*mon
, QObject
**ret_data
)
2080 BlockDriverState
*bs
;
2082 devices
= qlist_new();
2084 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
2085 obj
= bdrv_info_stats_bs(bs
);
2086 qlist_append_obj(devices
, obj
);
2089 *ret_data
= QOBJECT(devices
);
2092 const char *bdrv_get_encrypted_filename(BlockDriverState
*bs
)
2094 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
2095 return bs
->backing_file
;
2096 else if (bs
->encrypted
)
2097 return bs
->filename
;
2102 void bdrv_get_backing_filename(BlockDriverState
*bs
,
2103 char *filename
, int filename_size
)
2105 if (!bs
->backing_file
) {
2106 pstrcpy(filename
, filename_size
, "");
2108 pstrcpy(filename
, filename_size
, bs
->backing_file
);
2112 int bdrv_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
2113 const uint8_t *buf
, int nb_sectors
)
2115 BlockDriver
*drv
= bs
->drv
;
2118 if (!drv
->bdrv_write_compressed
)
2120 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2123 if (bs
->dirty_bitmap
) {
2124 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
2127 return drv
->bdrv_write_compressed(bs
, sector_num
, buf
, nb_sectors
);
2130 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2132 BlockDriver
*drv
= bs
->drv
;
2135 if (!drv
->bdrv_get_info
)
2137 memset(bdi
, 0, sizeof(*bdi
));
2138 return drv
->bdrv_get_info(bs
, bdi
);
2141 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2142 int64_t pos
, int size
)
2144 BlockDriver
*drv
= bs
->drv
;
2147 if (drv
->bdrv_save_vmstate
)
2148 return drv
->bdrv_save_vmstate(bs
, buf
, pos
, size
);
2150 return bdrv_save_vmstate(bs
->file
, buf
, pos
, size
);
2154 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2155 int64_t pos
, int size
)
2157 BlockDriver
*drv
= bs
->drv
;
2160 if (drv
->bdrv_load_vmstate
)
2161 return drv
->bdrv_load_vmstate(bs
, buf
, pos
, size
);
2163 return bdrv_load_vmstate(bs
->file
, buf
, pos
, size
);
2167 void bdrv_debug_event(BlockDriverState
*bs
, BlkDebugEvent event
)
2169 BlockDriver
*drv
= bs
->drv
;
2171 if (!drv
|| !drv
->bdrv_debug_event
) {
2175 return drv
->bdrv_debug_event(bs
, event
);
2179 /**************************************************************/
2180 /* handling of snapshots */
2182 int bdrv_can_snapshot(BlockDriverState
*bs
)
2184 BlockDriver
*drv
= bs
->drv
;
2185 if (!drv
|| !bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
)) {
2189 if (!drv
->bdrv_snapshot_create
) {
2190 if (bs
->file
!= NULL
) {
2191 return bdrv_can_snapshot(bs
->file
);
2199 int bdrv_is_snapshot(BlockDriverState
*bs
)
2201 return !!(bs
->open_flags
& BDRV_O_SNAPSHOT
);
2204 BlockDriverState
*bdrv_snapshots(void)
2206 BlockDriverState
*bs
;
2209 return bs_snapshots
;
2213 while ((bs
= bdrv_next(bs
))) {
2214 if (bdrv_can_snapshot(bs
)) {
2222 int bdrv_snapshot_create(BlockDriverState
*bs
,
2223 QEMUSnapshotInfo
*sn_info
)
2225 BlockDriver
*drv
= bs
->drv
;
2228 if (drv
->bdrv_snapshot_create
)
2229 return drv
->bdrv_snapshot_create(bs
, sn_info
);
2231 return bdrv_snapshot_create(bs
->file
, sn_info
);
2235 int bdrv_snapshot_goto(BlockDriverState
*bs
,
2236 const char *snapshot_id
)
2238 BlockDriver
*drv
= bs
->drv
;
2243 if (drv
->bdrv_snapshot_goto
)
2244 return drv
->bdrv_snapshot_goto(bs
, snapshot_id
);
2247 drv
->bdrv_close(bs
);
2248 ret
= bdrv_snapshot_goto(bs
->file
, snapshot_id
);
2249 open_ret
= drv
->bdrv_open(bs
, bs
->open_flags
);
2251 bdrv_delete(bs
->file
);
2261 int bdrv_snapshot_delete(BlockDriverState
*bs
, const char *snapshot_id
)
2263 BlockDriver
*drv
= bs
->drv
;
2266 if (drv
->bdrv_snapshot_delete
)
2267 return drv
->bdrv_snapshot_delete(bs
, snapshot_id
);
2269 return bdrv_snapshot_delete(bs
->file
, snapshot_id
);
2273 int bdrv_snapshot_list(BlockDriverState
*bs
,
2274 QEMUSnapshotInfo
**psn_info
)
2276 BlockDriver
*drv
= bs
->drv
;
2279 if (drv
->bdrv_snapshot_list
)
2280 return drv
->bdrv_snapshot_list(bs
, psn_info
);
2282 return bdrv_snapshot_list(bs
->file
, psn_info
);
2286 int bdrv_snapshot_load_tmp(BlockDriverState
*bs
,
2287 const char *snapshot_name
)
2289 BlockDriver
*drv
= bs
->drv
;
2293 if (!bs
->read_only
) {
2296 if (drv
->bdrv_snapshot_load_tmp
) {
2297 return drv
->bdrv_snapshot_load_tmp(bs
, snapshot_name
);
2302 #define NB_SUFFIXES 4
2304 char *get_human_readable_size(char *buf
, int buf_size
, int64_t size
)
2306 static const char suffixes
[NB_SUFFIXES
] = "KMGT";
2311 snprintf(buf
, buf_size
, "%" PRId64
, size
);
2314 for(i
= 0; i
< NB_SUFFIXES
; i
++) {
2315 if (size
< (10 * base
)) {
2316 snprintf(buf
, buf_size
, "%0.1f%c",
2317 (double)size
/ base
,
2320 } else if (size
< (1000 * base
) || i
== (NB_SUFFIXES
- 1)) {
2321 snprintf(buf
, buf_size
, "%" PRId64
"%c",
2322 ((size
+ (base
>> 1)) / base
),
2332 char *bdrv_snapshot_dump(char *buf
, int buf_size
, QEMUSnapshotInfo
*sn
)
2334 char buf1
[128], date_buf
[128], clock_buf
[128];
2344 snprintf(buf
, buf_size
,
2345 "%-10s%-20s%7s%20s%15s",
2346 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2350 ptm
= localtime(&ti
);
2351 strftime(date_buf
, sizeof(date_buf
),
2352 "%Y-%m-%d %H:%M:%S", ptm
);
2354 localtime_r(&ti
, &tm
);
2355 strftime(date_buf
, sizeof(date_buf
),
2356 "%Y-%m-%d %H:%M:%S", &tm
);
2358 secs
= sn
->vm_clock_nsec
/ 1000000000;
2359 snprintf(clock_buf
, sizeof(clock_buf
),
2360 "%02d:%02d:%02d.%03d",
2362 (int)((secs
/ 60) % 60),
2364 (int)((sn
->vm_clock_nsec
/ 1000000) % 1000));
2365 snprintf(buf
, buf_size
,
2366 "%-10s%-20s%7s%20s%15s",
2367 sn
->id_str
, sn
->name
,
2368 get_human_readable_size(buf1
, sizeof(buf1
), sn
->vm_state_size
),
2375 /**************************************************************/
2378 BlockDriverAIOCB
*bdrv_aio_readv(BlockDriverState
*bs
, int64_t sector_num
,
2379 QEMUIOVector
*qiov
, int nb_sectors
,
2380 BlockDriverCompletionFunc
*cb
, void *opaque
)
2382 trace_bdrv_aio_readv(bs
, sector_num
, nb_sectors
, opaque
);
2384 return bdrv_co_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
,
2385 cb
, opaque
, false, bdrv_co_do_rw
);
2388 typedef struct BlockCompleteData
{
2389 BlockDriverCompletionFunc
*cb
;
2391 BlockDriverState
*bs
;
2394 } BlockCompleteData
;
2396 static void block_complete_cb(void *opaque
, int ret
)
2398 BlockCompleteData
*b
= opaque
;
2400 if (b
->bs
->dirty_bitmap
) {
2401 set_dirty_bitmap(b
->bs
, b
->sector_num
, b
->nb_sectors
, 1);
2403 b
->cb(b
->opaque
, ret
);
2407 static BlockCompleteData
*blk_dirty_cb_alloc(BlockDriverState
*bs
,
2410 BlockDriverCompletionFunc
*cb
,
2413 BlockCompleteData
*blkdata
= g_malloc0(sizeof(BlockCompleteData
));
2417 blkdata
->opaque
= opaque
;
2418 blkdata
->sector_num
= sector_num
;
2419 blkdata
->nb_sectors
= nb_sectors
;
2424 BlockDriverAIOCB
*bdrv_aio_writev(BlockDriverState
*bs
, int64_t sector_num
,
2425 QEMUIOVector
*qiov
, int nb_sectors
,
2426 BlockDriverCompletionFunc
*cb
, void *opaque
)
2428 BlockDriver
*drv
= bs
->drv
;
2429 BlockDriverAIOCB
*ret
;
2430 BlockCompleteData
*blk_cb_data
;
2432 trace_bdrv_aio_writev(bs
, sector_num
, nb_sectors
, opaque
);
2438 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2441 if (bs
->dirty_bitmap
) {
2442 blk_cb_data
= blk_dirty_cb_alloc(bs
, sector_num
, nb_sectors
, cb
,
2444 cb
= &block_complete_cb
;
2445 opaque
= blk_cb_data
;
2448 ret
= drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
2452 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
2453 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
2461 typedef struct MultiwriteCB
{
2466 BlockDriverCompletionFunc
*cb
;
2468 QEMUIOVector
*free_qiov
;
2473 static void multiwrite_user_cb(MultiwriteCB
*mcb
)
2477 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2478 mcb
->callbacks
[i
].cb(mcb
->callbacks
[i
].opaque
, mcb
->error
);
2479 if (mcb
->callbacks
[i
].free_qiov
) {
2480 qemu_iovec_destroy(mcb
->callbacks
[i
].free_qiov
);
2482 g_free(mcb
->callbacks
[i
].free_qiov
);
2483 qemu_vfree(mcb
->callbacks
[i
].free_buf
);
2487 static void multiwrite_cb(void *opaque
, int ret
)
2489 MultiwriteCB
*mcb
= opaque
;
2491 trace_multiwrite_cb(mcb
, ret
);
2493 if (ret
< 0 && !mcb
->error
) {
2497 mcb
->num_requests
--;
2498 if (mcb
->num_requests
== 0) {
2499 multiwrite_user_cb(mcb
);
2504 static int multiwrite_req_compare(const void *a
, const void *b
)
2506 const BlockRequest
*req1
= a
, *req2
= b
;
2509 * Note that we can't simply subtract req2->sector from req1->sector
2510 * here as that could overflow the return value.
2512 if (req1
->sector
> req2
->sector
) {
2514 } else if (req1
->sector
< req2
->sector
) {
2522 * Takes a bunch of requests and tries to merge them. Returns the number of
2523 * requests that remain after merging.
2525 static int multiwrite_merge(BlockDriverState
*bs
, BlockRequest
*reqs
,
2526 int num_reqs
, MultiwriteCB
*mcb
)
2530 // Sort requests by start sector
2531 qsort(reqs
, num_reqs
, sizeof(*reqs
), &multiwrite_req_compare
);
2533 // Check if adjacent requests touch the same clusters. If so, combine them,
2534 // filling up gaps with zero sectors.
2536 for (i
= 1; i
< num_reqs
; i
++) {
2538 int64_t oldreq_last
= reqs
[outidx
].sector
+ reqs
[outidx
].nb_sectors
;
2540 // This handles the cases that are valid for all block drivers, namely
2541 // exactly sequential writes and overlapping writes.
2542 if (reqs
[i
].sector
<= oldreq_last
) {
2546 // The block driver may decide that it makes sense to combine requests
2547 // even if there is a gap of some sectors between them. In this case,
2548 // the gap is filled with zeros (therefore only applicable for yet
2549 // unused space in format like qcow2).
2550 if (!merge
&& bs
->drv
->bdrv_merge_requests
) {
2551 merge
= bs
->drv
->bdrv_merge_requests(bs
, &reqs
[outidx
], &reqs
[i
]);
2554 if (reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1 > IOV_MAX
) {
2560 QEMUIOVector
*qiov
= g_malloc0(sizeof(*qiov
));
2561 qemu_iovec_init(qiov
,
2562 reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1);
2564 // Add the first request to the merged one. If the requests are
2565 // overlapping, drop the last sectors of the first request.
2566 size
= (reqs
[i
].sector
- reqs
[outidx
].sector
) << 9;
2567 qemu_iovec_concat(qiov
, reqs
[outidx
].qiov
, size
);
2569 // We might need to add some zeros between the two requests
2570 if (reqs
[i
].sector
> oldreq_last
) {
2571 size_t zero_bytes
= (reqs
[i
].sector
- oldreq_last
) << 9;
2572 uint8_t *buf
= qemu_blockalign(bs
, zero_bytes
);
2573 memset(buf
, 0, zero_bytes
);
2574 qemu_iovec_add(qiov
, buf
, zero_bytes
);
2575 mcb
->callbacks
[i
].free_buf
= buf
;
2578 // Add the second request
2579 qemu_iovec_concat(qiov
, reqs
[i
].qiov
, reqs
[i
].qiov
->size
);
2581 reqs
[outidx
].nb_sectors
= qiov
->size
>> 9;
2582 reqs
[outidx
].qiov
= qiov
;
2584 mcb
->callbacks
[i
].free_qiov
= reqs
[outidx
].qiov
;
2587 reqs
[outidx
].sector
= reqs
[i
].sector
;
2588 reqs
[outidx
].nb_sectors
= reqs
[i
].nb_sectors
;
2589 reqs
[outidx
].qiov
= reqs
[i
].qiov
;
2597 * Submit multiple AIO write requests at once.
2599 * On success, the function returns 0 and all requests in the reqs array have
2600 * been submitted. In error case this function returns -1, and any of the
2601 * requests may or may not be submitted yet. In particular, this means that the
2602 * callback will be called for some of the requests, for others it won't. The
2603 * caller must check the error field of the BlockRequest to wait for the right
2604 * callbacks (if error != 0, no callback will be called).
2606 * The implementation may modify the contents of the reqs array, e.g. to merge
2607 * requests. However, the fields opaque and error are left unmodified as they
2608 * are used to signal failure for a single request to the caller.
2610 int bdrv_aio_multiwrite(BlockDriverState
*bs
, BlockRequest
*reqs
, int num_reqs
)
2612 BlockDriverAIOCB
*acb
;
2616 /* don't submit writes if we don't have a medium */
2617 if (bs
->drv
== NULL
) {
2618 for (i
= 0; i
< num_reqs
; i
++) {
2619 reqs
[i
].error
= -ENOMEDIUM
;
2624 if (num_reqs
== 0) {
2628 // Create MultiwriteCB structure
2629 mcb
= g_malloc0(sizeof(*mcb
) + num_reqs
* sizeof(*mcb
->callbacks
));
2630 mcb
->num_requests
= 0;
2631 mcb
->num_callbacks
= num_reqs
;
2633 for (i
= 0; i
< num_reqs
; i
++) {
2634 mcb
->callbacks
[i
].cb
= reqs
[i
].cb
;
2635 mcb
->callbacks
[i
].opaque
= reqs
[i
].opaque
;
2638 // Check for mergable requests
2639 num_reqs
= multiwrite_merge(bs
, reqs
, num_reqs
, mcb
);
2641 trace_bdrv_aio_multiwrite(mcb
, mcb
->num_callbacks
, num_reqs
);
2644 * Run the aio requests. As soon as one request can't be submitted
2645 * successfully, fail all requests that are not yet submitted (we must
2646 * return failure for all requests anyway)
2648 * num_requests cannot be set to the right value immediately: If
2649 * bdrv_aio_writev fails for some request, num_requests would be too high
2650 * and therefore multiwrite_cb() would never recognize the multiwrite
2651 * request as completed. We also cannot use the loop variable i to set it
2652 * when the first request fails because the callback may already have been
2653 * called for previously submitted requests. Thus, num_requests must be
2654 * incremented for each request that is submitted.
2656 * The problem that callbacks may be called early also means that we need
2657 * to take care that num_requests doesn't become 0 before all requests are
2658 * submitted - multiwrite_cb() would consider the multiwrite request
2659 * completed. A dummy request that is "completed" by a manual call to
2660 * multiwrite_cb() takes care of this.
2662 mcb
->num_requests
= 1;
2664 // Run the aio requests
2665 for (i
= 0; i
< num_reqs
; i
++) {
2666 mcb
->num_requests
++;
2667 acb
= bdrv_aio_writev(bs
, reqs
[i
].sector
, reqs
[i
].qiov
,
2668 reqs
[i
].nb_sectors
, multiwrite_cb
, mcb
);
2671 // We can only fail the whole thing if no request has been
2672 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2673 // complete and report the error in the callback.
2675 trace_bdrv_aio_multiwrite_earlyfail(mcb
);
2678 trace_bdrv_aio_multiwrite_latefail(mcb
, i
);
2679 multiwrite_cb(mcb
, -EIO
);
2685 /* Complete the dummy request */
2686 multiwrite_cb(mcb
, 0);
2691 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2692 reqs
[i
].error
= -EIO
;
2698 BlockDriverAIOCB
*bdrv_aio_flush(BlockDriverState
*bs
,
2699 BlockDriverCompletionFunc
*cb
, void *opaque
)
2701 BlockDriver
*drv
= bs
->drv
;
2703 trace_bdrv_aio_flush(bs
, opaque
);
2705 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2706 return bdrv_aio_noop_em(bs
, cb
, opaque
);
2711 return drv
->bdrv_aio_flush(bs
, cb
, opaque
);
2714 void bdrv_aio_cancel(BlockDriverAIOCB
*acb
)
2716 acb
->pool
->cancel(acb
);
2720 /**************************************************************/
2721 /* async block device emulation */
2723 typedef struct BlockDriverAIOCBSync
{
2724 BlockDriverAIOCB common
;
2727 /* vector translation state */
2731 } BlockDriverAIOCBSync
;
2733 static void bdrv_aio_cancel_em(BlockDriverAIOCB
*blockacb
)
2735 BlockDriverAIOCBSync
*acb
=
2736 container_of(blockacb
, BlockDriverAIOCBSync
, common
);
2737 qemu_bh_delete(acb
->bh
);
2739 qemu_aio_release(acb
);
2742 static AIOPool bdrv_em_aio_pool
= {
2743 .aiocb_size
= sizeof(BlockDriverAIOCBSync
),
2744 .cancel
= bdrv_aio_cancel_em
,
2747 static void bdrv_aio_bh_cb(void *opaque
)
2749 BlockDriverAIOCBSync
*acb
= opaque
;
2752 qemu_iovec_from_buffer(acb
->qiov
, acb
->bounce
, acb
->qiov
->size
);
2753 qemu_vfree(acb
->bounce
);
2754 acb
->common
.cb(acb
->common
.opaque
, acb
->ret
);
2755 qemu_bh_delete(acb
->bh
);
2757 qemu_aio_release(acb
);
2760 static BlockDriverAIOCB
*bdrv_aio_rw_vector(BlockDriverState
*bs
,
2764 BlockDriverCompletionFunc
*cb
,
2769 BlockDriverAIOCBSync
*acb
;
2771 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2772 acb
->is_write
= is_write
;
2774 acb
->bounce
= qemu_blockalign(bs
, qiov
->size
);
2777 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2780 qemu_iovec_to_buffer(acb
->qiov
, acb
->bounce
);
2781 acb
->ret
= bs
->drv
->bdrv_write(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2783 acb
->ret
= bs
->drv
->bdrv_read(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2786 qemu_bh_schedule(acb
->bh
);
2788 return &acb
->common
;
2791 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
2792 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2793 BlockDriverCompletionFunc
*cb
, void *opaque
)
2795 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 0);
2798 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
2799 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2800 BlockDriverCompletionFunc
*cb
, void *opaque
)
2802 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 1);
2806 typedef struct BlockDriverAIOCBCoroutine
{
2807 BlockDriverAIOCB common
;
2811 } BlockDriverAIOCBCoroutine
;
2813 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB
*blockacb
)
2818 static AIOPool bdrv_em_co_aio_pool
= {
2819 .aiocb_size
= sizeof(BlockDriverAIOCBCoroutine
),
2820 .cancel
= bdrv_aio_co_cancel_em
,
2823 static void bdrv_co_rw_bh(void *opaque
)
2825 BlockDriverAIOCBCoroutine
*acb
= opaque
;
2827 acb
->common
.cb(acb
->common
.opaque
, acb
->req
.error
);
2828 qemu_bh_delete(acb
->bh
);
2829 qemu_aio_release(acb
);
2832 /* Invoke .bdrv_co_readv/.bdrv_co_writev */
2833 static void coroutine_fn
bdrv_co_rw(void *opaque
)
2835 BlockDriverAIOCBCoroutine
*acb
= opaque
;
2836 BlockDriverState
*bs
= acb
->common
.bs
;
2838 if (!acb
->is_write
) {
2839 acb
->req
.error
= bs
->drv
->bdrv_co_readv(bs
, acb
->req
.sector
,
2840 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2842 acb
->req
.error
= bs
->drv
->bdrv_co_writev(bs
, acb
->req
.sector
,
2843 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2846 acb
->bh
= qemu_bh_new(bdrv_co_rw_bh
, acb
);
2847 qemu_bh_schedule(acb
->bh
);
2850 /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
2851 static void coroutine_fn
bdrv_co_do_rw(void *opaque
)
2853 BlockDriverAIOCBCoroutine
*acb
= opaque
;
2854 BlockDriverState
*bs
= acb
->common
.bs
;
2856 if (!acb
->is_write
) {
2857 acb
->req
.error
= bdrv_co_do_readv(bs
, acb
->req
.sector
,
2858 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2860 acb
->req
.error
= bdrv_co_do_writev(bs
, acb
->req
.sector
,
2861 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2864 acb
->bh
= qemu_bh_new(bdrv_co_rw_bh
, acb
);
2865 qemu_bh_schedule(acb
->bh
);
2868 static BlockDriverAIOCB
*bdrv_co_aio_rw_vector(BlockDriverState
*bs
,
2872 BlockDriverCompletionFunc
*cb
,
2875 CoroutineEntry
*entry
)
2878 BlockDriverAIOCBCoroutine
*acb
;
2880 acb
= qemu_aio_get(&bdrv_em_co_aio_pool
, bs
, cb
, opaque
);
2881 acb
->req
.sector
= sector_num
;
2882 acb
->req
.nb_sectors
= nb_sectors
;
2883 acb
->req
.qiov
= qiov
;
2884 acb
->is_write
= is_write
;
2886 co
= qemu_coroutine_create(entry
);
2887 qemu_coroutine_enter(co
, acb
);
2889 return &acb
->common
;
2892 static BlockDriverAIOCB
*bdrv_co_aio_readv_em(BlockDriverState
*bs
,
2893 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2894 BlockDriverCompletionFunc
*cb
, void *opaque
)
2896 return bdrv_co_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
,
2900 static BlockDriverAIOCB
*bdrv_co_aio_writev_em(BlockDriverState
*bs
,
2901 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2902 BlockDriverCompletionFunc
*cb
, void *opaque
)
2904 return bdrv_co_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
,
2908 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
2909 BlockDriverCompletionFunc
*cb
, void *opaque
)
2911 BlockDriverAIOCBSync
*acb
;
2913 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2914 acb
->is_write
= 1; /* don't bounce in the completion hadler */
2920 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2923 qemu_bh_schedule(acb
->bh
);
2924 return &acb
->common
;
2927 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
2928 BlockDriverCompletionFunc
*cb
, void *opaque
)
2930 BlockDriverAIOCBSync
*acb
;
2932 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2933 acb
->is_write
= 1; /* don't bounce in the completion handler */
2939 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2942 qemu_bh_schedule(acb
->bh
);
2943 return &acb
->common
;
2946 /**************************************************************/
2947 /* sync block device emulation */
2949 static void bdrv_rw_em_cb(void *opaque
, int ret
)
2951 *(int *)opaque
= ret
;
2954 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
2955 uint8_t *buf
, int nb_sectors
)
2958 BlockDriverAIOCB
*acb
;
2962 async_ret
= NOT_DONE
;
2963 iov
.iov_base
= (void *)buf
;
2964 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2965 qemu_iovec_init_external(&qiov
, &iov
, 1);
2967 acb
= bs
->drv
->bdrv_aio_readv(bs
, sector_num
, &qiov
, nb_sectors
,
2968 bdrv_rw_em_cb
, &async_ret
);
2974 while (async_ret
== NOT_DONE
) {
2983 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
2984 const uint8_t *buf
, int nb_sectors
)
2987 BlockDriverAIOCB
*acb
;
2991 async_ret
= NOT_DONE
;
2992 iov
.iov_base
= (void *)buf
;
2993 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2994 qemu_iovec_init_external(&qiov
, &iov
, 1);
2996 acb
= bs
->drv
->bdrv_aio_writev(bs
, sector_num
, &qiov
, nb_sectors
,
2997 bdrv_rw_em_cb
, &async_ret
);
3002 while (async_ret
== NOT_DONE
) {
3010 void bdrv_init(void)
3012 module_call_init(MODULE_INIT_BLOCK
);
3015 void bdrv_init_with_whitelist(void)
3017 use_bdrv_whitelist
= 1;
3021 void *qemu_aio_get(AIOPool
*pool
, BlockDriverState
*bs
,
3022 BlockDriverCompletionFunc
*cb
, void *opaque
)
3024 BlockDriverAIOCB
*acb
;
3026 if (pool
->free_aiocb
) {
3027 acb
= pool
->free_aiocb
;
3028 pool
->free_aiocb
= acb
->next
;
3030 acb
= g_malloc0(pool
->aiocb_size
);
3035 acb
->opaque
= opaque
;
3039 void qemu_aio_release(void *p
)
3041 BlockDriverAIOCB
*acb
= (BlockDriverAIOCB
*)p
;
3042 AIOPool
*pool
= acb
->pool
;
3043 acb
->next
= pool
->free_aiocb
;
3044 pool
->free_aiocb
= acb
;
3047 /**************************************************************/
3048 /* Coroutine block device emulation */
3050 typedef struct CoroutineIOCompletion
{
3051 Coroutine
*coroutine
;
3053 } CoroutineIOCompletion
;
3055 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
3057 CoroutineIOCompletion
*co
= opaque
;
3060 qemu_coroutine_enter(co
->coroutine
, NULL
);
3063 static int coroutine_fn
bdrv_co_io_em(BlockDriverState
*bs
, int64_t sector_num
,
3064 int nb_sectors
, QEMUIOVector
*iov
,
3067 CoroutineIOCompletion co
= {
3068 .coroutine
= qemu_coroutine_self(),
3070 BlockDriverAIOCB
*acb
;
3073 acb
= bs
->drv
->bdrv_aio_writev(bs
, sector_num
, iov
, nb_sectors
,
3074 bdrv_co_io_em_complete
, &co
);
3076 acb
= bs
->drv
->bdrv_aio_readv(bs
, sector_num
, iov
, nb_sectors
,
3077 bdrv_co_io_em_complete
, &co
);
3080 trace_bdrv_co_io_em(bs
, sector_num
, nb_sectors
, is_write
, acb
);
3084 qemu_coroutine_yield();
3089 static int coroutine_fn
bdrv_co_readv_em(BlockDriverState
*bs
,
3090 int64_t sector_num
, int nb_sectors
,
3093 return bdrv_co_io_em(bs
, sector_num
, nb_sectors
, iov
, false);
3096 static int coroutine_fn
bdrv_co_writev_em(BlockDriverState
*bs
,
3097 int64_t sector_num
, int nb_sectors
,
3100 return bdrv_co_io_em(bs
, sector_num
, nb_sectors
, iov
, true);
3103 static int coroutine_fn
bdrv_co_flush_em(BlockDriverState
*bs
)
3105 CoroutineIOCompletion co
= {
3106 .coroutine
= qemu_coroutine_self(),
3108 BlockDriverAIOCB
*acb
;
3110 acb
= bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
3114 qemu_coroutine_yield();
3118 /**************************************************************/
3119 /* removable device support */
3122 * Return TRUE if the media is present
3124 int bdrv_is_inserted(BlockDriverState
*bs
)
3126 BlockDriver
*drv
= bs
->drv
;
3130 if (!drv
->bdrv_is_inserted
)
3132 return drv
->bdrv_is_inserted(bs
);
3136 * Return whether the media changed since the last call to this
3137 * function, or -ENOTSUP if we don't know. Most drivers don't know.
3139 int bdrv_media_changed(BlockDriverState
*bs
)
3141 BlockDriver
*drv
= bs
->drv
;
3143 if (drv
&& drv
->bdrv_media_changed
) {
3144 return drv
->bdrv_media_changed(bs
);
3150 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3152 void bdrv_eject(BlockDriverState
*bs
, int eject_flag
)
3154 BlockDriver
*drv
= bs
->drv
;
3156 if (drv
&& drv
->bdrv_eject
) {
3157 drv
->bdrv_eject(bs
, eject_flag
);
3162 * Lock or unlock the media (if it is locked, the user won't be able
3163 * to eject it manually).
3165 void bdrv_lock_medium(BlockDriverState
*bs
, bool locked
)
3167 BlockDriver
*drv
= bs
->drv
;
3169 trace_bdrv_lock_medium(bs
, locked
);
3171 if (drv
&& drv
->bdrv_lock_medium
) {
3172 drv
->bdrv_lock_medium(bs
, locked
);
3176 /* needed for generic scsi interface */
3178 int bdrv_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
3180 BlockDriver
*drv
= bs
->drv
;
3182 if (drv
&& drv
->bdrv_ioctl
)
3183 return drv
->bdrv_ioctl(bs
, req
, buf
);
3187 BlockDriverAIOCB
*bdrv_aio_ioctl(BlockDriverState
*bs
,
3188 unsigned long int req
, void *buf
,
3189 BlockDriverCompletionFunc
*cb
, void *opaque
)
3191 BlockDriver
*drv
= bs
->drv
;
3193 if (drv
&& drv
->bdrv_aio_ioctl
)
3194 return drv
->bdrv_aio_ioctl(bs
, req
, buf
, cb
, opaque
);
3198 void bdrv_set_buffer_alignment(BlockDriverState
*bs
, int align
)
3200 bs
->buffer_alignment
= align
;
3203 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
3205 return qemu_memalign((bs
&& bs
->buffer_alignment
) ? bs
->buffer_alignment
: 512, size
);
3208 void bdrv_set_dirty_tracking(BlockDriverState
*bs
, int enable
)
3210 int64_t bitmap_size
;
3212 bs
->dirty_count
= 0;
3214 if (!bs
->dirty_bitmap
) {
3215 bitmap_size
= (bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
) +
3216 BDRV_SECTORS_PER_DIRTY_CHUNK
* 8 - 1;
3217 bitmap_size
/= BDRV_SECTORS_PER_DIRTY_CHUNK
* 8;
3219 bs
->dirty_bitmap
= g_malloc0(bitmap_size
);
3222 if (bs
->dirty_bitmap
) {
3223 g_free(bs
->dirty_bitmap
);
3224 bs
->dirty_bitmap
= NULL
;
3229 int bdrv_get_dirty(BlockDriverState
*bs
, int64_t sector
)
3231 int64_t chunk
= sector
/ (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK
;
3233 if (bs
->dirty_bitmap
&&
3234 (sector
<< BDRV_SECTOR_BITS
) < bdrv_getlength(bs
)) {
3235 return !!(bs
->dirty_bitmap
[chunk
/ (sizeof(unsigned long) * 8)] &
3236 (1UL << (chunk
% (sizeof(unsigned long) * 8))));
3242 void bdrv_reset_dirty(BlockDriverState
*bs
, int64_t cur_sector
,
3245 set_dirty_bitmap(bs
, cur_sector
, nr_sectors
, 0);
3248 int64_t bdrv_get_dirty_count(BlockDriverState
*bs
)
3250 return bs
->dirty_count
;
3253 void bdrv_set_in_use(BlockDriverState
*bs
, int in_use
)
3255 assert(bs
->in_use
!= in_use
);
3256 bs
->in_use
= in_use
;
3259 int bdrv_in_use(BlockDriverState
*bs
)
3264 void bdrv_iostatus_enable(BlockDriverState
*bs
)
3266 bs
->iostatus
= BDRV_IOS_OK
;
3269 /* The I/O status is only enabled if the drive explicitly
3270 * enables it _and_ the VM is configured to stop on errors */
3271 bool bdrv_iostatus_is_enabled(const BlockDriverState
*bs
)
3273 return (bs
->iostatus
!= BDRV_IOS_INVAL
&&
3274 (bs
->on_write_error
== BLOCK_ERR_STOP_ENOSPC
||
3275 bs
->on_write_error
== BLOCK_ERR_STOP_ANY
||
3276 bs
->on_read_error
== BLOCK_ERR_STOP_ANY
));
3279 void bdrv_iostatus_disable(BlockDriverState
*bs
)
3281 bs
->iostatus
= BDRV_IOS_INVAL
;
3284 void bdrv_iostatus_reset(BlockDriverState
*bs
)
3286 if (bdrv_iostatus_is_enabled(bs
)) {
3287 bs
->iostatus
= BDRV_IOS_OK
;
3291 /* XXX: Today this is set by device models because it makes the implementation
3292 quite simple. However, the block layer knows about the error, so it's
3293 possible to implement this without device models being involved */
3294 void bdrv_iostatus_set_err(BlockDriverState
*bs
, int error
)
3296 if (bdrv_iostatus_is_enabled(bs
) && bs
->iostatus
== BDRV_IOS_OK
) {
3298 bs
->iostatus
= error
== ENOSPC
? BDRV_IOS_ENOSPC
: BDRV_IOS_FAILED
;
3303 bdrv_acct_start(BlockDriverState
*bs
, BlockAcctCookie
*cookie
, int64_t bytes
,
3304 enum BlockAcctType type
)
3306 assert(type
< BDRV_MAX_IOTYPE
);
3308 cookie
->bytes
= bytes
;
3309 cookie
->start_time_ns
= get_clock();
3310 cookie
->type
= type
;
3314 bdrv_acct_done(BlockDriverState
*bs
, BlockAcctCookie
*cookie
)
3316 assert(cookie
->type
< BDRV_MAX_IOTYPE
);
3318 bs
->nr_bytes
[cookie
->type
] += cookie
->bytes
;
3319 bs
->nr_ops
[cookie
->type
]++;
3320 bs
->total_time_ns
[cookie
->type
] += get_clock() - cookie
->start_time_ns
;
3323 int bdrv_img_create(const char *filename
, const char *fmt
,
3324 const char *base_filename
, const char *base_fmt
,
3325 char *options
, uint64_t img_size
, int flags
)
3327 QEMUOptionParameter
*param
= NULL
, *create_options
= NULL
;
3328 QEMUOptionParameter
*backing_fmt
, *backing_file
, *size
;
3329 BlockDriverState
*bs
= NULL
;
3330 BlockDriver
*drv
, *proto_drv
;
3331 BlockDriver
*backing_drv
= NULL
;
3334 /* Find driver and parse its options */
3335 drv
= bdrv_find_format(fmt
);
3337 error_report("Unknown file format '%s'", fmt
);
3342 proto_drv
= bdrv_find_protocol(filename
);
3344 error_report("Unknown protocol '%s'", filename
);
3349 create_options
= append_option_parameters(create_options
,
3350 drv
->create_options
);
3351 create_options
= append_option_parameters(create_options
,
3352 proto_drv
->create_options
);
3354 /* Create parameter list with default values */
3355 param
= parse_option_parameters("", create_options
, param
);
3357 set_option_parameter_int(param
, BLOCK_OPT_SIZE
, img_size
);
3359 /* Parse -o options */
3361 param
= parse_option_parameters(options
, create_options
, param
);
3362 if (param
== NULL
) {
3363 error_report("Invalid options for file format '%s'.", fmt
);
3369 if (base_filename
) {
3370 if (set_option_parameter(param
, BLOCK_OPT_BACKING_FILE
,
3372 error_report("Backing file not supported for file format '%s'",
3380 if (set_option_parameter(param
, BLOCK_OPT_BACKING_FMT
, base_fmt
)) {
3381 error_report("Backing file format not supported for file "
3382 "format '%s'", fmt
);
3388 backing_file
= get_option_parameter(param
, BLOCK_OPT_BACKING_FILE
);
3389 if (backing_file
&& backing_file
->value
.s
) {
3390 if (!strcmp(filename
, backing_file
->value
.s
)) {
3391 error_report("Error: Trying to create an image with the "
3392 "same filename as the backing file");
3398 backing_fmt
= get_option_parameter(param
, BLOCK_OPT_BACKING_FMT
);
3399 if (backing_fmt
&& backing_fmt
->value
.s
) {
3400 backing_drv
= bdrv_find_format(backing_fmt
->value
.s
);
3402 error_report("Unknown backing file format '%s'",
3403 backing_fmt
->value
.s
);
3409 // The size for the image must always be specified, with one exception:
3410 // If we are using a backing file, we can obtain the size from there
3411 size
= get_option_parameter(param
, BLOCK_OPT_SIZE
);
3412 if (size
&& size
->value
.n
== -1) {
3413 if (backing_file
&& backing_file
->value
.s
) {
3419 ret
= bdrv_open(bs
, backing_file
->value
.s
, flags
, backing_drv
);
3421 error_report("Could not open '%s'", backing_file
->value
.s
);
3424 bdrv_get_geometry(bs
, &size
);
3427 snprintf(buf
, sizeof(buf
), "%" PRId64
, size
);
3428 set_option_parameter(param
, BLOCK_OPT_SIZE
, buf
);
3430 error_report("Image creation needs a size parameter");
3436 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
3437 print_option_parameters(param
);
3440 ret
= bdrv_create(drv
, filename
, param
);
3443 if (ret
== -ENOTSUP
) {
3444 error_report("Formatting or formatting option not supported for "
3445 "file format '%s'", fmt
);
3446 } else if (ret
== -EFBIG
) {
3447 error_report("The image size is too large for file format '%s'",
3450 error_report("%s: error while creating %s: %s", filename
, fmt
,
3456 free_option_parameters(create_options
);
3457 free_option_parameters(param
);