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"
32 #include "block/add-cow.h"
35 #include <sys/types.h>
37 #include <sys/ioctl.h>
38 #include <sys/queue.h>
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
= qemu_mallocz(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 *filename1
)
334 char *filename
= NULL
;
335 char *cow_file
= NULL
;
336 char filename_buff
[1024];
337 snprintf(filename_buff
,sizeof(filename_buff
),"%s",filename1
);
338 filename
= strtok(filename_buff
,":");
339 cow_file
= strtok(NULL
, ":" );
341 /* TODO Drivers without bdrv_file_open must be specified explicitly */
344 * XXX(hch): we really should not let host device detection
345 * override an explicit protocol specification, but moving this
346 * later breaks access to device names with colons in them.
347 * Thanks to the brain-dead persistent naming schemes on udev-
348 * based Linux systems those actually are quite common.
350 drv1
= find_hdev_driver(filename
);
355 if (!path_has_protocol(filename
)) {
356 return bdrv_find_format("file");
358 p
= strchr(filename
, ':');
361 if (len
> sizeof(protocol
) - 1)
362 len
= sizeof(protocol
) - 1;
363 memcpy(protocol
, filename
, len
);
364 protocol
[len
] = '\0';
365 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
366 if (drv1
->protocol_name
&&
367 !strcmp(drv1
->protocol_name
, protocol
)) {
374 static int find_image_format(const char *filename
, BlockDriver
**pdrv
)
376 int ret
, score
, score_max
;
377 BlockDriver
*drv1
, *drv
;
379 BlockDriverState
*bs
;
380 char *image_file
= NULL
;
381 char *cow_file
= NULL
;
382 char filename_buff
[1024];
383 snprintf(filename_buff
,sizeof(filename_buff
),"%s",filename
);
385 image_file
= strtok(filename_buff
,":");
386 cow_file
= strtok(NULL
,":");
388 ret
= bdrv_file_open(&bs
, image_file
, 0);
391 sprintf(bs
->cow_file
,"%s",cow_file
);
398 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
399 if (bs
->sg
|| !bdrv_is_inserted(bs
)) {
401 drv
= bdrv_find_format("raw");
409 ret
= bdrv_pread(bs
, 0, buf
, sizeof(buf
));
418 QLIST_FOREACH(drv1
, &bdrv_drivers
, list
) {
419 if (drv1
->bdrv_probe
) {
420 score
= drv1
->bdrv_probe(buf
, ret
, filename
);
421 if (score
> score_max
) {
435 * Set the current 'total_sectors' value
437 static int refresh_total_sectors(BlockDriverState
*bs
, int64_t hint
)
439 BlockDriver
*drv
= bs
->drv
;
441 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
445 /* query actual device if possible, otherwise just trust the hint */
446 if (drv
->bdrv_getlength
) {
447 int64_t length
= drv
->bdrv_getlength(bs
);
451 hint
= length
>> BDRV_SECTOR_BITS
;
454 bs
->total_sectors
= hint
;
459 * Common part for opening disk images and files
461 static int bdrv_open_common(BlockDriverState
*bs
, const char *filename
,
462 int flags
, BlockDriver
*drv
)
469 bs
->total_sectors
= 0;
472 bs
->open_flags
= flags
;
473 /* buffer_alignment defaulted to 512, drivers can change this value */
474 bs
->buffer_alignment
= 512;
476 pstrcpy(bs
->filename
, sizeof(bs
->filename
), filename
);
478 if (use_bdrv_whitelist
&& !bdrv_is_whitelisted(drv
)) {
483 bs
->opaque
= qemu_mallocz(drv
->instance_size
);
485 if (flags
& BDRV_O_CACHE_WB
)
486 bs
->enable_write_cache
= 1;
489 * Clear flags that are internal to the block layer before opening the
492 open_flags
= flags
& ~(BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
495 * Snapshots should be writable.
497 if (bs
->is_temporary
) {
498 open_flags
|= BDRV_O_RDWR
;
501 /* Open the image, either directly or using a protocol */
502 if (drv
->bdrv_file_open
) {
503 ret
= drv
->bdrv_file_open(bs
, filename
, open_flags
);
505 ret
= bdrv_file_open(&bs
->file
, filename
, open_flags
);
507 ret
= drv
->bdrv_open(bs
, open_flags
);
515 bs
->keep_read_only
= bs
->read_only
= !(open_flags
& BDRV_O_RDWR
);
517 ret
= refresh_total_sectors(bs
, bs
->total_sectors
);
523 if (bs
->is_temporary
) {
531 bdrv_delete(bs
->file
);
534 qemu_free(bs
->opaque
);
541 * Opens a file using a protocol (file, host_device, nbd, ...)
543 int bdrv_file_open(BlockDriverState
**pbs
, const char *filename
, int flags
)
545 BlockDriverState
*bs
;
549 drv
= bdrv_find_protocol(filename
);
555 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
566 * Opens a disk image (raw, qcow2, vmdk, ...)
568 int bdrv_open(BlockDriverState
*bs
, const char *filename1
, int flags
,
572 char *filename
= NULL
;
573 char *cowfile
= NULL
;
574 struct add_cow_head header
;
576 char filename_buff
[1024];
577 snprintf(filename_buff
,sizeof(filename_buff
),"%s",filename1
);
578 filename
= strtok(filename_buff
,":");
579 cowfile
= strtok(NULL
,":");
581 if (flags
& BDRV_O_SNAPSHOT
) {
582 BlockDriverState
*bs1
;
585 BlockDriver
*bdrv_qcow2
;
586 QEMUOptionParameter
*options
;
587 char tmp_filename
[PATH_MAX
];
588 char backing_filename
[PATH_MAX
];
590 /* if snapshot, we create a temporary backing file and open it
591 instead of opening 'filename' directly */
593 /* if there is a backing file, use it */
595 ret
= bdrv_open(bs1
, filename
, 0, drv
);
600 total_size
= bdrv_getlength(bs1
) & BDRV_SECTOR_MASK
;
602 if (bs1
->drv
&& bs1
->drv
->protocol_name
)
607 get_tmp_filename(tmp_filename
, sizeof(tmp_filename
));
609 /* Real path is meaningless for protocols */
611 snprintf(backing_filename
, sizeof(backing_filename
),
613 else if (!realpath(filename
, backing_filename
))
616 bdrv_qcow2
= bdrv_find_format("qcow2");
617 options
= parse_option_parameters("", bdrv_qcow2
->create_options
, NULL
);
619 set_option_parameter_int(options
, BLOCK_OPT_SIZE
, total_size
);
620 set_option_parameter(options
, BLOCK_OPT_BACKING_FILE
, backing_filename
);
622 set_option_parameter(options
, BLOCK_OPT_BACKING_FMT
,
626 ret
= bdrv_create(bdrv_qcow2
, tmp_filename
, options
);
627 free_option_parameters(options
);
632 filename
= tmp_filename
;
634 bs
->is_temporary
= 1;
638 snprintf(bs
->cow_file
, sizeof(bs
->cow_file
), "%s", cowfile
);
639 get_add_cow_head(cowfile
, &header
);
640 sprintf(bs
->backing_file
,"%s",header
.backing_file
);
643 /* Find the right image format driver */
645 ret
= find_image_format(filename
, &drv
);
649 goto unlink_and_fail
;
653 ret
= bdrv_open_common(bs
, filename
, flags
, drv
);
655 goto unlink_and_fail
;
658 /* If there is a backing file, use it */
659 if ((flags
& BDRV_O_NO_BACKING
) == 0 && bs
->backing_file
[0] != '\0') {
660 char backing_filename
[PATH_MAX
];
662 BlockDriver
*back_drv
= NULL
;
664 bs
->backing_hd
= bdrv_new("");
666 if (path_has_protocol(bs
->backing_file
)) {
667 pstrcpy(backing_filename
, sizeof(backing_filename
),
670 path_combine(backing_filename
, sizeof(backing_filename
),
671 filename
, bs
->backing_file
);
674 if (bs
->backing_format
[0] != '\0') {
675 back_drv
= bdrv_find_format(bs
->backing_format
);
678 /* backing files always opened read-only */
680 flags
& ~(BDRV_O_RDWR
| BDRV_O_SNAPSHOT
| BDRV_O_NO_BACKING
);
682 ret
= bdrv_open(bs
->backing_hd
, backing_filename
, back_flags
, back_drv
);
687 if (bs
->is_temporary
) {
688 bs
->backing_hd
->keep_read_only
= !(flags
& BDRV_O_RDWR
);
690 /* base image inherits from "parent" */
691 bs
->backing_hd
->keep_read_only
= bs
->keep_read_only
;
695 if (!bdrv_key_required(bs
)) {
696 /* call the change callback */
697 bs
->media_changed
= 1;
699 bs
->change_cb(bs
->change_opaque
, CHANGE_MEDIA
);
705 if (bs
->is_temporary
) {
711 void bdrv_close(BlockDriverState
*bs
)
714 if (bs
== bs_snapshots
) {
717 if (bs
->backing_hd
) {
718 bdrv_delete(bs
->backing_hd
);
719 bs
->backing_hd
= NULL
;
721 bs
->drv
->bdrv_close(bs
);
722 qemu_free(bs
->opaque
);
724 if (bs
->is_temporary
) {
725 unlink(bs
->filename
);
731 if (bs
->file
!= NULL
) {
732 bdrv_close(bs
->file
);
735 /* call the change callback */
736 bs
->media_changed
= 1;
738 bs
->change_cb(bs
->change_opaque
, CHANGE_MEDIA
);
742 void bdrv_close_all(void)
744 BlockDriverState
*bs
;
746 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
751 /* make a BlockDriverState anonymous by removing from bdrv_state list.
752 Also, NULL terminate the device_name to prevent double remove */
753 void bdrv_make_anon(BlockDriverState
*bs
)
755 if (bs
->device_name
[0] != '\0') {
756 QTAILQ_REMOVE(&bdrv_states
, bs
, list
);
758 bs
->device_name
[0] = '\0';
761 void bdrv_delete(BlockDriverState
*bs
)
765 /* remove from list, if necessary */
769 if (bs
->file
!= NULL
) {
770 bdrv_delete(bs
->file
);
773 assert(bs
!= bs_snapshots
);
777 int bdrv_attach(BlockDriverState
*bs
, DeviceState
*qdev
)
786 void bdrv_detach(BlockDriverState
*bs
, DeviceState
*qdev
)
788 assert(bs
->peer
== qdev
);
790 bs
->change_cb
= NULL
;
791 bs
->change_opaque
= NULL
;
794 DeviceState
*bdrv_get_attached(BlockDriverState
*bs
)
800 * Run consistency checks on an image
802 * Returns 0 if the check could be completed (it doesn't mean that the image is
803 * free of errors) or -errno when an internal error occurred. The results of the
804 * check are stored in res.
806 int bdrv_check(BlockDriverState
*bs
, BdrvCheckResult
*res
)
808 if (bs
->drv
->bdrv_check
== NULL
) {
812 memset(res
, 0, sizeof(*res
));
813 return bs
->drv
->bdrv_check(bs
, res
);
816 #define COMMIT_BUF_SECTORS 2048
818 /* commit COW file into the raw image */
819 int bdrv_commit(BlockDriverState
*bs
)
821 BlockDriver
*drv
= bs
->drv
;
822 BlockDriver
*backing_drv
;
823 int64_t sector
, total_sectors
;
824 int n
, ro
, open_flags
;
825 int ret
= 0, rw_ret
= 0;
828 BlockDriverState
*bs_rw
, *bs_ro
;
833 if (!bs
->backing_hd
) {
837 if (bs
->backing_hd
->keep_read_only
) {
841 backing_drv
= bs
->backing_hd
->drv
;
842 ro
= bs
->backing_hd
->read_only
;
843 strncpy(filename
, bs
->backing_hd
->filename
, sizeof(filename
));
844 open_flags
= bs
->backing_hd
->open_flags
;
848 bdrv_delete(bs
->backing_hd
);
849 bs
->backing_hd
= NULL
;
850 bs_rw
= bdrv_new("");
851 rw_ret
= bdrv_open(bs_rw
, filename
, open_flags
| BDRV_O_RDWR
,
855 /* try to re-open read-only */
856 bs_ro
= bdrv_new("");
857 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
,
861 /* drive not functional anymore */
865 bs
->backing_hd
= bs_ro
;
868 bs
->backing_hd
= bs_rw
;
871 total_sectors
= bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
;
872 buf
= qemu_malloc(COMMIT_BUF_SECTORS
* BDRV_SECTOR_SIZE
);
874 for (sector
= 0; sector
< total_sectors
; sector
+= n
) {
875 if (drv
->bdrv_is_allocated(bs
, sector
, COMMIT_BUF_SECTORS
, &n
)) {
877 if (bdrv_read(bs
, sector
, buf
, n
) != 0) {
882 if (bdrv_write(bs
->backing_hd
, sector
, buf
, n
) != 0) {
889 if (drv
->bdrv_make_empty
) {
890 ret
= drv
->bdrv_make_empty(bs
);
895 * Make sure all data we wrote to the backing device is actually
899 bdrv_flush(bs
->backing_hd
);
906 bdrv_delete(bs
->backing_hd
);
907 bs
->backing_hd
= NULL
;
908 bs_ro
= bdrv_new("");
909 ret
= bdrv_open(bs_ro
, filename
, open_flags
& ~BDRV_O_RDWR
,
913 /* drive not functional anymore */
917 bs
->backing_hd
= bs_ro
;
918 bs
->backing_hd
->keep_read_only
= 0;
924 void bdrv_commit_all(void)
926 BlockDriverState
*bs
;
928 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
936 * -EINVAL - backing format specified, but no file
937 * -ENOSPC - can't update the backing file because no space is left in the
939 * -ENOTSUP - format driver doesn't support changing the backing file
941 int bdrv_change_backing_file(BlockDriverState
*bs
,
942 const char *backing_file
, const char *backing_fmt
)
944 BlockDriver
*drv
= bs
->drv
;
946 if (drv
->bdrv_change_backing_file
!= NULL
) {
947 return drv
->bdrv_change_backing_file(bs
, backing_file
, backing_fmt
);
953 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
958 if (!bdrv_is_inserted(bs
))
964 len
= bdrv_getlength(bs
);
969 if ((offset
> len
) || (len
- offset
< size
))
975 static int bdrv_check_request(BlockDriverState
*bs
, int64_t sector_num
,
978 return bdrv_check_byte_request(bs
, sector_num
* BDRV_SECTOR_SIZE
,
979 nb_sectors
* BDRV_SECTOR_SIZE
);
982 static inline bool bdrv_has_async_rw(BlockDriver
*drv
)
984 return drv
->bdrv_co_readv
!= bdrv_co_readv_em
985 || drv
->bdrv_aio_readv
!= bdrv_aio_readv_em
;
988 static inline bool bdrv_has_async_flush(BlockDriver
*drv
)
990 return drv
->bdrv_aio_flush
!= bdrv_aio_flush_em
;
993 /* return < 0 if error. See bdrv_write() for the return codes */
994 int bdrv_read(BlockDriverState
*bs
, int64_t sector_num
,
995 uint8_t *buf
, int nb_sectors
)
997 BlockDriver
*drv
= bs
->drv
;
1002 if (bdrv_has_async_rw(drv
) && qemu_in_coroutine()) {
1004 struct iovec iov
= {
1005 .iov_base
= (void *)buf
,
1006 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
1009 qemu_iovec_init_external(&qiov
, &iov
, 1);
1010 return bdrv_co_readv(bs
, sector_num
, nb_sectors
, &qiov
);
1013 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1016 return drv
->bdrv_read(bs
, sector_num
, buf
, nb_sectors
);
1019 static void set_dirty_bitmap(BlockDriverState
*bs
, int64_t sector_num
,
1020 int nb_sectors
, int dirty
)
1023 unsigned long val
, idx
, bit
;
1025 start
= sector_num
/ BDRV_SECTORS_PER_DIRTY_CHUNK
;
1026 end
= (sector_num
+ nb_sectors
- 1) / BDRV_SECTORS_PER_DIRTY_CHUNK
;
1028 for (; start
<= end
; start
++) {
1029 idx
= start
/ (sizeof(unsigned long) * 8);
1030 bit
= start
% (sizeof(unsigned long) * 8);
1031 val
= bs
->dirty_bitmap
[idx
];
1033 if (!(val
& (1UL << bit
))) {
1038 if (val
& (1UL << bit
)) {
1040 val
&= ~(1UL << bit
);
1043 bs
->dirty_bitmap
[idx
] = val
;
1047 /* Return < 0 if error. Important errors are:
1048 -EIO generic I/O error (may happen for all errors)
1049 -ENOMEDIUM No media inserted.
1050 -EINVAL Invalid sector number or nb_sectors
1051 -EACCES Trying to write a read-only device
1053 int bdrv_write(BlockDriverState
*bs
, int64_t sector_num
,
1054 const uint8_t *buf
, int nb_sectors
)
1056 BlockDriver
*drv
= bs
->drv
;
1061 if (bdrv_has_async_rw(drv
) && qemu_in_coroutine()) {
1063 struct iovec iov
= {
1064 .iov_base
= (void *)buf
,
1065 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
1068 qemu_iovec_init_external(&qiov
, &iov
, 1);
1069 return bdrv_co_writev(bs
, sector_num
, nb_sectors
, &qiov
);
1074 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
1077 if (bs
->dirty_bitmap
) {
1078 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1081 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1082 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1085 return drv
->bdrv_write(bs
, sector_num
, buf
, nb_sectors
);
1088 int bdrv_pread(BlockDriverState
*bs
, int64_t offset
,
1089 void *buf
, int count1
)
1091 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1092 int len
, nb_sectors
, count
;
1097 /* first read to align to sector start */
1098 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1101 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1103 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1105 memcpy(buf
, tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), len
);
1113 /* read the sectors "in place" */
1114 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1115 if (nb_sectors
> 0) {
1116 if ((ret
= bdrv_read(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1118 sector_num
+= nb_sectors
;
1119 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1124 /* add data from the last sector */
1126 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1128 memcpy(buf
, tmp_buf
, count
);
1133 int bdrv_pwrite(BlockDriverState
*bs
, int64_t offset
,
1134 const void *buf
, int count1
)
1136 uint8_t tmp_buf
[BDRV_SECTOR_SIZE
];
1137 int len
, nb_sectors
, count
;
1142 /* first write to align to sector start */
1143 len
= (BDRV_SECTOR_SIZE
- offset
) & (BDRV_SECTOR_SIZE
- 1);
1146 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1148 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1150 memcpy(tmp_buf
+ (offset
& (BDRV_SECTOR_SIZE
- 1)), buf
, len
);
1151 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1160 /* write the sectors "in place" */
1161 nb_sectors
= count
>> BDRV_SECTOR_BITS
;
1162 if (nb_sectors
> 0) {
1163 if ((ret
= bdrv_write(bs
, sector_num
, buf
, nb_sectors
)) < 0)
1165 sector_num
+= nb_sectors
;
1166 len
= nb_sectors
<< BDRV_SECTOR_BITS
;
1171 /* add data from the last sector */
1173 if ((ret
= bdrv_read(bs
, sector_num
, tmp_buf
, 1)) < 0)
1175 memcpy(tmp_buf
, buf
, count
);
1176 if ((ret
= bdrv_write(bs
, sector_num
, tmp_buf
, 1)) < 0)
1183 * Writes to the file and ensures that no writes are reordered across this
1184 * request (acts as a barrier)
1186 * Returns 0 on success, -errno in error cases.
1188 int bdrv_pwrite_sync(BlockDriverState
*bs
, int64_t offset
,
1189 const void *buf
, int count
)
1193 ret
= bdrv_pwrite(bs
, offset
, buf
, count
);
1198 /* No flush needed for cache=writethrough, it uses O_DSYNC */
1199 if ((bs
->open_flags
& BDRV_O_CACHE_MASK
) != 0) {
1206 int coroutine_fn
bdrv_co_readv(BlockDriverState
*bs
, int64_t sector_num
,
1207 int nb_sectors
, QEMUIOVector
*qiov
)
1209 BlockDriver
*drv
= bs
->drv
;
1211 trace_bdrv_co_readv(bs
, sector_num
, nb_sectors
);
1216 if (bdrv_check_request(bs
, sector_num
, nb_sectors
)) {
1220 return drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1223 int coroutine_fn
bdrv_co_writev(BlockDriverState
*bs
, int64_t sector_num
,
1224 int nb_sectors
, QEMUIOVector
*qiov
)
1226 BlockDriver
*drv
= bs
->drv
;
1228 trace_bdrv_co_writev(bs
, sector_num
, nb_sectors
);
1233 if (bs
->read_only
) {
1236 if (bdrv_check_request(bs
, sector_num
, nb_sectors
)) {
1240 if (bs
->dirty_bitmap
) {
1241 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
1244 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
1245 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
1248 return drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
);
1252 * Truncate file to 'offset' bytes (needed only for file protocols)
1254 int bdrv_truncate(BlockDriverState
*bs
, int64_t offset
)
1256 BlockDriver
*drv
= bs
->drv
;
1260 if (!drv
->bdrv_truncate
)
1264 if (bdrv_in_use(bs
))
1266 ret
= drv
->bdrv_truncate(bs
, offset
);
1268 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
1269 if (bs
->change_cb
) {
1270 bs
->change_cb(bs
->change_opaque
, CHANGE_SIZE
);
1277 * Length of a allocated file in bytes. Sparse files are counted by actual
1278 * allocated space. Return < 0 if error or unknown.
1280 int64_t bdrv_get_allocated_file_size(BlockDriverState
*bs
)
1282 BlockDriver
*drv
= bs
->drv
;
1286 if (drv
->bdrv_get_allocated_file_size
) {
1287 return drv
->bdrv_get_allocated_file_size(bs
);
1290 return bdrv_get_allocated_file_size(bs
->file
);
1296 * Length of a file in bytes. Return < 0 if error or unknown.
1298 int64_t bdrv_getlength(BlockDriverState
*bs
)
1300 BlockDriver
*drv
= bs
->drv
;
1304 if (bs
->growable
|| bs
->removable
) {
1305 if (drv
->bdrv_getlength
) {
1306 return drv
->bdrv_getlength(bs
);
1309 return bs
->total_sectors
* BDRV_SECTOR_SIZE
;
1312 /* return 0 as number of sectors if no device present or error */
1313 void bdrv_get_geometry(BlockDriverState
*bs
, uint64_t *nb_sectors_ptr
)
1316 length
= bdrv_getlength(bs
);
1320 length
= length
>> BDRV_SECTOR_BITS
;
1321 *nb_sectors_ptr
= length
;
1325 uint8_t boot_ind
; /* 0x80 - active */
1326 uint8_t head
; /* starting head */
1327 uint8_t sector
; /* starting sector */
1328 uint8_t cyl
; /* starting cylinder */
1329 uint8_t sys_ind
; /* What partition type */
1330 uint8_t end_head
; /* end head */
1331 uint8_t end_sector
; /* end sector */
1332 uint8_t end_cyl
; /* end cylinder */
1333 uint32_t start_sect
; /* starting sector counting from 0 */
1334 uint32_t nr_sects
; /* nr of sectors in partition */
1335 } __attribute__((packed
));
1337 /* try to guess the disk logical geometry from the MSDOS partition table. Return 0 if OK, -1 if could not guess */
1338 static int guess_disk_lchs(BlockDriverState
*bs
,
1339 int *pcylinders
, int *pheads
, int *psectors
)
1341 uint8_t buf
[BDRV_SECTOR_SIZE
];
1342 int ret
, i
, heads
, sectors
, cylinders
;
1343 struct partition
*p
;
1345 uint64_t nb_sectors
;
1347 bdrv_get_geometry(bs
, &nb_sectors
);
1349 ret
= bdrv_read(bs
, 0, buf
, 1);
1352 /* test msdos magic */
1353 if (buf
[510] != 0x55 || buf
[511] != 0xaa)
1355 for(i
= 0; i
< 4; i
++) {
1356 p
= ((struct partition
*)(buf
+ 0x1be)) + i
;
1357 nr_sects
= le32_to_cpu(p
->nr_sects
);
1358 if (nr_sects
&& p
->end_head
) {
1359 /* We make the assumption that the partition terminates on
1360 a cylinder boundary */
1361 heads
= p
->end_head
+ 1;
1362 sectors
= p
->end_sector
& 63;
1365 cylinders
= nb_sectors
/ (heads
* sectors
);
1366 if (cylinders
< 1 || cylinders
> 16383)
1369 *psectors
= sectors
;
1370 *pcylinders
= cylinders
;
1372 printf("guessed geometry: LCHS=%d %d %d\n",
1373 cylinders
, heads
, sectors
);
1381 void bdrv_guess_geometry(BlockDriverState
*bs
, int *pcyls
, int *pheads
, int *psecs
)
1383 int translation
, lba_detected
= 0;
1384 int cylinders
, heads
, secs
;
1385 uint64_t nb_sectors
;
1387 /* if a geometry hint is available, use it */
1388 bdrv_get_geometry(bs
, &nb_sectors
);
1389 bdrv_get_geometry_hint(bs
, &cylinders
, &heads
, &secs
);
1390 translation
= bdrv_get_translation_hint(bs
);
1391 if (cylinders
!= 0) {
1396 if (guess_disk_lchs(bs
, &cylinders
, &heads
, &secs
) == 0) {
1398 /* if heads > 16, it means that a BIOS LBA
1399 translation was active, so the default
1400 hardware geometry is OK */
1402 goto default_geometry
;
1407 /* disable any translation to be in sync with
1408 the logical geometry */
1409 if (translation
== BIOS_ATA_TRANSLATION_AUTO
) {
1410 bdrv_set_translation_hint(bs
,
1411 BIOS_ATA_TRANSLATION_NONE
);
1416 /* if no geometry, use a standard physical disk geometry */
1417 cylinders
= nb_sectors
/ (16 * 63);
1419 if (cylinders
> 16383)
1421 else if (cylinders
< 2)
1426 if ((lba_detected
== 1) && (translation
== BIOS_ATA_TRANSLATION_AUTO
)) {
1427 if ((*pcyls
* *pheads
) <= 131072) {
1428 bdrv_set_translation_hint(bs
,
1429 BIOS_ATA_TRANSLATION_LARGE
);
1431 bdrv_set_translation_hint(bs
,
1432 BIOS_ATA_TRANSLATION_LBA
);
1436 bdrv_set_geometry_hint(bs
, *pcyls
, *pheads
, *psecs
);
1440 void bdrv_set_geometry_hint(BlockDriverState
*bs
,
1441 int cyls
, int heads
, int secs
)
1448 void bdrv_set_translation_hint(BlockDriverState
*bs
, int translation
)
1450 bs
->translation
= translation
;
1453 void bdrv_get_geometry_hint(BlockDriverState
*bs
,
1454 int *pcyls
, int *pheads
, int *psecs
)
1457 *pheads
= bs
->heads
;
1461 /* Recognize floppy formats */
1462 typedef struct FDFormat
{
1469 static const FDFormat fd_formats
[] = {
1470 /* First entry is default format */
1471 /* 1.44 MB 3"1/2 floppy disks */
1472 { FDRIVE_DRV_144
, 18, 80, 1, },
1473 { FDRIVE_DRV_144
, 20, 80, 1, },
1474 { FDRIVE_DRV_144
, 21, 80, 1, },
1475 { FDRIVE_DRV_144
, 21, 82, 1, },
1476 { FDRIVE_DRV_144
, 21, 83, 1, },
1477 { FDRIVE_DRV_144
, 22, 80, 1, },
1478 { FDRIVE_DRV_144
, 23, 80, 1, },
1479 { FDRIVE_DRV_144
, 24, 80, 1, },
1480 /* 2.88 MB 3"1/2 floppy disks */
1481 { FDRIVE_DRV_288
, 36, 80, 1, },
1482 { FDRIVE_DRV_288
, 39, 80, 1, },
1483 { FDRIVE_DRV_288
, 40, 80, 1, },
1484 { FDRIVE_DRV_288
, 44, 80, 1, },
1485 { FDRIVE_DRV_288
, 48, 80, 1, },
1486 /* 720 kB 3"1/2 floppy disks */
1487 { FDRIVE_DRV_144
, 9, 80, 1, },
1488 { FDRIVE_DRV_144
, 10, 80, 1, },
1489 { FDRIVE_DRV_144
, 10, 82, 1, },
1490 { FDRIVE_DRV_144
, 10, 83, 1, },
1491 { FDRIVE_DRV_144
, 13, 80, 1, },
1492 { FDRIVE_DRV_144
, 14, 80, 1, },
1493 /* 1.2 MB 5"1/4 floppy disks */
1494 { FDRIVE_DRV_120
, 15, 80, 1, },
1495 { FDRIVE_DRV_120
, 18, 80, 1, },
1496 { FDRIVE_DRV_120
, 18, 82, 1, },
1497 { FDRIVE_DRV_120
, 18, 83, 1, },
1498 { FDRIVE_DRV_120
, 20, 80, 1, },
1499 /* 720 kB 5"1/4 floppy disks */
1500 { FDRIVE_DRV_120
, 9, 80, 1, },
1501 { FDRIVE_DRV_120
, 11, 80, 1, },
1502 /* 360 kB 5"1/4 floppy disks */
1503 { FDRIVE_DRV_120
, 9, 40, 1, },
1504 { FDRIVE_DRV_120
, 9, 40, 0, },
1505 { FDRIVE_DRV_120
, 10, 41, 1, },
1506 { FDRIVE_DRV_120
, 10, 42, 1, },
1507 /* 320 kB 5"1/4 floppy disks */
1508 { FDRIVE_DRV_120
, 8, 40, 1, },
1509 { FDRIVE_DRV_120
, 8, 40, 0, },
1510 /* 360 kB must match 5"1/4 better than 3"1/2... */
1511 { FDRIVE_DRV_144
, 9, 80, 0, },
1513 { FDRIVE_DRV_NONE
, -1, -1, 0, },
1516 void bdrv_get_floppy_geometry_hint(BlockDriverState
*bs
, int *nb_heads
,
1517 int *max_track
, int *last_sect
,
1518 FDriveType drive_in
, FDriveType
*drive
)
1520 const FDFormat
*parse
;
1521 uint64_t nb_sectors
, size
;
1522 int i
, first_match
, match
;
1524 bdrv_get_geometry_hint(bs
, nb_heads
, max_track
, last_sect
);
1525 if (*nb_heads
!= 0 && *max_track
!= 0 && *last_sect
!= 0) {
1526 /* User defined disk */
1528 bdrv_get_geometry(bs
, &nb_sectors
);
1531 for (i
= 0; ; i
++) {
1532 parse
= &fd_formats
[i
];
1533 if (parse
->drive
== FDRIVE_DRV_NONE
) {
1536 if (drive_in
== parse
->drive
||
1537 drive_in
== FDRIVE_DRV_NONE
) {
1538 size
= (parse
->max_head
+ 1) * parse
->max_track
*
1540 if (nb_sectors
== size
) {
1544 if (first_match
== -1) {
1550 if (first_match
== -1) {
1553 match
= first_match
;
1555 parse
= &fd_formats
[match
];
1557 *nb_heads
= parse
->max_head
+ 1;
1558 *max_track
= parse
->max_track
;
1559 *last_sect
= parse
->last_sect
;
1560 *drive
= parse
->drive
;
1564 int bdrv_get_translation_hint(BlockDriverState
*bs
)
1566 return bs
->translation
;
1569 void bdrv_set_on_error(BlockDriverState
*bs
, BlockErrorAction on_read_error
,
1570 BlockErrorAction on_write_error
)
1572 bs
->on_read_error
= on_read_error
;
1573 bs
->on_write_error
= on_write_error
;
1576 BlockErrorAction
bdrv_get_on_error(BlockDriverState
*bs
, int is_read
)
1578 return is_read
? bs
->on_read_error
: bs
->on_write_error
;
1581 void bdrv_set_removable(BlockDriverState
*bs
, int removable
)
1583 bs
->removable
= removable
;
1584 if (removable
&& bs
== bs_snapshots
) {
1585 bs_snapshots
= NULL
;
1589 int bdrv_is_removable(BlockDriverState
*bs
)
1591 return bs
->removable
;
1594 int bdrv_is_read_only(BlockDriverState
*bs
)
1596 return bs
->read_only
;
1599 int bdrv_is_sg(BlockDriverState
*bs
)
1604 int bdrv_enable_write_cache(BlockDriverState
*bs
)
1606 return bs
->enable_write_cache
;
1609 /* XXX: no longer used */
1610 void bdrv_set_change_cb(BlockDriverState
*bs
,
1611 void (*change_cb
)(void *opaque
, int reason
),
1614 bs
->change_cb
= change_cb
;
1615 bs
->change_opaque
= opaque
;
1618 int bdrv_is_encrypted(BlockDriverState
*bs
)
1620 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1622 return bs
->encrypted
;
1625 int bdrv_key_required(BlockDriverState
*bs
)
1627 BlockDriverState
*backing_hd
= bs
->backing_hd
;
1629 if (backing_hd
&& backing_hd
->encrypted
&& !backing_hd
->valid_key
)
1631 return (bs
->encrypted
&& !bs
->valid_key
);
1634 int bdrv_set_key(BlockDriverState
*bs
, const char *key
)
1637 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
) {
1638 ret
= bdrv_set_key(bs
->backing_hd
, key
);
1644 if (!bs
->encrypted
) {
1646 } else if (!bs
->drv
|| !bs
->drv
->bdrv_set_key
) {
1649 ret
= bs
->drv
->bdrv_set_key(bs
, key
);
1652 } else if (!bs
->valid_key
) {
1654 /* call the change callback now, we skipped it on open */
1655 bs
->media_changed
= 1;
1657 bs
->change_cb(bs
->change_opaque
, CHANGE_MEDIA
);
1662 void bdrv_get_format(BlockDriverState
*bs
, char *buf
, int buf_size
)
1667 pstrcpy(buf
, buf_size
, bs
->drv
->format_name
);
1671 void bdrv_iterate_format(void (*it
)(void *opaque
, const char *name
),
1676 QLIST_FOREACH(drv
, &bdrv_drivers
, list
) {
1677 it(opaque
, drv
->format_name
);
1681 BlockDriverState
*bdrv_find(const char *name
)
1683 BlockDriverState
*bs
;
1685 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1686 if (!strcmp(name
, bs
->device_name
)) {
1693 BlockDriverState
*bdrv_next(BlockDriverState
*bs
)
1696 return QTAILQ_FIRST(&bdrv_states
);
1698 return QTAILQ_NEXT(bs
, list
);
1701 void bdrv_iterate(void (*it
)(void *opaque
, BlockDriverState
*bs
), void *opaque
)
1703 BlockDriverState
*bs
;
1705 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1710 const char *bdrv_get_device_name(BlockDriverState
*bs
)
1712 return bs
->device_name
;
1715 int bdrv_flush(BlockDriverState
*bs
)
1717 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
1721 if (bs
->drv
&& bdrv_has_async_flush(bs
->drv
) && qemu_in_coroutine()) {
1722 return bdrv_co_flush_em(bs
);
1725 if (bs
->drv
&& bs
->drv
->bdrv_flush
) {
1726 return bs
->drv
->bdrv_flush(bs
);
1730 * Some block drivers always operate in either writethrough or unsafe mode
1731 * and don't support bdrv_flush therefore. Usually qemu doesn't know how
1732 * the server works (because the behaviour is hardcoded or depends on
1733 * server-side configuration), so we can't ensure that everything is safe
1734 * on disk. Returning an error doesn't work because that would break guests
1735 * even if the server operates in writethrough mode.
1737 * Let's hope the user knows what he's doing.
1742 void bdrv_flush_all(void)
1744 BlockDriverState
*bs
;
1746 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1747 if (bs
->drv
&& !bdrv_is_read_only(bs
) &&
1748 (!bdrv_is_removable(bs
) || bdrv_is_inserted(bs
))) {
1754 int bdrv_has_zero_init(BlockDriverState
*bs
)
1758 if (bs
->drv
->bdrv_has_zero_init
) {
1759 return bs
->drv
->bdrv_has_zero_init(bs
);
1765 int bdrv_discard(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
)
1770 if (!bs
->drv
->bdrv_discard
) {
1773 return bs
->drv
->bdrv_discard(bs
, sector_num
, nb_sectors
);
1777 * Returns true iff the specified sector is present in the disk image. Drivers
1778 * not implementing the functionality are assumed to not support backing files,
1779 * hence all their sectors are reported as allocated.
1781 * 'pnum' is set to the number of sectors (including and immediately following
1782 * the specified sector) that are known to be in the same
1783 * allocated/unallocated state.
1785 * 'nb_sectors' is the max value 'pnum' should be set to.
1787 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t sector_num
, int nb_sectors
,
1791 if (!bs
->drv
->bdrv_is_allocated
) {
1792 if (sector_num
>= bs
->total_sectors
) {
1796 n
= bs
->total_sectors
- sector_num
;
1797 *pnum
= (n
< nb_sectors
) ? (n
) : (nb_sectors
);
1800 return bs
->drv
->bdrv_is_allocated(bs
, sector_num
, nb_sectors
, pnum
);
1803 void bdrv_mon_event(const BlockDriverState
*bdrv
,
1804 BlockMonEventAction action
, int is_read
)
1807 const char *action_str
;
1810 case BDRV_ACTION_REPORT
:
1811 action_str
= "report";
1813 case BDRV_ACTION_IGNORE
:
1814 action_str
= "ignore";
1816 case BDRV_ACTION_STOP
:
1817 action_str
= "stop";
1823 data
= qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
1826 is_read
? "read" : "write");
1827 monitor_protocol_event(QEVENT_BLOCK_IO_ERROR
, data
);
1829 qobject_decref(data
);
1832 static void bdrv_print_dict(QObject
*obj
, void *opaque
)
1835 Monitor
*mon
= opaque
;
1837 bs_dict
= qobject_to_qdict(obj
);
1839 monitor_printf(mon
, "%s: removable=%d",
1840 qdict_get_str(bs_dict
, "device"),
1841 qdict_get_bool(bs_dict
, "removable"));
1843 if (qdict_get_bool(bs_dict
, "removable")) {
1844 monitor_printf(mon
, " locked=%d", qdict_get_bool(bs_dict
, "locked"));
1847 if (qdict_haskey(bs_dict
, "inserted")) {
1848 QDict
*qdict
= qobject_to_qdict(qdict_get(bs_dict
, "inserted"));
1850 monitor_printf(mon
, " file=");
1851 monitor_print_filename(mon
, qdict_get_str(qdict
, "file"));
1852 if (qdict_haskey(qdict
, "backing_file")) {
1853 monitor_printf(mon
, " backing_file=");
1854 monitor_print_filename(mon
, qdict_get_str(qdict
, "backing_file"));
1856 monitor_printf(mon
, " ro=%d drv=%s encrypted=%d",
1857 qdict_get_bool(qdict
, "ro"),
1858 qdict_get_str(qdict
, "drv"),
1859 qdict_get_bool(qdict
, "encrypted"));
1861 monitor_printf(mon
, " [not inserted]");
1864 monitor_printf(mon
, "\n");
1867 void bdrv_info_print(Monitor
*mon
, const QObject
*data
)
1869 qlist_iter(qobject_to_qlist(data
), bdrv_print_dict
, mon
);
1872 void bdrv_info(Monitor
*mon
, QObject
**ret_data
)
1875 BlockDriverState
*bs
;
1877 bs_list
= qlist_new();
1879 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1882 bs_obj
= qobject_from_jsonf("{ 'device': %s, 'type': 'unknown', "
1883 "'removable': %i, 'locked': %i }",
1884 bs
->device_name
, bs
->removable
,
1889 QDict
*bs_dict
= qobject_to_qdict(bs_obj
);
1891 obj
= qobject_from_jsonf("{ 'file': %s, 'ro': %i, 'drv': %s, "
1892 "'encrypted': %i }",
1893 bs
->filename
, bs
->read_only
,
1894 bs
->drv
->format_name
,
1895 bdrv_is_encrypted(bs
));
1896 if (bs
->backing_file
[0] != '\0') {
1897 QDict
*qdict
= qobject_to_qdict(obj
);
1898 qdict_put(qdict
, "backing_file",
1899 qstring_from_str(bs
->backing_file
));
1902 qdict_put_obj(bs_dict
, "inserted", obj
);
1904 qlist_append_obj(bs_list
, bs_obj
);
1907 *ret_data
= QOBJECT(bs_list
);
1910 static void bdrv_stats_iter(QObject
*data
, void *opaque
)
1913 Monitor
*mon
= opaque
;
1915 qdict
= qobject_to_qdict(data
);
1916 monitor_printf(mon
, "%s:", qdict_get_str(qdict
, "device"));
1918 qdict
= qobject_to_qdict(qdict_get(qdict
, "stats"));
1919 monitor_printf(mon
, " rd_bytes=%" PRId64
1920 " wr_bytes=%" PRId64
1921 " rd_operations=%" PRId64
1922 " wr_operations=%" PRId64
1924 qdict_get_int(qdict
, "rd_bytes"),
1925 qdict_get_int(qdict
, "wr_bytes"),
1926 qdict_get_int(qdict
, "rd_operations"),
1927 qdict_get_int(qdict
, "wr_operations"));
1930 void bdrv_stats_print(Monitor
*mon
, const QObject
*data
)
1932 qlist_iter(qobject_to_qlist(data
), bdrv_stats_iter
, mon
);
1935 static QObject
* bdrv_info_stats_bs(BlockDriverState
*bs
)
1940 res
= qobject_from_jsonf("{ 'stats': {"
1941 "'rd_bytes': %" PRId64
","
1942 "'wr_bytes': %" PRId64
","
1943 "'rd_operations': %" PRId64
","
1944 "'wr_operations': %" PRId64
","
1945 "'wr_highest_offset': %" PRId64
1947 bs
->rd_bytes
, bs
->wr_bytes
,
1948 bs
->rd_ops
, bs
->wr_ops
,
1949 bs
->wr_highest_sector
*
1950 (uint64_t)BDRV_SECTOR_SIZE
);
1951 dict
= qobject_to_qdict(res
);
1953 if (*bs
->device_name
) {
1954 qdict_put(dict
, "device", qstring_from_str(bs
->device_name
));
1958 QObject
*parent
= bdrv_info_stats_bs(bs
->file
);
1959 qdict_put_obj(dict
, "parent", parent
);
1965 void bdrv_info_stats(Monitor
*mon
, QObject
**ret_data
)
1969 BlockDriverState
*bs
;
1971 devices
= qlist_new();
1973 QTAILQ_FOREACH(bs
, &bdrv_states
, list
) {
1974 obj
= bdrv_info_stats_bs(bs
);
1975 qlist_append_obj(devices
, obj
);
1978 *ret_data
= QOBJECT(devices
);
1981 const char *bdrv_get_encrypted_filename(BlockDriverState
*bs
)
1983 if (bs
->backing_hd
&& bs
->backing_hd
->encrypted
)
1984 return bs
->backing_file
;
1985 else if (bs
->encrypted
)
1986 return bs
->filename
;
1991 void bdrv_get_backing_filename(BlockDriverState
*bs
,
1992 char *filename
, int filename_size
)
1994 if (!bs
->backing_file
) {
1995 pstrcpy(filename
, filename_size
, "");
1997 pstrcpy(filename
, filename_size
, bs
->backing_file
);
2001 int bdrv_write_compressed(BlockDriverState
*bs
, int64_t sector_num
,
2002 const uint8_t *buf
, int nb_sectors
)
2004 BlockDriver
*drv
= bs
->drv
;
2007 if (!drv
->bdrv_write_compressed
)
2009 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2012 if (bs
->dirty_bitmap
) {
2013 set_dirty_bitmap(bs
, sector_num
, nb_sectors
, 1);
2016 return drv
->bdrv_write_compressed(bs
, sector_num
, buf
, nb_sectors
);
2019 int bdrv_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2021 BlockDriver
*drv
= bs
->drv
;
2024 if (!drv
->bdrv_get_info
)
2026 memset(bdi
, 0, sizeof(*bdi
));
2027 return drv
->bdrv_get_info(bs
, bdi
);
2030 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2031 int64_t pos
, int size
)
2033 BlockDriver
*drv
= bs
->drv
;
2036 if (drv
->bdrv_save_vmstate
)
2037 return drv
->bdrv_save_vmstate(bs
, buf
, pos
, size
);
2039 return bdrv_save_vmstate(bs
->file
, buf
, pos
, size
);
2043 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2044 int64_t pos
, int size
)
2046 BlockDriver
*drv
= bs
->drv
;
2049 if (drv
->bdrv_load_vmstate
)
2050 return drv
->bdrv_load_vmstate(bs
, buf
, pos
, size
);
2052 return bdrv_load_vmstate(bs
->file
, buf
, pos
, size
);
2056 void bdrv_debug_event(BlockDriverState
*bs
, BlkDebugEvent event
)
2058 BlockDriver
*drv
= bs
->drv
;
2060 if (!drv
|| !drv
->bdrv_debug_event
) {
2064 return drv
->bdrv_debug_event(bs
, event
);
2068 /**************************************************************/
2069 /* handling of snapshots */
2071 int bdrv_can_snapshot(BlockDriverState
*bs
)
2073 BlockDriver
*drv
= bs
->drv
;
2074 if (!drv
|| bdrv_is_removable(bs
) || bdrv_is_read_only(bs
)) {
2078 if (!drv
->bdrv_snapshot_create
) {
2079 if (bs
->file
!= NULL
) {
2080 return bdrv_can_snapshot(bs
->file
);
2088 int bdrv_is_snapshot(BlockDriverState
*bs
)
2090 return !!(bs
->open_flags
& BDRV_O_SNAPSHOT
);
2093 BlockDriverState
*bdrv_snapshots(void)
2095 BlockDriverState
*bs
;
2098 return bs_snapshots
;
2102 while ((bs
= bdrv_next(bs
))) {
2103 if (bdrv_can_snapshot(bs
)) {
2111 int bdrv_snapshot_create(BlockDriverState
*bs
,
2112 QEMUSnapshotInfo
*sn_info
)
2114 BlockDriver
*drv
= bs
->drv
;
2117 if (drv
->bdrv_snapshot_create
)
2118 return drv
->bdrv_snapshot_create(bs
, sn_info
);
2120 return bdrv_snapshot_create(bs
->file
, sn_info
);
2124 int bdrv_snapshot_goto(BlockDriverState
*bs
,
2125 const char *snapshot_id
)
2127 BlockDriver
*drv
= bs
->drv
;
2132 if (drv
->bdrv_snapshot_goto
)
2133 return drv
->bdrv_snapshot_goto(bs
, snapshot_id
);
2136 drv
->bdrv_close(bs
);
2137 ret
= bdrv_snapshot_goto(bs
->file
, snapshot_id
);
2138 open_ret
= drv
->bdrv_open(bs
, bs
->open_flags
);
2140 bdrv_delete(bs
->file
);
2150 int bdrv_snapshot_delete(BlockDriverState
*bs
, const char *snapshot_id
)
2152 BlockDriver
*drv
= bs
->drv
;
2155 if (drv
->bdrv_snapshot_delete
)
2156 return drv
->bdrv_snapshot_delete(bs
, snapshot_id
);
2158 return bdrv_snapshot_delete(bs
->file
, snapshot_id
);
2162 int bdrv_snapshot_list(BlockDriverState
*bs
,
2163 QEMUSnapshotInfo
**psn_info
)
2165 BlockDriver
*drv
= bs
->drv
;
2168 if (drv
->bdrv_snapshot_list
)
2169 return drv
->bdrv_snapshot_list(bs
, psn_info
);
2171 return bdrv_snapshot_list(bs
->file
, psn_info
);
2175 int bdrv_snapshot_load_tmp(BlockDriverState
*bs
,
2176 const char *snapshot_name
)
2178 BlockDriver
*drv
= bs
->drv
;
2182 if (!bs
->read_only
) {
2185 if (drv
->bdrv_snapshot_load_tmp
) {
2186 return drv
->bdrv_snapshot_load_tmp(bs
, snapshot_name
);
2191 #define NB_SUFFIXES 4
2193 char *get_human_readable_size(char *buf
, int buf_size
, int64_t size
)
2195 static const char suffixes
[NB_SUFFIXES
] = "KMGT";
2200 snprintf(buf
, buf_size
, "%" PRId64
, size
);
2203 for(i
= 0; i
< NB_SUFFIXES
; i
++) {
2204 if (size
< (10 * base
)) {
2205 snprintf(buf
, buf_size
, "%0.1f%c",
2206 (double)size
/ base
,
2209 } else if (size
< (1000 * base
) || i
== (NB_SUFFIXES
- 1)) {
2210 snprintf(buf
, buf_size
, "%" PRId64
"%c",
2211 ((size
+ (base
>> 1)) / base
),
2221 char *bdrv_snapshot_dump(char *buf
, int buf_size
, QEMUSnapshotInfo
*sn
)
2223 char buf1
[128], date_buf
[128], clock_buf
[128];
2233 snprintf(buf
, buf_size
,
2234 "%-10s%-20s%7s%20s%15s",
2235 "ID", "TAG", "VM SIZE", "DATE", "VM CLOCK");
2239 ptm
= localtime(&ti
);
2240 strftime(date_buf
, sizeof(date_buf
),
2241 "%Y-%m-%d %H:%M:%S", ptm
);
2243 localtime_r(&ti
, &tm
);
2244 strftime(date_buf
, sizeof(date_buf
),
2245 "%Y-%m-%d %H:%M:%S", &tm
);
2247 secs
= sn
->vm_clock_nsec
/ 1000000000;
2248 snprintf(clock_buf
, sizeof(clock_buf
),
2249 "%02d:%02d:%02d.%03d",
2251 (int)((secs
/ 60) % 60),
2253 (int)((sn
->vm_clock_nsec
/ 1000000) % 1000));
2254 snprintf(buf
, buf_size
,
2255 "%-10s%-20s%7s%20s%15s",
2256 sn
->id_str
, sn
->name
,
2257 get_human_readable_size(buf1
, sizeof(buf1
), sn
->vm_state_size
),
2265 /**************************************************************/
2268 BlockDriverAIOCB
*bdrv_aio_readv(BlockDriverState
*bs
, int64_t sector_num
,
2269 QEMUIOVector
*qiov
, int nb_sectors
,
2270 BlockDriverCompletionFunc
*cb
, void *opaque
)
2272 BlockDriver
*drv
= bs
->drv
;
2273 BlockDriverAIOCB
*ret
;
2275 trace_bdrv_aio_readv(bs
, sector_num
, nb_sectors
, opaque
);
2279 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2282 ret
= drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
2286 /* Update stats even though technically transfer has not happened. */
2287 bs
->rd_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
2294 typedef struct BlockCompleteData
{
2295 BlockDriverCompletionFunc
*cb
;
2297 BlockDriverState
*bs
;
2300 } BlockCompleteData
;
2302 static void block_complete_cb(void *opaque
, int ret
)
2304 BlockCompleteData
*b
= opaque
;
2306 if (b
->bs
->dirty_bitmap
) {
2307 set_dirty_bitmap(b
->bs
, b
->sector_num
, b
->nb_sectors
, 1);
2309 b
->cb(b
->opaque
, ret
);
2313 static BlockCompleteData
*blk_dirty_cb_alloc(BlockDriverState
*bs
,
2316 BlockDriverCompletionFunc
*cb
,
2319 BlockCompleteData
*blkdata
= qemu_mallocz(sizeof(BlockCompleteData
));
2323 blkdata
->opaque
= opaque
;
2324 blkdata
->sector_num
= sector_num
;
2325 blkdata
->nb_sectors
= nb_sectors
;
2330 BlockDriverAIOCB
*bdrv_aio_writev(BlockDriverState
*bs
, int64_t sector_num
,
2331 QEMUIOVector
*qiov
, int nb_sectors
,
2332 BlockDriverCompletionFunc
*cb
, void *opaque
)
2334 BlockDriver
*drv
= bs
->drv
;
2335 BlockDriverAIOCB
*ret
;
2336 BlockCompleteData
*blk_cb_data
;
2338 trace_bdrv_aio_writev(bs
, sector_num
, nb_sectors
, opaque
);
2344 if (bdrv_check_request(bs
, sector_num
, nb_sectors
))
2347 if (bs
->dirty_bitmap
) {
2348 blk_cb_data
= blk_dirty_cb_alloc(bs
, sector_num
, nb_sectors
, cb
,
2350 cb
= &block_complete_cb
;
2351 opaque
= blk_cb_data
;
2354 ret
= drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
2358 /* Update stats even though technically transfer has not happened. */
2359 bs
->wr_bytes
+= (unsigned) nb_sectors
* BDRV_SECTOR_SIZE
;
2361 if (bs
->wr_highest_sector
< sector_num
+ nb_sectors
- 1) {
2362 bs
->wr_highest_sector
= sector_num
+ nb_sectors
- 1;
2370 typedef struct MultiwriteCB
{
2375 BlockDriverCompletionFunc
*cb
;
2377 QEMUIOVector
*free_qiov
;
2382 static void multiwrite_user_cb(MultiwriteCB
*mcb
)
2386 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2387 mcb
->callbacks
[i
].cb(mcb
->callbacks
[i
].opaque
, mcb
->error
);
2388 if (mcb
->callbacks
[i
].free_qiov
) {
2389 qemu_iovec_destroy(mcb
->callbacks
[i
].free_qiov
);
2391 qemu_free(mcb
->callbacks
[i
].free_qiov
);
2392 qemu_vfree(mcb
->callbacks
[i
].free_buf
);
2396 static void multiwrite_cb(void *opaque
, int ret
)
2398 MultiwriteCB
*mcb
= opaque
;
2400 trace_multiwrite_cb(mcb
, ret
);
2402 if (ret
< 0 && !mcb
->error
) {
2406 mcb
->num_requests
--;
2407 if (mcb
->num_requests
== 0) {
2408 multiwrite_user_cb(mcb
);
2413 static int multiwrite_req_compare(const void *a
, const void *b
)
2415 const BlockRequest
*req1
= a
, *req2
= b
;
2418 * Note that we can't simply subtract req2->sector from req1->sector
2419 * here as that could overflow the return value.
2421 if (req1
->sector
> req2
->sector
) {
2423 } else if (req1
->sector
< req2
->sector
) {
2431 * Takes a bunch of requests and tries to merge them. Returns the number of
2432 * requests that remain after merging.
2434 static int multiwrite_merge(BlockDriverState
*bs
, BlockRequest
*reqs
,
2435 int num_reqs
, MultiwriteCB
*mcb
)
2439 // Sort requests by start sector
2440 qsort(reqs
, num_reqs
, sizeof(*reqs
), &multiwrite_req_compare
);
2442 // Check if adjacent requests touch the same clusters. If so, combine them,
2443 // filling up gaps with zero sectors.
2445 for (i
= 1; i
< num_reqs
; i
++) {
2447 int64_t oldreq_last
= reqs
[outidx
].sector
+ reqs
[outidx
].nb_sectors
;
2449 // This handles the cases that are valid for all block drivers, namely
2450 // exactly sequential writes and overlapping writes.
2451 if (reqs
[i
].sector
<= oldreq_last
) {
2455 // The block driver may decide that it makes sense to combine requests
2456 // even if there is a gap of some sectors between them. In this case,
2457 // the gap is filled with zeros (therefore only applicable for yet
2458 // unused space in format like qcow2).
2459 if (!merge
&& bs
->drv
->bdrv_merge_requests
) {
2460 merge
= bs
->drv
->bdrv_merge_requests(bs
, &reqs
[outidx
], &reqs
[i
]);
2463 if (reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1 > IOV_MAX
) {
2469 QEMUIOVector
*qiov
= qemu_mallocz(sizeof(*qiov
));
2470 qemu_iovec_init(qiov
,
2471 reqs
[outidx
].qiov
->niov
+ reqs
[i
].qiov
->niov
+ 1);
2473 // Add the first request to the merged one. If the requests are
2474 // overlapping, drop the last sectors of the first request.
2475 size
= (reqs
[i
].sector
- reqs
[outidx
].sector
) << 9;
2476 qemu_iovec_concat(qiov
, reqs
[outidx
].qiov
, size
);
2478 // We might need to add some zeros between the two requests
2479 if (reqs
[i
].sector
> oldreq_last
) {
2480 size_t zero_bytes
= (reqs
[i
].sector
- oldreq_last
) << 9;
2481 uint8_t *buf
= qemu_blockalign(bs
, zero_bytes
);
2482 memset(buf
, 0, zero_bytes
);
2483 qemu_iovec_add(qiov
, buf
, zero_bytes
);
2484 mcb
->callbacks
[i
].free_buf
= buf
;
2487 // Add the second request
2488 qemu_iovec_concat(qiov
, reqs
[i
].qiov
, reqs
[i
].qiov
->size
);
2490 reqs
[outidx
].nb_sectors
= qiov
->size
>> 9;
2491 reqs
[outidx
].qiov
= qiov
;
2493 mcb
->callbacks
[i
].free_qiov
= reqs
[outidx
].qiov
;
2496 reqs
[outidx
].sector
= reqs
[i
].sector
;
2497 reqs
[outidx
].nb_sectors
= reqs
[i
].nb_sectors
;
2498 reqs
[outidx
].qiov
= reqs
[i
].qiov
;
2506 * Submit multiple AIO write requests at once.
2508 * On success, the function returns 0 and all requests in the reqs array have
2509 * been submitted. In error case this function returns -1, and any of the
2510 * requests may or may not be submitted yet. In particular, this means that the
2511 * callback will be called for some of the requests, for others it won't. The
2512 * caller must check the error field of the BlockRequest to wait for the right
2513 * callbacks (if error != 0, no callback will be called).
2515 * The implementation may modify the contents of the reqs array, e.g. to merge
2516 * requests. However, the fields opaque and error are left unmodified as they
2517 * are used to signal failure for a single request to the caller.
2519 int bdrv_aio_multiwrite(BlockDriverState
*bs
, BlockRequest
*reqs
, int num_reqs
)
2521 BlockDriverAIOCB
*acb
;
2525 /* don't submit writes if we don't have a medium */
2526 if (bs
->drv
== NULL
) {
2527 for (i
= 0; i
< num_reqs
; i
++) {
2528 reqs
[i
].error
= -ENOMEDIUM
;
2533 if (num_reqs
== 0) {
2537 // Create MultiwriteCB structure
2538 mcb
= qemu_mallocz(sizeof(*mcb
) + num_reqs
* sizeof(*mcb
->callbacks
));
2539 mcb
->num_requests
= 0;
2540 mcb
->num_callbacks
= num_reqs
;
2542 for (i
= 0; i
< num_reqs
; i
++) {
2543 mcb
->callbacks
[i
].cb
= reqs
[i
].cb
;
2544 mcb
->callbacks
[i
].opaque
= reqs
[i
].opaque
;
2547 // Check for mergable requests
2548 num_reqs
= multiwrite_merge(bs
, reqs
, num_reqs
, mcb
);
2550 trace_bdrv_aio_multiwrite(mcb
, mcb
->num_callbacks
, num_reqs
);
2553 * Run the aio requests. As soon as one request can't be submitted
2554 * successfully, fail all requests that are not yet submitted (we must
2555 * return failure for all requests anyway)
2557 * num_requests cannot be set to the right value immediately: If
2558 * bdrv_aio_writev fails for some request, num_requests would be too high
2559 * and therefore multiwrite_cb() would never recognize the multiwrite
2560 * request as completed. We also cannot use the loop variable i to set it
2561 * when the first request fails because the callback may already have been
2562 * called for previously submitted requests. Thus, num_requests must be
2563 * incremented for each request that is submitted.
2565 * The problem that callbacks may be called early also means that we need
2566 * to take care that num_requests doesn't become 0 before all requests are
2567 * submitted - multiwrite_cb() would consider the multiwrite request
2568 * completed. A dummy request that is "completed" by a manual call to
2569 * multiwrite_cb() takes care of this.
2571 mcb
->num_requests
= 1;
2573 // Run the aio requests
2574 for (i
= 0; i
< num_reqs
; i
++) {
2575 mcb
->num_requests
++;
2576 acb
= bdrv_aio_writev(bs
, reqs
[i
].sector
, reqs
[i
].qiov
,
2577 reqs
[i
].nb_sectors
, multiwrite_cb
, mcb
);
2580 // We can only fail the whole thing if no request has been
2581 // submitted yet. Otherwise we'll wait for the submitted AIOs to
2582 // complete and report the error in the callback.
2584 trace_bdrv_aio_multiwrite_earlyfail(mcb
);
2587 trace_bdrv_aio_multiwrite_latefail(mcb
, i
);
2588 multiwrite_cb(mcb
, -EIO
);
2594 /* Complete the dummy request */
2595 multiwrite_cb(mcb
, 0);
2600 for (i
= 0; i
< mcb
->num_callbacks
; i
++) {
2601 reqs
[i
].error
= -EIO
;
2607 BlockDriverAIOCB
*bdrv_aio_flush(BlockDriverState
*bs
,
2608 BlockDriverCompletionFunc
*cb
, void *opaque
)
2610 BlockDriver
*drv
= bs
->drv
;
2612 trace_bdrv_aio_flush(bs
, opaque
);
2614 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2615 return bdrv_aio_noop_em(bs
, cb
, opaque
);
2620 return drv
->bdrv_aio_flush(bs
, cb
, opaque
);
2623 void bdrv_aio_cancel(BlockDriverAIOCB
*acb
)
2625 acb
->pool
->cancel(acb
);
2629 /**************************************************************/
2630 /* async block device emulation */
2632 typedef struct BlockDriverAIOCBSync
{
2633 BlockDriverAIOCB common
;
2636 /* vector translation state */
2640 } BlockDriverAIOCBSync
;
2642 static void bdrv_aio_cancel_em(BlockDriverAIOCB
*blockacb
)
2644 BlockDriverAIOCBSync
*acb
=
2645 container_of(blockacb
, BlockDriverAIOCBSync
, common
);
2646 qemu_bh_delete(acb
->bh
);
2648 qemu_aio_release(acb
);
2651 static AIOPool bdrv_em_aio_pool
= {
2652 .aiocb_size
= sizeof(BlockDriverAIOCBSync
),
2653 .cancel
= bdrv_aio_cancel_em
,
2656 static void bdrv_aio_bh_cb(void *opaque
)
2658 BlockDriverAIOCBSync
*acb
= opaque
;
2661 qemu_iovec_from_buffer(acb
->qiov
, acb
->bounce
, acb
->qiov
->size
);
2662 qemu_vfree(acb
->bounce
);
2663 acb
->common
.cb(acb
->common
.opaque
, acb
->ret
);
2664 qemu_bh_delete(acb
->bh
);
2666 qemu_aio_release(acb
);
2669 static BlockDriverAIOCB
*bdrv_aio_rw_vector(BlockDriverState
*bs
,
2673 BlockDriverCompletionFunc
*cb
,
2678 BlockDriverAIOCBSync
*acb
;
2680 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2681 acb
->is_write
= is_write
;
2683 acb
->bounce
= qemu_blockalign(bs
, qiov
->size
);
2686 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2689 qemu_iovec_to_buffer(acb
->qiov
, acb
->bounce
);
2690 acb
->ret
= bdrv_write(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2692 acb
->ret
= bdrv_read(bs
, sector_num
, acb
->bounce
, nb_sectors
);
2695 qemu_bh_schedule(acb
->bh
);
2697 return &acb
->common
;
2700 static BlockDriverAIOCB
*bdrv_aio_readv_em(BlockDriverState
*bs
,
2701 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2702 BlockDriverCompletionFunc
*cb
, void *opaque
)
2704 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 0);
2707 static BlockDriverAIOCB
*bdrv_aio_writev_em(BlockDriverState
*bs
,
2708 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2709 BlockDriverCompletionFunc
*cb
, void *opaque
)
2711 return bdrv_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
, 1);
2715 typedef struct BlockDriverAIOCBCoroutine
{
2716 BlockDriverAIOCB common
;
2720 } BlockDriverAIOCBCoroutine
;
2722 static void bdrv_aio_co_cancel_em(BlockDriverAIOCB
*blockacb
)
2727 static AIOPool bdrv_em_co_aio_pool
= {
2728 .aiocb_size
= sizeof(BlockDriverAIOCBCoroutine
),
2729 .cancel
= bdrv_aio_co_cancel_em
,
2732 static void bdrv_co_rw_bh(void *opaque
)
2734 BlockDriverAIOCBCoroutine
*acb
= opaque
;
2736 acb
->common
.cb(acb
->common
.opaque
, acb
->req
.error
);
2737 qemu_bh_delete(acb
->bh
);
2738 qemu_aio_release(acb
);
2741 static void coroutine_fn
bdrv_co_rw(void *opaque
)
2743 BlockDriverAIOCBCoroutine
*acb
= opaque
;
2744 BlockDriverState
*bs
= acb
->common
.bs
;
2746 if (!acb
->is_write
) {
2747 acb
->req
.error
= bs
->drv
->bdrv_co_readv(bs
, acb
->req
.sector
,
2748 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2750 acb
->req
.error
= bs
->drv
->bdrv_co_writev(bs
, acb
->req
.sector
,
2751 acb
->req
.nb_sectors
, acb
->req
.qiov
);
2754 acb
->bh
= qemu_bh_new(bdrv_co_rw_bh
, acb
);
2755 qemu_bh_schedule(acb
->bh
);
2758 static BlockDriverAIOCB
*bdrv_co_aio_rw_vector(BlockDriverState
*bs
,
2762 BlockDriverCompletionFunc
*cb
,
2767 BlockDriverAIOCBCoroutine
*acb
;
2769 acb
= qemu_aio_get(&bdrv_em_co_aio_pool
, bs
, cb
, opaque
);
2770 acb
->req
.sector
= sector_num
;
2771 acb
->req
.nb_sectors
= nb_sectors
;
2772 acb
->req
.qiov
= qiov
;
2773 acb
->is_write
= is_write
;
2775 co
= qemu_coroutine_create(bdrv_co_rw
);
2776 qemu_coroutine_enter(co
, acb
);
2778 return &acb
->common
;
2781 static BlockDriverAIOCB
*bdrv_co_aio_readv_em(BlockDriverState
*bs
,
2782 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2783 BlockDriverCompletionFunc
*cb
, void *opaque
)
2785 return bdrv_co_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
,
2789 static BlockDriverAIOCB
*bdrv_co_aio_writev_em(BlockDriverState
*bs
,
2790 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
2791 BlockDriverCompletionFunc
*cb
, void *opaque
)
2793 return bdrv_co_aio_rw_vector(bs
, sector_num
, qiov
, nb_sectors
, cb
, opaque
,
2797 static BlockDriverAIOCB
*bdrv_aio_flush_em(BlockDriverState
*bs
,
2798 BlockDriverCompletionFunc
*cb
, void *opaque
)
2800 BlockDriverAIOCBSync
*acb
;
2802 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2803 acb
->is_write
= 1; /* don't bounce in the completion hadler */
2809 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2812 qemu_bh_schedule(acb
->bh
);
2813 return &acb
->common
;
2816 static BlockDriverAIOCB
*bdrv_aio_noop_em(BlockDriverState
*bs
,
2817 BlockDriverCompletionFunc
*cb
, void *opaque
)
2819 BlockDriverAIOCBSync
*acb
;
2821 acb
= qemu_aio_get(&bdrv_em_aio_pool
, bs
, cb
, opaque
);
2822 acb
->is_write
= 1; /* don't bounce in the completion handler */
2828 acb
->bh
= qemu_bh_new(bdrv_aio_bh_cb
, acb
);
2831 qemu_bh_schedule(acb
->bh
);
2832 return &acb
->common
;
2835 /**************************************************************/
2836 /* sync block device emulation */
2838 static void bdrv_rw_em_cb(void *opaque
, int ret
)
2840 *(int *)opaque
= ret
;
2843 #define NOT_DONE 0x7fffffff
2845 static int bdrv_read_em(BlockDriverState
*bs
, int64_t sector_num
,
2846 uint8_t *buf
, int nb_sectors
)
2849 BlockDriverAIOCB
*acb
;
2853 async_ret
= NOT_DONE
;
2854 iov
.iov_base
= (void *)buf
;
2855 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2856 qemu_iovec_init_external(&qiov
, &iov
, 1);
2857 acb
= bdrv_aio_readv(bs
, sector_num
, &qiov
, nb_sectors
,
2858 bdrv_rw_em_cb
, &async_ret
);
2864 while (async_ret
== NOT_DONE
) {
2873 static int bdrv_write_em(BlockDriverState
*bs
, int64_t sector_num
,
2874 const uint8_t *buf
, int nb_sectors
)
2877 BlockDriverAIOCB
*acb
;
2881 async_ret
= NOT_DONE
;
2882 iov
.iov_base
= (void *)buf
;
2883 iov
.iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
;
2884 qemu_iovec_init_external(&qiov
, &iov
, 1);
2885 acb
= bdrv_aio_writev(bs
, sector_num
, &qiov
, nb_sectors
,
2886 bdrv_rw_em_cb
, &async_ret
);
2891 while (async_ret
== NOT_DONE
) {
2899 void bdrv_init(void)
2901 module_call_init(MODULE_INIT_BLOCK
);
2904 void bdrv_init_with_whitelist(void)
2906 use_bdrv_whitelist
= 1;
2910 void *qemu_aio_get(AIOPool
*pool
, BlockDriverState
*bs
,
2911 BlockDriverCompletionFunc
*cb
, void *opaque
)
2913 BlockDriverAIOCB
*acb
;
2915 if (pool
->free_aiocb
) {
2916 acb
= pool
->free_aiocb
;
2917 pool
->free_aiocb
= acb
->next
;
2919 acb
= qemu_mallocz(pool
->aiocb_size
);
2924 acb
->opaque
= opaque
;
2928 void qemu_aio_release(void *p
)
2930 BlockDriverAIOCB
*acb
= (BlockDriverAIOCB
*)p
;
2931 AIOPool
*pool
= acb
->pool
;
2932 acb
->next
= pool
->free_aiocb
;
2933 pool
->free_aiocb
= acb
;
2936 /**************************************************************/
2937 /* Coroutine block device emulation */
2939 typedef struct CoroutineIOCompletion
{
2940 Coroutine
*coroutine
;
2942 } CoroutineIOCompletion
;
2944 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
2946 CoroutineIOCompletion
*co
= opaque
;
2949 qemu_coroutine_enter(co
->coroutine
, NULL
);
2952 static int coroutine_fn
bdrv_co_io_em(BlockDriverState
*bs
, int64_t sector_num
,
2953 int nb_sectors
, QEMUIOVector
*iov
,
2956 CoroutineIOCompletion co
= {
2957 .coroutine
= qemu_coroutine_self(),
2959 BlockDriverAIOCB
*acb
;
2962 acb
= bdrv_aio_writev(bs
, sector_num
, iov
, nb_sectors
,
2963 bdrv_co_io_em_complete
, &co
);
2965 acb
= bdrv_aio_readv(bs
, sector_num
, iov
, nb_sectors
,
2966 bdrv_co_io_em_complete
, &co
);
2969 trace_bdrv_co_io(is_write
, acb
);
2973 qemu_coroutine_yield();
2978 static int coroutine_fn
bdrv_co_readv_em(BlockDriverState
*bs
,
2979 int64_t sector_num
, int nb_sectors
,
2982 return bdrv_co_io_em(bs
, sector_num
, nb_sectors
, iov
, false);
2985 static int coroutine_fn
bdrv_co_writev_em(BlockDriverState
*bs
,
2986 int64_t sector_num
, int nb_sectors
,
2989 return bdrv_co_io_em(bs
, sector_num
, nb_sectors
, iov
, true);
2992 static int coroutine_fn
bdrv_co_flush_em(BlockDriverState
*bs
)
2994 CoroutineIOCompletion co
= {
2995 .coroutine
= qemu_coroutine_self(),
2997 BlockDriverAIOCB
*acb
;
2999 acb
= bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
3003 qemu_coroutine_yield();
3007 /**************************************************************/
3008 /* removable device support */
3011 * Return TRUE if the media is present
3013 int bdrv_is_inserted(BlockDriverState
*bs
)
3015 BlockDriver
*drv
= bs
->drv
;
3019 if (!drv
->bdrv_is_inserted
)
3020 return !bs
->tray_open
;
3021 ret
= drv
->bdrv_is_inserted(bs
);
3026 * Return TRUE if the media changed since the last call to this
3027 * function. It is currently only used for floppy disks
3029 int bdrv_media_changed(BlockDriverState
*bs
)
3031 BlockDriver
*drv
= bs
->drv
;
3034 if (!drv
|| !drv
->bdrv_media_changed
)
3037 ret
= drv
->bdrv_media_changed(bs
);
3038 if (ret
== -ENOTSUP
)
3039 ret
= bs
->media_changed
;
3040 bs
->media_changed
= 0;
3045 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3047 int bdrv_eject(BlockDriverState
*bs
, int eject_flag
)
3049 BlockDriver
*drv
= bs
->drv
;
3051 if (eject_flag
&& bs
->locked
) {
3055 if (drv
&& drv
->bdrv_eject
) {
3056 drv
->bdrv_eject(bs
, eject_flag
);
3058 bs
->tray_open
= eject_flag
;
3062 int bdrv_is_locked(BlockDriverState
*bs
)
3068 * Lock or unlock the media (if it is locked, the user won't be able
3069 * to eject it manually).
3071 void bdrv_set_locked(BlockDriverState
*bs
, int locked
)
3073 BlockDriver
*drv
= bs
->drv
;
3075 trace_bdrv_set_locked(bs
, locked
);
3077 bs
->locked
= locked
;
3078 if (drv
&& drv
->bdrv_set_locked
) {
3079 drv
->bdrv_set_locked(bs
, locked
);
3083 /* needed for generic scsi interface */
3085 int bdrv_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
3087 BlockDriver
*drv
= bs
->drv
;
3089 if (drv
&& drv
->bdrv_ioctl
)
3090 return drv
->bdrv_ioctl(bs
, req
, buf
);
3094 BlockDriverAIOCB
*bdrv_aio_ioctl(BlockDriverState
*bs
,
3095 unsigned long int req
, void *buf
,
3096 BlockDriverCompletionFunc
*cb
, void *opaque
)
3098 BlockDriver
*drv
= bs
->drv
;
3100 if (drv
&& drv
->bdrv_aio_ioctl
)
3101 return drv
->bdrv_aio_ioctl(bs
, req
, buf
, cb
, opaque
);
3107 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
3109 return qemu_memalign((bs
&& bs
->buffer_alignment
) ? bs
->buffer_alignment
: 512, size
);
3112 void bdrv_set_dirty_tracking(BlockDriverState
*bs
, int enable
)
3114 int64_t bitmap_size
;
3116 bs
->dirty_count
= 0;
3118 if (!bs
->dirty_bitmap
) {
3119 bitmap_size
= (bdrv_getlength(bs
) >> BDRV_SECTOR_BITS
) +
3120 BDRV_SECTORS_PER_DIRTY_CHUNK
* 8 - 1;
3121 bitmap_size
/= BDRV_SECTORS_PER_DIRTY_CHUNK
* 8;
3123 bs
->dirty_bitmap
= qemu_mallocz(bitmap_size
);
3126 if (bs
->dirty_bitmap
) {
3127 qemu_free(bs
->dirty_bitmap
);
3128 bs
->dirty_bitmap
= NULL
;
3133 int bdrv_get_dirty(BlockDriverState
*bs
, int64_t sector
)
3135 int64_t chunk
= sector
/ (int64_t)BDRV_SECTORS_PER_DIRTY_CHUNK
;
3137 if (bs
->dirty_bitmap
&&
3138 (sector
<< BDRV_SECTOR_BITS
) < bdrv_getlength(bs
)) {
3139 return !!(bs
->dirty_bitmap
[chunk
/ (sizeof(unsigned long) * 8)] &
3140 (1UL << (chunk
% (sizeof(unsigned long) * 8))));
3146 void bdrv_reset_dirty(BlockDriverState
*bs
, int64_t cur_sector
,
3149 set_dirty_bitmap(bs
, cur_sector
, nr_sectors
, 0);
3152 int64_t bdrv_get_dirty_count(BlockDriverState
*bs
)
3154 return bs
->dirty_count
;
3157 void bdrv_set_in_use(BlockDriverState
*bs
, int in_use
)
3159 assert(bs
->in_use
!= in_use
);
3160 bs
->in_use
= in_use
;
3163 int bdrv_in_use(BlockDriverState
*bs
)
3168 int bdrv_img_create(const char *filename
, const char *fmt
,
3169 const char *base_filename
, const char *base_fmt
,
3170 char *options
, uint64_t img_size
, int flags
)
3172 QEMUOptionParameter
*param
= NULL
, *create_options
= NULL
;
3173 QEMUOptionParameter
*backing_fmt
, *backing_file
, *size
;
3174 BlockDriverState
*bs
= NULL
;
3175 BlockDriver
*drv
, *proto_drv
;
3176 BlockDriver
*backing_drv
= NULL
;
3178 QEMUOptionParameter
*cow_file
;
3180 /* Find driver and parse its options */
3181 drv
= bdrv_find_format(fmt
);
3183 error_report("Unknown file format '%s'", fmt
);
3188 proto_drv
= bdrv_find_protocol(filename
);
3190 error_report("Unknown protocol '%s'", filename
);
3195 create_options
= append_option_parameters(create_options
,
3196 drv
->create_options
);
3197 create_options
= append_option_parameters(create_options
,
3198 proto_drv
->create_options
);
3200 /* Create parameter list with default values */
3201 param
= parse_option_parameters("", create_options
, param
);
3203 set_option_parameter_int(param
, BLOCK_OPT_SIZE
, img_size
);
3205 /* Parse -o options */
3207 param
= parse_option_parameters(options
, create_options
, param
);
3208 if (param
== NULL
) {
3209 error_report("Invalid options for file format '%s'.", fmt
);
3215 if (base_filename
) {
3216 if (set_option_parameter(param
, BLOCK_OPT_BACKING_FILE
,
3218 error_report("Backing file not supported for file format '%s'",
3226 if (set_option_parameter(param
, BLOCK_OPT_BACKING_FMT
, base_fmt
)) {
3227 error_report("Backing file format not supported for file "
3228 "format '%s'", fmt
);
3234 backing_file
= get_option_parameter(param
, BLOCK_OPT_BACKING_FILE
);
3235 if (backing_file
&& backing_file
->value
.s
) {
3236 if (!strcmp(filename
, backing_file
->value
.s
)) {
3237 error_report("Error: Trying to create an image with the "
3238 "same filename as the backing file");
3244 backing_fmt
= get_option_parameter(param
, BLOCK_OPT_BACKING_FMT
);
3245 if (backing_fmt
&& backing_fmt
->value
.s
) {
3246 backing_drv
= bdrv_find_format(backing_fmt
->value
.s
);
3248 error_report("Unknown backing file format '%s'",
3249 backing_fmt
->value
.s
);
3257 if (!strcmp(fmt
, "raw")) {
3258 cow_file
= get_option_parameter(param
, BLOCK_OPT_COW_FILE
);
3259 if(cow_file
->value
.s
&& cow_file
->value
.s
) {
3260 if( !strcmp(cow_file
->value
.s
,backing_file
->value
.s
)) {
3261 error_report("Error: Trying to create an cow file with the "
3262 "same filename as the backing file");
3267 if( !strcmp(cow_file
->value
.s
, filename
)) {
3268 error_report("Error: Trying to create an cow file with the "
3269 "same filename as the image file");
3276 // The size for the image must always be specified, with one exception:
3277 // If we are using a backing file, we can obtain the size from there
3278 size
= get_option_parameter(param
, BLOCK_OPT_SIZE
);
3279 if (size
&& size
->value
.n
== -1) {
3280 if (backing_file
&& backing_file
->value
.s
) {
3286 ret
= bdrv_open(bs
, backing_file
->value
.s
, flags
, backing_drv
);
3288 error_report("Could not open '%s'", backing_file
->value
.s
);
3291 bdrv_get_geometry(bs
, &size
);
3294 snprintf(buf
, sizeof(buf
), "%" PRId64
, size
);
3295 set_option_parameter(param
, BLOCK_OPT_SIZE
, buf
);
3297 error_report("Image creation needs a size parameter");
3303 printf("Formatting '%s', fmt=%s ", filename
, fmt
);
3304 print_option_parameters(param
);
3307 ret
= bdrv_create(drv
, filename
, param
);
3310 if (ret
== -ENOTSUP
) {
3311 error_report("Formatting or formatting option not supported for "
3312 "file format '%s'", fmt
);
3313 } else if (ret
== -EFBIG
) {
3314 error_report("The image size is too large for file format '%s'",
3317 error_report("%s: error while creating %s: %s", filename
, fmt
,
3323 free_option_parameters(create_options
);
3324 free_option_parameters(param
);