2 * Block driver for RAW files (posix)
4 * Copyright (c) 2006 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 "qemu/osdep.h"
25 #include "qapi/error.h"
26 #include "qemu/cutils.h"
27 #include "qemu/error-report.h"
28 #include "block/block_int.h"
29 #include "qemu/module.h"
31 #include "block/thread-pool.h"
33 #include "block/raw-aio.h"
34 #include "qapi/util.h"
35 #include "qapi/qmp/qstring.h"
37 #if defined(__APPLE__) && (__MACH__)
39 #include <sys/param.h>
40 #include <IOKit/IOKitLib.h>
41 #include <IOKit/IOBSD.h>
42 #include <IOKit/storage/IOMediaBSDClient.h>
43 #include <IOKit/storage/IOMedia.h>
44 #include <IOKit/storage/IOCDMedia.h>
45 //#include <IOKit/storage/IOCDTypes.h>
46 #include <IOKit/storage/IODVDMedia.h>
47 #include <CoreFoundation/CoreFoundation.h>
51 #define _POSIX_PTHREAD_SEMANTICS 1
55 #include <sys/ioctl.h>
56 #include <sys/param.h>
57 #include <linux/cdrom.h>
60 #include <linux/hdreg.h>
66 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
69 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
70 #include <linux/falloc.h>
72 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
78 #include <sys/ioctl.h>
79 #include <sys/disklabel.h>
84 #include <sys/ioctl.h>
85 #include <sys/disklabel.h>
91 #include <sys/ioctl.h>
92 #include <sys/diskslice.h>
102 # define DEBUG_BLOCK_PRINT 1
104 # define DEBUG_BLOCK_PRINT 0
106 #define DPRINTF(fmt, ...) \
108 if (DEBUG_BLOCK_PRINT) { \
109 printf(fmt, ## __VA_ARGS__); \
113 /* OS X does not have O_DSYNC */
116 #define O_DSYNC O_SYNC
117 #elif defined(O_FSYNC)
118 #define O_DSYNC O_FSYNC
122 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
124 #define O_DIRECT O_DSYNC
130 #define MAX_BLOCKSIZE 4096
132 typedef struct BDRVRawState
{
142 bool has_write_zeroes
:1;
143 bool discard_zeroes
:1;
144 bool use_linux_aio
:1;
145 bool page_cache_inconsistent
:1;
147 bool needs_alignment
;
150 typedef struct BDRVRawReopenState
{
153 } BDRVRawReopenState
;
155 static int fd_open(BlockDriverState
*bs
);
156 static int64_t raw_getlength(BlockDriverState
*bs
);
158 typedef struct RawPosixAIOData
{
159 BlockDriverState
*bs
;
162 struct iovec
*aio_iov
;
167 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
172 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
173 static int cdrom_reopen(BlockDriverState
*bs
);
176 #if defined(__NetBSD__)
177 static int raw_normalize_devicepath(const char **filename
)
179 static char namebuf
[PATH_MAX
];
180 const char *dp
, *fname
;
184 dp
= strrchr(fname
, '/');
185 if (lstat(fname
, &sb
) < 0) {
186 fprintf(stderr
, "%s: stat failed: %s\n",
187 fname
, strerror(errno
));
191 if (!S_ISBLK(sb
.st_mode
)) {
196 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
198 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
199 (int)(dp
- fname
), fname
, dp
+ 1);
201 fprintf(stderr
, "%s is a block device", fname
);
203 fprintf(stderr
, ", using %s\n", *filename
);
208 static int raw_normalize_devicepath(const char **filename
)
215 * Get logical block size via ioctl. On success store it in @sector_size_p.
217 static int probe_logical_blocksize(int fd
, unsigned int *sector_size_p
)
219 unsigned int sector_size
;
220 bool success
= false;
224 static const unsigned long ioctl_list
[] = {
228 #ifdef DKIOCGETBLOCKSIZE
231 #ifdef DIOCGSECTORSIZE
236 /* Try a few ioctls to get the right size */
237 for (i
= 0; i
< (int)ARRAY_SIZE(ioctl_list
); i
++) {
238 if (ioctl(fd
, ioctl_list
[i
], §or_size
) >= 0) {
239 *sector_size_p
= sector_size
;
244 return success
? 0 : -errno
;
248 * Get physical block size of @fd.
249 * On success, store it in @blk_size and return 0.
250 * On failure, return -errno.
252 static int probe_physical_blocksize(int fd
, unsigned int *blk_size
)
255 if (ioctl(fd
, BLKPBSZGET
, blk_size
) < 0) {
264 /* Check if read is allowed with given memory buffer and length.
266 * This function is used to check O_DIRECT memory buffer and request alignment.
268 static bool raw_is_io_aligned(int fd
, void *buf
, size_t len
)
270 ssize_t ret
= pread(fd
, buf
, len
, 0);
277 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
278 * other errors (e.g. real I/O error), which could happen on a failed
279 * drive, since we only care about probing alignment.
281 if (errno
!= EINVAL
) {
289 static void raw_probe_alignment(BlockDriverState
*bs
, int fd
, Error
**errp
)
291 BDRVRawState
*s
= bs
->opaque
;
293 size_t max_align
= MAX(MAX_BLOCKSIZE
, getpagesize());
295 /* For SCSI generic devices the alignment is not really used.
296 With buffered I/O, we don't have any restrictions. */
297 if (bdrv_is_sg(bs
) || !s
->needs_alignment
) {
298 bs
->bl
.request_alignment
= 1;
303 bs
->bl
.request_alignment
= 0;
305 /* Let's try to use the logical blocksize for the alignment. */
306 if (probe_logical_blocksize(fd
, &bs
->bl
.request_alignment
) < 0) {
307 bs
->bl
.request_alignment
= 0;
312 if (xfsctl(NULL
, fd
, XFS_IOC_DIOINFO
, &da
) >= 0) {
313 bs
->bl
.request_alignment
= da
.d_miniosz
;
314 /* The kernel returns wrong information for d_mem */
315 /* s->buf_align = da.d_mem; */
320 /* If we could not get the sizes so far, we can only guess them */
323 buf
= qemu_memalign(max_align
, 2 * max_align
);
324 for (align
= 512; align
<= max_align
; align
<<= 1) {
325 if (raw_is_io_aligned(fd
, buf
+ align
, max_align
)) {
326 s
->buf_align
= align
;
333 if (!bs
->bl
.request_alignment
) {
335 buf
= qemu_memalign(s
->buf_align
, max_align
);
336 for (align
= 512; align
<= max_align
; align
<<= 1) {
337 if (raw_is_io_aligned(fd
, buf
, align
)) {
338 bs
->bl
.request_alignment
= align
;
345 if (!s
->buf_align
|| !bs
->bl
.request_alignment
) {
346 error_setg(errp
, "Could not find working O_DIRECT alignment");
347 error_append_hint(errp
, "Try cache.direct=off\n");
351 static void raw_parse_flags(int bdrv_flags
, int *open_flags
)
353 assert(open_flags
!= NULL
);
355 *open_flags
|= O_BINARY
;
356 *open_flags
&= ~O_ACCMODE
;
357 if (bdrv_flags
& BDRV_O_RDWR
) {
358 *open_flags
|= O_RDWR
;
360 *open_flags
|= O_RDONLY
;
363 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
364 * and O_DIRECT for no caching. */
365 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
366 *open_flags
|= O_DIRECT
;
370 static void raw_parse_filename(const char *filename
, QDict
*options
,
373 /* The filename does not have to be prefixed by the protocol name, since
374 * "file" is the default protocol; therefore, the return value of this
375 * function call can be ignored. */
376 strstart(filename
, "file:", &filename
);
378 qdict_put_str(options
, "filename", filename
);
381 static QemuOptsList raw_runtime_opts
= {
383 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
387 .type
= QEMU_OPT_STRING
,
388 .help
= "File name of the image",
392 .type
= QEMU_OPT_STRING
,
393 .help
= "host AIO implementation (threads, native)",
395 { /* end of list */ }
399 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
400 int bdrv_flags
, int open_flags
, Error
**errp
)
402 BDRVRawState
*s
= bs
->opaque
;
404 Error
*local_err
= NULL
;
405 const char *filename
= NULL
;
406 BlockdevAioOptions aio
, aio_default
;
410 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
411 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
413 error_propagate(errp
, local_err
);
418 filename
= qemu_opt_get(opts
, "filename");
420 ret
= raw_normalize_devicepath(&filename
);
422 error_setg_errno(errp
, -ret
, "Could not normalize device path");
426 aio_default
= (bdrv_flags
& BDRV_O_NATIVE_AIO
)
427 ? BLOCKDEV_AIO_OPTIONS_NATIVE
428 : BLOCKDEV_AIO_OPTIONS_THREADS
;
429 aio
= qapi_enum_parse(BlockdevAioOptions_lookup
, qemu_opt_get(opts
, "aio"),
430 BLOCKDEV_AIO_OPTIONS__MAX
, aio_default
, &local_err
);
432 error_propagate(errp
, local_err
);
436 s
->use_linux_aio
= (aio
== BLOCKDEV_AIO_OPTIONS_NATIVE
);
438 s
->open_flags
= open_flags
;
439 raw_parse_flags(bdrv_flags
, &s
->open_flags
);
442 fd
= qemu_open(filename
, s
->open_flags
, 0644);
445 error_setg_errno(errp
, errno
, "Could not open '%s'", filename
);
453 #ifdef CONFIG_LINUX_AIO
454 /* Currently Linux does AIO only for files opened with O_DIRECT */
455 if (s
->use_linux_aio
&& !(s
->open_flags
& O_DIRECT
)) {
456 error_setg(errp
, "aio=native was specified, but it requires "
457 "cache.direct=on, which was not specified.");
462 if (s
->use_linux_aio
) {
463 error_setg(errp
, "aio=native was specified, but is not supported "
468 #endif /* !defined(CONFIG_LINUX_AIO) */
470 s
->has_discard
= true;
471 s
->has_write_zeroes
= true;
472 bs
->supported_zero_flags
= BDRV_REQ_MAY_UNMAP
;
473 if ((bs
->open_flags
& BDRV_O_NOCACHE
) != 0) {
474 s
->needs_alignment
= true;
477 if (fstat(s
->fd
, &st
) < 0) {
479 error_setg_errno(errp
, errno
, "Could not stat file");
482 if (S_ISREG(st
.st_mode
)) {
483 s
->discard_zeroes
= true;
484 s
->has_fallocate
= true;
486 if (S_ISBLK(st
.st_mode
)) {
487 #ifdef BLKDISCARDZEROES
489 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
490 s
->discard_zeroes
= true;
494 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
495 * not rely on the contents of discarded blocks unless using O_DIRECT.
496 * Same for BLKZEROOUT.
498 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
499 s
->discard_zeroes
= false;
500 s
->has_write_zeroes
= false;
505 if (S_ISCHR(st
.st_mode
)) {
507 * The file is a char device (disk), which on FreeBSD isn't behind
508 * a pager, so force all requests to be aligned. This is needed
509 * so QEMU makes sure all IO operations on the device are aligned
510 * to sector size, or else FreeBSD will reject them with EINVAL.
512 s
->needs_alignment
= true;
517 if (platform_test_xfs_fd(s
->fd
)) {
524 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
531 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
534 BDRVRawState
*s
= bs
->opaque
;
536 s
->type
= FTYPE_FILE
;
537 return raw_open_common(bs
, options
, flags
, 0, errp
);
540 static int raw_reopen_prepare(BDRVReopenState
*state
,
541 BlockReopenQueue
*queue
, Error
**errp
)
544 BDRVRawReopenState
*rs
;
546 Error
*local_err
= NULL
;
548 assert(state
!= NULL
);
549 assert(state
->bs
!= NULL
);
551 s
= state
->bs
->opaque
;
553 state
->opaque
= g_new0(BDRVRawReopenState
, 1);
556 if (s
->type
== FTYPE_CD
) {
557 rs
->open_flags
|= O_NONBLOCK
;
560 raw_parse_flags(state
->flags
, &rs
->open_flags
);
564 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
566 fcntl_flags
|= O_NOATIME
;
570 /* Not all operating systems have O_ASYNC, and those that don't
571 * will not let us track the state into rs->open_flags (typically
572 * you achieve the same effect with an ioctl, for example I_SETSIG
573 * on Solaris). But we do not use O_ASYNC, so that's fine.
575 assert((s
->open_flags
& O_ASYNC
) == 0);
578 if ((rs
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
579 /* dup the original fd */
580 rs
->fd
= qemu_dup(s
->fd
);
582 ret
= fcntl_setfl(rs
->fd
, rs
->open_flags
);
590 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
592 const char *normalized_filename
= state
->bs
->filename
;
593 ret
= raw_normalize_devicepath(&normalized_filename
);
595 error_setg_errno(errp
, -ret
, "Could not normalize device path");
597 assert(!(rs
->open_flags
& O_CREAT
));
598 rs
->fd
= qemu_open(normalized_filename
, rs
->open_flags
);
600 error_setg_errno(errp
, errno
, "Could not reopen file");
606 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
607 * alignment with the new fd. */
609 raw_probe_alignment(state
->bs
, rs
->fd
, &local_err
);
613 error_propagate(errp
, local_err
);
621 static void raw_reopen_commit(BDRVReopenState
*state
)
623 BDRVRawReopenState
*rs
= state
->opaque
;
624 BDRVRawState
*s
= state
->bs
->opaque
;
626 s
->open_flags
= rs
->open_flags
;
631 g_free(state
->opaque
);
632 state
->opaque
= NULL
;
636 static void raw_reopen_abort(BDRVReopenState
*state
)
638 BDRVRawReopenState
*rs
= state
->opaque
;
640 /* nothing to do if NULL, we didn't get far enough */
649 g_free(state
->opaque
);
650 state
->opaque
= NULL
;
653 static int hdev_get_max_transfer_length(BlockDriverState
*bs
, int fd
)
657 short max_sectors
= 0;
658 if (bs
->sg
&& ioctl(fd
, BLKSECTGET
, &max_bytes
) == 0) {
660 } else if (!bs
->sg
&& ioctl(fd
, BLKSECTGET
, &max_sectors
) == 0) {
661 return max_sectors
<< BDRV_SECTOR_BITS
;
670 static int hdev_get_max_segments(const struct stat
*st
)
680 sysfspath
= g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
681 major(st
->st_rdev
), minor(st
->st_rdev
));
682 fd
= open(sysfspath
, O_RDONLY
);
688 ret
= read(fd
, buf
, sizeof(buf
) - 1);
689 } while (ret
== -1 && errno
== EINTR
);
693 } else if (ret
== 0) {
698 /* The file is ended with '\n', pass 'end' to accept that. */
699 ret
= qemu_strtol(buf
, &end
, 10, &max_segments
);
700 if (ret
== 0 && end
&& *end
== '\n') {
715 static void raw_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
717 BDRVRawState
*s
= bs
->opaque
;
720 if (!fstat(s
->fd
, &st
)) {
721 if (S_ISBLK(st
.st_mode
) || S_ISCHR(st
.st_mode
)) {
722 int ret
= hdev_get_max_transfer_length(bs
, s
->fd
);
723 if (ret
> 0 && ret
<= BDRV_REQUEST_MAX_BYTES
) {
724 bs
->bl
.max_transfer
= pow2floor(ret
);
726 ret
= hdev_get_max_segments(&st
);
728 bs
->bl
.max_transfer
= MIN(bs
->bl
.max_transfer
,
729 ret
* getpagesize());
734 raw_probe_alignment(bs
, s
->fd
, errp
);
735 bs
->bl
.min_mem_alignment
= s
->buf_align
;
736 bs
->bl
.opt_mem_alignment
= MAX(s
->buf_align
, getpagesize());
739 static int check_for_dasd(int fd
)
742 struct dasd_information2_t info
= {0};
744 return ioctl(fd
, BIODASDINFO2
, &info
);
751 * Try to get @bs's logical and physical block size.
752 * On success, store them in @bsz and return zero.
753 * On failure, return negative errno.
755 static int hdev_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
757 BDRVRawState
*s
= bs
->opaque
;
760 /* If DASD, get blocksizes */
761 if (check_for_dasd(s
->fd
) < 0) {
764 ret
= probe_logical_blocksize(s
->fd
, &bsz
->log
);
768 return probe_physical_blocksize(s
->fd
, &bsz
->phys
);
772 * Try to get @bs's geometry: cyls, heads, sectors.
773 * On success, store them in @geo and return 0.
774 * On failure return -errno.
775 * (Allows block driver to assign default geometry values that guest sees)
778 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
780 BDRVRawState
*s
= bs
->opaque
;
781 struct hd_geometry ioctl_geo
= {0};
783 /* If DASD, get its geometry */
784 if (check_for_dasd(s
->fd
) < 0) {
787 if (ioctl(s
->fd
, HDIO_GETGEO
, &ioctl_geo
) < 0) {
790 /* HDIO_GETGEO may return success even though geo contains zeros
791 (e.g. certain multipath setups) */
792 if (!ioctl_geo
.heads
|| !ioctl_geo
.sectors
|| !ioctl_geo
.cylinders
) {
795 /* Do not return a geometry for partition */
796 if (ioctl_geo
.start
!= 0) {
799 geo
->heads
= ioctl_geo
.heads
;
800 geo
->sectors
= ioctl_geo
.sectors
;
801 geo
->cylinders
= ioctl_geo
.cylinders
;
805 #else /* __linux__ */
806 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
812 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
816 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
824 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
826 BDRVRawState
*s
= aiocb
->bs
->opaque
;
829 if (s
->page_cache_inconsistent
) {
833 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
835 /* There is no clear definition of the semantics of a failing fsync(),
836 * so we may have to assume the worst. The sad truth is that this
837 * assumption is correct for Linux. Some pages are now probably marked
838 * clean in the page cache even though they are inconsistent with the
839 * on-disk contents. The next fdatasync() call would succeed, but no
840 * further writeback attempt will be made. We can't get back to a state
841 * in which we know what is on disk (we would have to rewrite
842 * everything that was touched since the last fdatasync() at least), so
843 * make bdrv_flush() fail permanently. Given that the behaviour isn't
844 * really defined, I have little hope that other OSes are doing better.
846 * Obviously, this doesn't affect O_DIRECT, which bypasses the page
848 if ((s
->open_flags
& O_DIRECT
) == 0) {
849 s
->page_cache_inconsistent
= true;
858 static bool preadv_present
= true;
861 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
863 return preadv(fd
, iov
, nr_iov
, offset
);
867 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
869 return pwritev(fd
, iov
, nr_iov
, offset
);
874 static bool preadv_present
= false;
877 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
883 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
890 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
895 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
896 len
= qemu_pwritev(aiocb
->aio_fildes
,
901 len
= qemu_preadv(aiocb
->aio_fildes
,
905 } while (len
== -1 && errno
== EINTR
);
914 * Read/writes the data to/from a given linear buffer.
916 * Returns the number of bytes handles or -errno in case of an error. Short
917 * reads are only returned if the end of the file is reached.
919 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
924 while (offset
< aiocb
->aio_nbytes
) {
925 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
926 len
= pwrite(aiocb
->aio_fildes
,
927 (const char *)buf
+ offset
,
928 aiocb
->aio_nbytes
- offset
,
929 aiocb
->aio_offset
+ offset
);
931 len
= pread(aiocb
->aio_fildes
,
933 aiocb
->aio_nbytes
- offset
,
934 aiocb
->aio_offset
+ offset
);
936 if (len
== -1 && errno
== EINTR
) {
938 } else if (len
== -1 && errno
== EINVAL
&&
939 (aiocb
->bs
->open_flags
& BDRV_O_NOCACHE
) &&
940 !(aiocb
->aio_type
& QEMU_AIO_WRITE
) &&
942 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
943 * after a short read. Assume that O_DIRECT short reads only occur
944 * at EOF. Therefore this is a short read, not an I/O error.
947 } else if (len
== -1) {
950 } else if (len
== 0) {
959 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
964 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
966 * If there is just a single buffer, and it is properly aligned
967 * we can just use plain pread/pwrite without any problems.
969 if (aiocb
->aio_niov
== 1) {
970 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
973 * We have more than one iovec, and all are properly aligned.
975 * Try preadv/pwritev first and fall back to linearizing the
976 * buffer if it's not supported.
978 if (preadv_present
) {
979 nbytes
= handle_aiocb_rw_vector(aiocb
);
980 if (nbytes
== aiocb
->aio_nbytes
||
981 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
984 preadv_present
= false;
988 * XXX(hch): short read/write. no easy way to handle the reminder
989 * using these interfaces. For now retry using plain
995 * Ok, we have to do it the hard way, copy all segments into
996 * a single aligned buffer.
998 buf
= qemu_try_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
1003 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1007 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
1008 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
1009 p
+= aiocb
->aio_iov
[i
].iov_len
;
1011 assert(p
- buf
== aiocb
->aio_nbytes
);
1014 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
1015 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
1017 size_t count
= aiocb
->aio_nbytes
, copy
;
1020 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
1022 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
1023 copy
= aiocb
->aio_iov
[i
].iov_len
;
1025 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
1026 assert(count
>= copy
);
1038 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1040 struct xfs_flock64 fl
;
1043 memset(&fl
, 0, sizeof(fl
));
1044 fl
.l_whence
= SEEK_SET
;
1045 fl
.l_start
= offset
;
1048 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
1050 DPRINTF("cannot write zero range (%s)\n", strerror(errno
));
1057 static int xfs_discard(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1059 struct xfs_flock64 fl
;
1062 memset(&fl
, 0, sizeof(fl
));
1063 fl
.l_whence
= SEEK_SET
;
1064 fl
.l_start
= offset
;
1067 if (xfsctl(NULL
, s
->fd
, XFS_IOC_UNRESVSP64
, &fl
) < 0) {
1069 DPRINTF("cannot punch hole (%s)\n", strerror(errno
));
1077 static int translate_err(int err
)
1079 if (err
== -ENODEV
|| err
== -ENOSYS
|| err
== -EOPNOTSUPP
||
1086 #ifdef CONFIG_FALLOCATE
1087 static int do_fallocate(int fd
, int mode
, off_t offset
, off_t len
)
1090 if (fallocate(fd
, mode
, offset
, len
) == 0) {
1093 } while (errno
== EINTR
);
1094 return translate_err(-errno
);
1098 static ssize_t
handle_aiocb_write_zeroes_block(RawPosixAIOData
*aiocb
)
1101 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1103 if (!s
->has_write_zeroes
) {
1109 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1110 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
1113 } while (errno
== EINTR
);
1115 ret
= translate_err(-errno
);
1118 if (ret
== -ENOTSUP
) {
1119 s
->has_write_zeroes
= false;
1124 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
1126 #if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1127 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1130 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1131 return handle_aiocb_write_zeroes_block(aiocb
);
1136 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1140 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1141 if (s
->has_write_zeroes
) {
1142 int ret
= do_fallocate(s
->fd
, FALLOC_FL_ZERO_RANGE
,
1143 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1144 if (ret
== 0 || ret
!= -ENOTSUP
) {
1147 s
->has_write_zeroes
= false;
1151 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1152 if (s
->has_discard
&& s
->has_fallocate
) {
1153 int ret
= do_fallocate(s
->fd
,
1154 FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1155 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1157 ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1158 if (ret
== 0 || ret
!= -ENOTSUP
) {
1161 s
->has_fallocate
= false;
1162 } else if (ret
!= -ENOTSUP
) {
1165 s
->has_discard
= false;
1170 #ifdef CONFIG_FALLOCATE
1171 if (s
->has_fallocate
&& aiocb
->aio_offset
>= bdrv_getlength(aiocb
->bs
)) {
1172 int ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1173 if (ret
== 0 || ret
!= -ENOTSUP
) {
1176 s
->has_fallocate
= false;
1183 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
1185 int ret
= -EOPNOTSUPP
;
1186 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1188 if (!s
->has_discard
) {
1192 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1195 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1196 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
1199 } while (errno
== EINTR
);
1206 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1210 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1211 ret
= do_fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1212 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1216 ret
= translate_err(ret
);
1217 if (ret
== -ENOTSUP
) {
1218 s
->has_discard
= false;
1223 static int aio_worker(void *arg
)
1225 RawPosixAIOData
*aiocb
= arg
;
1228 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
1230 ret
= handle_aiocb_rw(aiocb
);
1231 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1232 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
1233 0, aiocb
->aio_nbytes
- ret
);
1235 ret
= aiocb
->aio_nbytes
;
1237 if (ret
== aiocb
->aio_nbytes
) {
1239 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1243 case QEMU_AIO_WRITE
:
1244 ret
= handle_aiocb_rw(aiocb
);
1245 if (ret
== aiocb
->aio_nbytes
) {
1247 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1251 case QEMU_AIO_FLUSH
:
1252 ret
= handle_aiocb_flush(aiocb
);
1254 case QEMU_AIO_IOCTL
:
1255 ret
= handle_aiocb_ioctl(aiocb
);
1257 case QEMU_AIO_DISCARD
:
1258 ret
= handle_aiocb_discard(aiocb
);
1260 case QEMU_AIO_WRITE_ZEROES
:
1261 ret
= handle_aiocb_write_zeroes(aiocb
);
1264 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
1273 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
1274 int64_t offset
, QEMUIOVector
*qiov
,
1275 int count
, int type
)
1277 RawPosixAIOData
*acb
= g_new(RawPosixAIOData
, 1);
1281 acb
->aio_type
= type
;
1282 acb
->aio_fildes
= fd
;
1284 acb
->aio_nbytes
= count
;
1285 acb
->aio_offset
= offset
;
1288 acb
->aio_iov
= qiov
->iov
;
1289 acb
->aio_niov
= qiov
->niov
;
1290 assert(qiov
->size
== count
);
1293 trace_paio_submit_co(offset
, count
, type
);
1294 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1295 return thread_pool_submit_co(pool
, aio_worker
, acb
);
1298 static BlockAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
1299 int64_t offset
, QEMUIOVector
*qiov
, int count
,
1300 BlockCompletionFunc
*cb
, void *opaque
, int type
)
1302 RawPosixAIOData
*acb
= g_new(RawPosixAIOData
, 1);
1306 acb
->aio_type
= type
;
1307 acb
->aio_fildes
= fd
;
1309 acb
->aio_nbytes
= count
;
1310 acb
->aio_offset
= offset
;
1313 acb
->aio_iov
= qiov
->iov
;
1314 acb
->aio_niov
= qiov
->niov
;
1315 assert(qiov
->size
== acb
->aio_nbytes
);
1318 trace_paio_submit(acb
, opaque
, offset
, count
, type
);
1319 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1320 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1323 static int coroutine_fn
raw_co_prw(BlockDriverState
*bs
, uint64_t offset
,
1324 uint64_t bytes
, QEMUIOVector
*qiov
, int type
)
1326 BDRVRawState
*s
= bs
->opaque
;
1328 if (fd_open(bs
) < 0)
1332 * Check if the underlying device requires requests to be aligned,
1333 * and if the request we are trying to submit is aligned or not.
1334 * If this is the case tell the low-level driver that it needs
1335 * to copy the buffer.
1337 if (s
->needs_alignment
) {
1338 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1339 type
|= QEMU_AIO_MISALIGNED
;
1340 #ifdef CONFIG_LINUX_AIO
1341 } else if (s
->use_linux_aio
) {
1342 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1343 assert(qiov
->size
== bytes
);
1344 return laio_co_submit(bs
, aio
, s
->fd
, offset
, qiov
, type
);
1349 return paio_submit_co(bs
, s
->fd
, offset
, qiov
, bytes
, type
);
1352 static int coroutine_fn
raw_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1353 uint64_t bytes
, QEMUIOVector
*qiov
,
1356 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_READ
);
1359 static int coroutine_fn
raw_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1360 uint64_t bytes
, QEMUIOVector
*qiov
,
1364 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_WRITE
);
1367 static void raw_aio_plug(BlockDriverState
*bs
)
1369 #ifdef CONFIG_LINUX_AIO
1370 BDRVRawState
*s
= bs
->opaque
;
1371 if (s
->use_linux_aio
) {
1372 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1373 laio_io_plug(bs
, aio
);
1378 static void raw_aio_unplug(BlockDriverState
*bs
)
1380 #ifdef CONFIG_LINUX_AIO
1381 BDRVRawState
*s
= bs
->opaque
;
1382 if (s
->use_linux_aio
) {
1383 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1384 laio_io_unplug(bs
, aio
);
1389 static BlockAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1390 BlockCompletionFunc
*cb
, void *opaque
)
1392 BDRVRawState
*s
= bs
->opaque
;
1394 if (fd_open(bs
) < 0)
1397 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1400 static void raw_close(BlockDriverState
*bs
)
1402 BDRVRawState
*s
= bs
->opaque
;
1410 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
, Error
**errp
)
1412 BDRVRawState
*s
= bs
->opaque
;
1416 if (fstat(s
->fd
, &st
)) {
1418 error_setg_errno(errp
, -ret
, "Failed to fstat() the file");
1422 if (S_ISREG(st
.st_mode
)) {
1423 if (ftruncate(s
->fd
, offset
) < 0) {
1425 error_setg_errno(errp
, -ret
, "Failed to resize the file");
1428 } else if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1429 if (offset
> raw_getlength(bs
)) {
1430 error_setg(errp
, "Cannot grow device files");
1434 error_setg(errp
, "Resizing this file is not supported");
1442 static int64_t raw_getlength(BlockDriverState
*bs
)
1444 BDRVRawState
*s
= bs
->opaque
;
1450 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1451 struct disklabel dl
;
1453 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1455 return (uint64_t)dl
.d_secsize
*
1456 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1460 #elif defined(__NetBSD__)
1461 static int64_t raw_getlength(BlockDriverState
*bs
)
1463 BDRVRawState
*s
= bs
->opaque
;
1469 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1470 struct dkwedge_info dkw
;
1472 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1473 return dkw
.dkw_size
* 512;
1475 struct disklabel dl
;
1477 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1479 return (uint64_t)dl
.d_secsize
*
1480 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1485 #elif defined(__sun__)
1486 static int64_t raw_getlength(BlockDriverState
*bs
)
1488 BDRVRawState
*s
= bs
->opaque
;
1489 struct dk_minfo minfo
;
1499 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1501 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1503 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1507 * There are reports that lseek on some devices fails, but
1508 * irc discussion said that contingency on contingency was overkill.
1510 size
= lseek(s
->fd
, 0, SEEK_END
);
1516 #elif defined(CONFIG_BSD)
1517 static int64_t raw_getlength(BlockDriverState
*bs
)
1519 BDRVRawState
*s
= bs
->opaque
;
1523 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1532 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1535 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1536 #ifdef DIOCGMEDIASIZE
1537 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1538 #elif defined(DIOCGPART)
1541 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1542 size
= pi
.media_size
;
1548 #if defined(__APPLE__) && defined(__MACH__)
1550 uint64_t sectors
= 0;
1551 uint32_t sector_size
= 0;
1553 if (ioctl(fd
, DKIOCGETBLOCKCOUNT
, §ors
) == 0
1554 && ioctl(fd
, DKIOCGETBLOCKSIZE
, §or_size
) == 0) {
1555 size
= sectors
* sector_size
;
1557 size
= lseek(fd
, 0LL, SEEK_END
);
1564 size
= lseek(fd
, 0LL, SEEK_END
);
1569 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1572 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1573 if (size
== 2048LL * (unsigned)-1)
1575 /* XXX no disc? maybe we need to reopen... */
1576 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1583 size
= lseek(fd
, 0, SEEK_END
);
1591 static int64_t raw_getlength(BlockDriverState
*bs
)
1593 BDRVRawState
*s
= bs
->opaque
;
1602 size
= lseek(s
->fd
, 0, SEEK_END
);
1610 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
1613 BDRVRawState
*s
= bs
->opaque
;
1615 if (fstat(s
->fd
, &st
) < 0) {
1618 return (int64_t)st
.st_blocks
* 512;
1621 static int raw_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1625 int64_t total_size
= 0;
1627 PreallocMode prealloc
;
1629 Error
*local_err
= NULL
;
1631 strstart(filename
, "file:", &filename
);
1633 /* Read out options */
1634 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1636 nocow
= qemu_opt_get_bool(opts
, BLOCK_OPT_NOCOW
, false);
1637 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
1638 prealloc
= qapi_enum_parse(PreallocMode_lookup
, buf
,
1639 PREALLOC_MODE__MAX
, PREALLOC_MODE_OFF
,
1643 error_propagate(errp
, local_err
);
1648 fd
= qemu_open(filename
, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
,
1652 error_setg_errno(errp
, -result
, "Could not create file");
1658 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1659 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1660 * will be ignored since any failure of this operation should not
1661 * block the left work.
1664 if (ioctl(fd
, FS_IOC_GETFLAGS
, &attr
) == 0) {
1665 attr
|= FS_NOCOW_FL
;
1666 ioctl(fd
, FS_IOC_SETFLAGS
, &attr
);
1672 #ifdef CONFIG_POSIX_FALLOCATE
1673 case PREALLOC_MODE_FALLOC
:
1675 * Truncating before posix_fallocate() makes it about twice slower on
1676 * file systems that do not support fallocate(), trying to check if a
1677 * block is allocated before allocating it, so don't do that here.
1679 result
= -posix_fallocate(fd
, 0, total_size
);
1681 /* posix_fallocate() doesn't set errno. */
1682 error_setg_errno(errp
, -result
,
1683 "Could not preallocate data for the new file");
1687 case PREALLOC_MODE_FULL
:
1690 * Knowing the final size from the beginning could allow the file
1691 * system driver to do less allocations and possibly avoid
1692 * fragmentation of the file.
1694 if (ftruncate(fd
, total_size
) != 0) {
1696 error_setg_errno(errp
, -result
, "Could not resize file");
1700 int64_t num
= 0, left
= total_size
;
1701 buf
= g_malloc0(65536);
1704 num
= MIN(left
, 65536);
1705 result
= write(fd
, buf
, num
);
1708 error_setg_errno(errp
, -result
,
1709 "Could not write to the new file");
1718 error_setg_errno(errp
, -result
,
1719 "Could not flush new file to disk");
1725 case PREALLOC_MODE_OFF
:
1726 if (ftruncate(fd
, total_size
) != 0) {
1728 error_setg_errno(errp
, -result
, "Could not resize file");
1733 error_setg(errp
, "Unsupported preallocation mode: %s",
1734 PreallocMode_lookup
[prealloc
]);
1739 if (qemu_close(fd
) != 0 && result
== 0) {
1741 error_setg_errno(errp
, -result
, "Could not close the new file");
1748 * Find allocation range in @bs around offset @start.
1749 * May change underlying file descriptor's file offset.
1750 * If @start is not in a hole, store @start in @data, and the
1751 * beginning of the next hole in @hole, and return 0.
1752 * If @start is in a non-trailing hole, store @start in @hole and the
1753 * beginning of the next non-hole in @data, and return 0.
1754 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1755 * If we can't find out, return a negative errno other than -ENXIO.
1757 static int find_allocation(BlockDriverState
*bs
, off_t start
,
1758 off_t
*data
, off_t
*hole
)
1760 #if defined SEEK_HOLE && defined SEEK_DATA
1761 BDRVRawState
*s
= bs
->opaque
;
1766 * D1. offs == start: start is in data
1767 * D2. offs > start: start is in a hole, next data at offs
1768 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1769 * or start is beyond EOF
1770 * If the latter happens, the file has been truncated behind
1771 * our back since we opened it. All bets are off then.
1772 * Treating like a trailing hole is simplest.
1773 * D4. offs < 0, errno != ENXIO: we learned nothing
1775 offs
= lseek(s
->fd
, start
, SEEK_DATA
);
1777 return -errno
; /* D3 or D4 */
1779 assert(offs
>= start
);
1782 /* D2: in hole, next data at offs */
1788 /* D1: in data, end not yet known */
1792 * H1. offs == start: start is in a hole
1793 * If this happens here, a hole has been dug behind our back
1794 * since the previous lseek().
1795 * H2. offs > start: either start is in data, next hole at offs,
1796 * or start is in trailing hole, EOF at offs
1797 * Linux treats trailing holes like any other hole: offs ==
1798 * start. Solaris seeks to EOF instead: offs > start (blech).
1799 * If that happens here, a hole has been dug behind our back
1800 * since the previous lseek().
1801 * H3. offs < 0, errno = ENXIO: start is beyond EOF
1802 * If this happens, the file has been truncated behind our
1803 * back since we opened it. Treat it like a trailing hole.
1804 * H4. offs < 0, errno != ENXIO: we learned nothing
1805 * Pretend we know nothing at all, i.e. "forget" about D1.
1807 offs
= lseek(s
->fd
, start
, SEEK_HOLE
);
1809 return -errno
; /* D1 and (H3 or H4) */
1811 assert(offs
>= start
);
1815 * D1 and H2: either in data, next hole at offs, or it was in
1816 * data but is now in a trailing hole. In the latter case,
1817 * all bets are off. Treating it as if it there was data all
1818 * the way to EOF is safe, so simply do that.
1833 * Returns the allocation status of the specified sectors.
1835 * If 'sector_num' is beyond the end of the disk image the return value is 0
1836 * and 'pnum' is set to 0.
1838 * 'pnum' is set to the number of sectors (including and immediately following
1839 * the specified sector) that are known to be in the same
1840 * allocated/unallocated state.
1842 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1843 * beyond the end of the disk image it will be clamped.
1845 static int64_t coroutine_fn
raw_co_get_block_status(BlockDriverState
*bs
,
1847 int nb_sectors
, int *pnum
,
1848 BlockDriverState
**file
)
1850 off_t start
, data
= 0, hole
= 0;
1859 start
= sector_num
* BDRV_SECTOR_SIZE
;
1860 total_size
= bdrv_getlength(bs
);
1861 if (total_size
< 0) {
1863 } else if (start
>= total_size
) {
1866 } else if (start
+ nb_sectors
* BDRV_SECTOR_SIZE
> total_size
) {
1867 nb_sectors
= DIV_ROUND_UP(total_size
- start
, BDRV_SECTOR_SIZE
);
1870 ret
= find_allocation(bs
, start
, &data
, &hole
);
1871 if (ret
== -ENXIO
) {
1874 ret
= BDRV_BLOCK_ZERO
;
1875 } else if (ret
< 0) {
1876 /* No info available, so pretend there are no holes */
1878 ret
= BDRV_BLOCK_DATA
;
1879 } else if (data
== start
) {
1880 /* On a data extent, compute sectors to the end of the extent,
1881 * possibly including a partial sector at EOF. */
1882 *pnum
= MIN(nb_sectors
, DIV_ROUND_UP(hole
- start
, BDRV_SECTOR_SIZE
));
1883 ret
= BDRV_BLOCK_DATA
;
1885 /* On a hole, compute sectors to the beginning of the next extent. */
1886 assert(hole
== start
);
1887 *pnum
= MIN(nb_sectors
, (data
- start
) / BDRV_SECTOR_SIZE
);
1888 ret
= BDRV_BLOCK_ZERO
;
1891 return ret
| BDRV_BLOCK_OFFSET_VALID
| start
;
1894 static coroutine_fn BlockAIOCB
*raw_aio_pdiscard(BlockDriverState
*bs
,
1895 int64_t offset
, int count
,
1896 BlockCompletionFunc
*cb
, void *opaque
)
1898 BDRVRawState
*s
= bs
->opaque
;
1900 return paio_submit(bs
, s
->fd
, offset
, NULL
, count
,
1901 cb
, opaque
, QEMU_AIO_DISCARD
);
1904 static int coroutine_fn
raw_co_pwrite_zeroes(
1905 BlockDriverState
*bs
, int64_t offset
,
1906 int count
, BdrvRequestFlags flags
)
1908 BDRVRawState
*s
= bs
->opaque
;
1910 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1911 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, count
,
1912 QEMU_AIO_WRITE_ZEROES
);
1913 } else if (s
->discard_zeroes
) {
1914 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, count
,
1920 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1922 BDRVRawState
*s
= bs
->opaque
;
1924 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
1925 bdi
->can_write_zeroes_with_unmap
= s
->discard_zeroes
;
1929 static QemuOptsList raw_create_opts
= {
1930 .name
= "raw-create-opts",
1931 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
1934 .name
= BLOCK_OPT_SIZE
,
1935 .type
= QEMU_OPT_SIZE
,
1936 .help
= "Virtual disk size"
1939 .name
= BLOCK_OPT_NOCOW
,
1940 .type
= QEMU_OPT_BOOL
,
1941 .help
= "Turn off copy-on-write (valid only on btrfs)"
1944 .name
= BLOCK_OPT_PREALLOC
,
1945 .type
= QEMU_OPT_STRING
,
1946 .help
= "Preallocation mode (allowed values: off, falloc, full)"
1948 { /* end of list */ }
1952 BlockDriver bdrv_file
= {
1953 .format_name
= "file",
1954 .protocol_name
= "file",
1955 .instance_size
= sizeof(BDRVRawState
),
1956 .bdrv_needs_filename
= true,
1957 .bdrv_probe
= NULL
, /* no probe for protocols */
1958 .bdrv_parse_filename
= raw_parse_filename
,
1959 .bdrv_file_open
= raw_open
,
1960 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1961 .bdrv_reopen_commit
= raw_reopen_commit
,
1962 .bdrv_reopen_abort
= raw_reopen_abort
,
1963 .bdrv_close
= raw_close
,
1964 .bdrv_create
= raw_create
,
1965 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
1966 .bdrv_co_get_block_status
= raw_co_get_block_status
,
1967 .bdrv_co_pwrite_zeroes
= raw_co_pwrite_zeroes
,
1969 .bdrv_co_preadv
= raw_co_preadv
,
1970 .bdrv_co_pwritev
= raw_co_pwritev
,
1971 .bdrv_aio_flush
= raw_aio_flush
,
1972 .bdrv_aio_pdiscard
= raw_aio_pdiscard
,
1973 .bdrv_refresh_limits
= raw_refresh_limits
,
1974 .bdrv_io_plug
= raw_aio_plug
,
1975 .bdrv_io_unplug
= raw_aio_unplug
,
1977 .bdrv_truncate
= raw_truncate
,
1978 .bdrv_getlength
= raw_getlength
,
1979 .bdrv_get_info
= raw_get_info
,
1980 .bdrv_get_allocated_file_size
1981 = raw_get_allocated_file_size
,
1983 .create_opts
= &raw_create_opts
,
1986 /***********************************************/
1989 #if defined(__APPLE__) && defined(__MACH__)
1990 static kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
1991 CFIndex maxPathSize
, int flags
);
1992 static char *FindEjectableOpticalMedia(io_iterator_t
*mediaIterator
)
1994 kern_return_t kernResult
= KERN_FAILURE
;
1995 mach_port_t masterPort
;
1996 CFMutableDictionaryRef classesToMatch
;
1997 const char *matching_array
[] = {kIODVDMediaClass
, kIOCDMediaClass
};
1998 char *mediaType
= NULL
;
2000 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
2001 if ( KERN_SUCCESS
!= kernResult
) {
2002 printf( "IOMasterPort returned %d\n", kernResult
);
2006 for (index
= 0; index
< ARRAY_SIZE(matching_array
); index
++) {
2007 classesToMatch
= IOServiceMatching(matching_array
[index
]);
2008 if (classesToMatch
== NULL
) {
2009 error_report("IOServiceMatching returned NULL for %s",
2010 matching_array
[index
]);
2013 CFDictionarySetValue(classesToMatch
, CFSTR(kIOMediaEjectableKey
),
2015 kernResult
= IOServiceGetMatchingServices(masterPort
, classesToMatch
,
2017 if (kernResult
!= KERN_SUCCESS
) {
2018 error_report("Note: IOServiceGetMatchingServices returned %d",
2023 /* If a match was found, leave the loop */
2024 if (*mediaIterator
!= 0) {
2025 DPRINTF("Matching using %s\n", matching_array
[index
]);
2026 mediaType
= g_strdup(matching_array
[index
]);
2033 kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
2034 CFIndex maxPathSize
, int flags
)
2036 io_object_t nextMedia
;
2037 kern_return_t kernResult
= KERN_FAILURE
;
2039 nextMedia
= IOIteratorNext( mediaIterator
);
2042 CFTypeRef bsdPathAsCFString
;
2043 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
2044 if ( bsdPathAsCFString
) {
2045 size_t devPathLength
;
2046 strcpy( bsdPath
, _PATH_DEV
);
2047 if (flags
& BDRV_O_NOCACHE
) {
2048 strcat(bsdPath
, "r");
2050 devPathLength
= strlen( bsdPath
);
2051 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
2052 kernResult
= KERN_SUCCESS
;
2054 CFRelease( bsdPathAsCFString
);
2056 IOObjectRelease( nextMedia
);
2062 /* Sets up a real cdrom for use in QEMU */
2063 static bool setup_cdrom(char *bsd_path
, Error
**errp
)
2065 int index
, num_of_test_partitions
= 2, fd
;
2066 char test_partition
[MAXPATHLEN
];
2067 bool partition_found
= false;
2069 /* look for a working partition */
2070 for (index
= 0; index
< num_of_test_partitions
; index
++) {
2071 snprintf(test_partition
, sizeof(test_partition
), "%ss%d", bsd_path
,
2073 fd
= qemu_open(test_partition
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
2075 partition_found
= true;
2081 /* if a working partition on the device was not found */
2082 if (partition_found
== false) {
2083 error_setg(errp
, "Failed to find a working partition on disc");
2085 DPRINTF("Using %s as optical disc\n", test_partition
);
2086 pstrcpy(bsd_path
, MAXPATHLEN
, test_partition
);
2088 return partition_found
;
2091 /* Prints directions on mounting and unmounting a device */
2092 static void print_unmounting_directions(const char *file_name
)
2094 error_report("If device %s is mounted on the desktop, unmount"
2095 " it first before using it in QEMU", file_name
);
2096 error_report("Command to unmount device: diskutil unmountDisk %s",
2098 error_report("Command to mount device: diskutil mountDisk %s", file_name
);
2101 #endif /* defined(__APPLE__) && defined(__MACH__) */
2103 static int hdev_probe_device(const char *filename
)
2107 /* allow a dedicated CD-ROM driver to match with a higher priority */
2108 if (strstart(filename
, "/dev/cdrom", NULL
))
2111 if (stat(filename
, &st
) >= 0 &&
2112 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
2119 static int check_hdev_writable(BDRVRawState
*s
)
2121 #if defined(BLKROGET)
2122 /* Linux block devices can be configured "read-only" using blockdev(8).
2123 * This is independent of device node permissions and therefore open(2)
2124 * with O_RDWR succeeds. Actual writes fail with EPERM.
2126 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
2127 * check for read-only block devices so that Linux block devices behave
2133 if (fstat(s
->fd
, &st
)) {
2137 if (!S_ISBLK(st
.st_mode
)) {
2141 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
2148 #endif /* defined(BLKROGET) */
2152 static void hdev_parse_filename(const char *filename
, QDict
*options
,
2155 /* The prefix is optional, just as for "file". */
2156 strstart(filename
, "host_device:", &filename
);
2158 qdict_put_str(options
, "filename", filename
);
2161 static bool hdev_is_sg(BlockDriverState
*bs
)
2164 #if defined(__linux__)
2166 BDRVRawState
*s
= bs
->opaque
;
2168 struct sg_scsi_id scsiid
;
2172 if (stat(bs
->filename
, &st
) < 0 || !S_ISCHR(st
.st_mode
)) {
2176 ret
= ioctl(s
->fd
, SG_GET_VERSION_NUM
, &sg_version
);
2181 ret
= ioctl(s
->fd
, SG_GET_SCSI_ID
, &scsiid
);
2183 DPRINTF("SG device found: type=%d, version=%d\n",
2184 scsiid
.scsi_type
, sg_version
);
2193 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2196 BDRVRawState
*s
= bs
->opaque
;
2197 Error
*local_err
= NULL
;
2200 #if defined(__APPLE__) && defined(__MACH__)
2202 * Caution: while qdict_get_str() is fine, getting non-string types
2203 * would require more care. When @options come from -blockdev or
2204 * blockdev_add, its members are typed according to the QAPI
2205 * schema, but when they come from -drive, they're all QString.
2207 const char *filename
= qdict_get_str(options
, "filename");
2208 char bsd_path
[MAXPATHLEN
] = "";
2209 bool error_occurred
= false;
2211 /* If using a real cdrom */
2212 if (strcmp(filename
, "/dev/cdrom") == 0) {
2213 char *mediaType
= NULL
;
2214 kern_return_t ret_val
;
2215 io_iterator_t mediaIterator
= 0;
2217 mediaType
= FindEjectableOpticalMedia(&mediaIterator
);
2218 if (mediaType
== NULL
) {
2219 error_setg(errp
, "Please make sure your CD/DVD is in the optical"
2221 error_occurred
= true;
2222 goto hdev_open_Mac_error
;
2225 ret_val
= GetBSDPath(mediaIterator
, bsd_path
, sizeof(bsd_path
), flags
);
2226 if (ret_val
!= KERN_SUCCESS
) {
2227 error_setg(errp
, "Could not get BSD path for optical drive");
2228 error_occurred
= true;
2229 goto hdev_open_Mac_error
;
2232 /* If a real optical drive was not found */
2233 if (bsd_path
[0] == '\0') {
2234 error_setg(errp
, "Failed to obtain bsd path for optical drive");
2235 error_occurred
= true;
2236 goto hdev_open_Mac_error
;
2239 /* If using a cdrom disc and finding a partition on the disc failed */
2240 if (strncmp(mediaType
, kIOCDMediaClass
, 9) == 0 &&
2241 setup_cdrom(bsd_path
, errp
) == false) {
2242 print_unmounting_directions(bsd_path
);
2243 error_occurred
= true;
2244 goto hdev_open_Mac_error
;
2247 qdict_put_str(options
, "filename", bsd_path
);
2249 hdev_open_Mac_error
:
2251 if (mediaIterator
) {
2252 IOObjectRelease(mediaIterator
);
2254 if (error_occurred
) {
2258 #endif /* defined(__APPLE__) && defined(__MACH__) */
2260 s
->type
= FTYPE_FILE
;
2262 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2264 error_propagate(errp
, local_err
);
2265 #if defined(__APPLE__) && defined(__MACH__)
2267 filename
= bsd_path
;
2269 /* if a physical device experienced an error while being opened */
2270 if (strncmp(filename
, "/dev/", 5) == 0) {
2271 print_unmounting_directions(filename
);
2273 #endif /* defined(__APPLE__) && defined(__MACH__) */
2277 /* Since this does ioctl the device must be already opened */
2278 bs
->sg
= hdev_is_sg(bs
);
2280 if (flags
& BDRV_O_RDWR
) {
2281 ret
= check_hdev_writable(s
);
2284 error_setg_errno(errp
, -ret
, "The device is not writable");
2292 #if defined(__linux__)
2294 static BlockAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
2295 unsigned long int req
, void *buf
,
2296 BlockCompletionFunc
*cb
, void *opaque
)
2298 BDRVRawState
*s
= bs
->opaque
;
2299 RawPosixAIOData
*acb
;
2302 if (fd_open(bs
) < 0)
2305 acb
= g_new(RawPosixAIOData
, 1);
2307 acb
->aio_type
= QEMU_AIO_IOCTL
;
2308 acb
->aio_fildes
= s
->fd
;
2309 acb
->aio_offset
= 0;
2310 acb
->aio_ioctl_buf
= buf
;
2311 acb
->aio_ioctl_cmd
= req
;
2312 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
2313 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
2317 static int fd_open(BlockDriverState
*bs
)
2319 BDRVRawState
*s
= bs
->opaque
;
2321 /* this is just to ensure s->fd is sane (its called by io ops) */
2327 static coroutine_fn BlockAIOCB
*hdev_aio_pdiscard(BlockDriverState
*bs
,
2328 int64_t offset
, int count
,
2329 BlockCompletionFunc
*cb
, void *opaque
)
2331 BDRVRawState
*s
= bs
->opaque
;
2333 if (fd_open(bs
) < 0) {
2336 return paio_submit(bs
, s
->fd
, offset
, NULL
, count
,
2337 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2340 static coroutine_fn
int hdev_co_pwrite_zeroes(BlockDriverState
*bs
,
2341 int64_t offset
, int count
, BdrvRequestFlags flags
)
2343 BDRVRawState
*s
= bs
->opaque
;
2350 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
2351 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, count
,
2352 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
2353 } else if (s
->discard_zeroes
) {
2354 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, count
,
2355 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2360 static int hdev_create(const char *filename
, QemuOpts
*opts
,
2365 struct stat stat_buf
;
2366 int64_t total_size
= 0;
2369 /* This function is used by both protocol block drivers and therefore either
2370 * of these prefixes may be given.
2371 * The return value has to be stored somewhere, otherwise this is an error
2372 * due to -Werror=unused-value. */
2374 strstart(filename
, "host_device:", &filename
) ||
2375 strstart(filename
, "host_cdrom:" , &filename
);
2379 ret
= raw_normalize_devicepath(&filename
);
2381 error_setg_errno(errp
, -ret
, "Could not normalize device path");
2385 /* Read out options */
2386 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2389 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
2392 error_setg_errno(errp
, -ret
, "Could not open device");
2396 if (fstat(fd
, &stat_buf
) < 0) {
2398 error_setg_errno(errp
, -ret
, "Could not stat device");
2399 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
2401 "The given file is neither a block nor a character device");
2403 } else if (lseek(fd
, 0, SEEK_END
) < total_size
) {
2404 error_setg(errp
, "Device is too small");
2412 static BlockDriver bdrv_host_device
= {
2413 .format_name
= "host_device",
2414 .protocol_name
= "host_device",
2415 .instance_size
= sizeof(BDRVRawState
),
2416 .bdrv_needs_filename
= true,
2417 .bdrv_probe_device
= hdev_probe_device
,
2418 .bdrv_parse_filename
= hdev_parse_filename
,
2419 .bdrv_file_open
= hdev_open
,
2420 .bdrv_close
= raw_close
,
2421 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2422 .bdrv_reopen_commit
= raw_reopen_commit
,
2423 .bdrv_reopen_abort
= raw_reopen_abort
,
2424 .bdrv_create
= hdev_create
,
2425 .create_opts
= &raw_create_opts
,
2426 .bdrv_co_pwrite_zeroes
= hdev_co_pwrite_zeroes
,
2428 .bdrv_co_preadv
= raw_co_preadv
,
2429 .bdrv_co_pwritev
= raw_co_pwritev
,
2430 .bdrv_aio_flush
= raw_aio_flush
,
2431 .bdrv_aio_pdiscard
= hdev_aio_pdiscard
,
2432 .bdrv_refresh_limits
= raw_refresh_limits
,
2433 .bdrv_io_plug
= raw_aio_plug
,
2434 .bdrv_io_unplug
= raw_aio_unplug
,
2436 .bdrv_truncate
= raw_truncate
,
2437 .bdrv_getlength
= raw_getlength
,
2438 .bdrv_get_info
= raw_get_info
,
2439 .bdrv_get_allocated_file_size
2440 = raw_get_allocated_file_size
,
2441 .bdrv_probe_blocksizes
= hdev_probe_blocksizes
,
2442 .bdrv_probe_geometry
= hdev_probe_geometry
,
2444 /* generic scsi device */
2446 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2450 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2451 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2454 /* The prefix is optional, just as for "file". */
2455 strstart(filename
, "host_cdrom:", &filename
);
2457 qdict_put_str(options
, "filename", filename
);
2462 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2465 BDRVRawState
*s
= bs
->opaque
;
2469 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2470 return raw_open_common(bs
, options
, flags
, O_NONBLOCK
, errp
);
2473 static int cdrom_probe_device(const char *filename
)
2479 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2483 ret
= fstat(fd
, &st
);
2484 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2488 /* Attempt to detect via a CDROM specific ioctl */
2489 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2499 static bool cdrom_is_inserted(BlockDriverState
*bs
)
2501 BDRVRawState
*s
= bs
->opaque
;
2504 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2505 return ret
== CDS_DISC_OK
;
2508 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2510 BDRVRawState
*s
= bs
->opaque
;
2513 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2514 perror("CDROMEJECT");
2516 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2517 perror("CDROMEJECT");
2521 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2523 BDRVRawState
*s
= bs
->opaque
;
2525 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2527 * Note: an error can happen if the distribution automatically
2530 /* perror("CDROM_LOCKDOOR"); */
2534 static BlockDriver bdrv_host_cdrom
= {
2535 .format_name
= "host_cdrom",
2536 .protocol_name
= "host_cdrom",
2537 .instance_size
= sizeof(BDRVRawState
),
2538 .bdrv_needs_filename
= true,
2539 .bdrv_probe_device
= cdrom_probe_device
,
2540 .bdrv_parse_filename
= cdrom_parse_filename
,
2541 .bdrv_file_open
= cdrom_open
,
2542 .bdrv_close
= raw_close
,
2543 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2544 .bdrv_reopen_commit
= raw_reopen_commit
,
2545 .bdrv_reopen_abort
= raw_reopen_abort
,
2546 .bdrv_create
= hdev_create
,
2547 .create_opts
= &raw_create_opts
,
2550 .bdrv_co_preadv
= raw_co_preadv
,
2551 .bdrv_co_pwritev
= raw_co_pwritev
,
2552 .bdrv_aio_flush
= raw_aio_flush
,
2553 .bdrv_refresh_limits
= raw_refresh_limits
,
2554 .bdrv_io_plug
= raw_aio_plug
,
2555 .bdrv_io_unplug
= raw_aio_unplug
,
2557 .bdrv_truncate
= raw_truncate
,
2558 .bdrv_getlength
= raw_getlength
,
2559 .has_variable_length
= true,
2560 .bdrv_get_allocated_file_size
2561 = raw_get_allocated_file_size
,
2563 /* removable device support */
2564 .bdrv_is_inserted
= cdrom_is_inserted
,
2565 .bdrv_eject
= cdrom_eject
,
2566 .bdrv_lock_medium
= cdrom_lock_medium
,
2568 /* generic scsi device */
2569 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2571 #endif /* __linux__ */
2573 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2574 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2577 BDRVRawState
*s
= bs
->opaque
;
2578 Error
*local_err
= NULL
;
2583 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2585 error_propagate(errp
, local_err
);
2589 /* make sure the door isn't locked at this time */
2590 ioctl(s
->fd
, CDIOCALLOW
);
2594 static int cdrom_probe_device(const char *filename
)
2596 if (strstart(filename
, "/dev/cd", NULL
) ||
2597 strstart(filename
, "/dev/acd", NULL
))
2602 static int cdrom_reopen(BlockDriverState
*bs
)
2604 BDRVRawState
*s
= bs
->opaque
;
2608 * Force reread of possibly changed/newly loaded disc,
2609 * FreeBSD seems to not notice sometimes...
2613 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
2620 /* make sure the door isn't locked at this time */
2621 ioctl(s
->fd
, CDIOCALLOW
);
2625 static bool cdrom_is_inserted(BlockDriverState
*bs
)
2627 return raw_getlength(bs
) > 0;
2630 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2632 BDRVRawState
*s
= bs
->opaque
;
2637 (void) ioctl(s
->fd
, CDIOCALLOW
);
2640 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
2641 perror("CDIOCEJECT");
2643 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
2644 perror("CDIOCCLOSE");
2650 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2652 BDRVRawState
*s
= bs
->opaque
;
2656 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
2658 * Note: an error can happen if the distribution automatically
2661 /* perror("CDROM_LOCKDOOR"); */
2665 static BlockDriver bdrv_host_cdrom
= {
2666 .format_name
= "host_cdrom",
2667 .protocol_name
= "host_cdrom",
2668 .instance_size
= sizeof(BDRVRawState
),
2669 .bdrv_needs_filename
= true,
2670 .bdrv_probe_device
= cdrom_probe_device
,
2671 .bdrv_parse_filename
= cdrom_parse_filename
,
2672 .bdrv_file_open
= cdrom_open
,
2673 .bdrv_close
= raw_close
,
2674 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2675 .bdrv_reopen_commit
= raw_reopen_commit
,
2676 .bdrv_reopen_abort
= raw_reopen_abort
,
2677 .bdrv_create
= hdev_create
,
2678 .create_opts
= &raw_create_opts
,
2680 .bdrv_co_preadv
= raw_co_preadv
,
2681 .bdrv_co_pwritev
= raw_co_pwritev
,
2682 .bdrv_aio_flush
= raw_aio_flush
,
2683 .bdrv_refresh_limits
= raw_refresh_limits
,
2684 .bdrv_io_plug
= raw_aio_plug
,
2685 .bdrv_io_unplug
= raw_aio_unplug
,
2687 .bdrv_truncate
= raw_truncate
,
2688 .bdrv_getlength
= raw_getlength
,
2689 .has_variable_length
= true,
2690 .bdrv_get_allocated_file_size
2691 = raw_get_allocated_file_size
,
2693 /* removable device support */
2694 .bdrv_is_inserted
= cdrom_is_inserted
,
2695 .bdrv_eject
= cdrom_eject
,
2696 .bdrv_lock_medium
= cdrom_lock_medium
,
2698 #endif /* __FreeBSD__ */
2700 static void bdrv_file_init(void)
2703 * Register all the drivers. Note that order is important, the driver
2704 * registered last will get probed first.
2706 bdrv_register(&bdrv_file
);
2707 bdrv_register(&bdrv_host_device
);
2709 bdrv_register(&bdrv_host_cdrom
);
2711 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2712 bdrv_register(&bdrv_host_cdrom
);
2716 block_init(bdrv_file_init
);