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 "qemu/timer.h"
30 #include "block/block_int.h"
31 #include "qemu/module.h"
33 #include "block/thread-pool.h"
35 #include "block/raw-aio.h"
36 #include "qapi/util.h"
37 #include "qapi/qmp/qstring.h"
39 #if defined(__APPLE__) && (__MACH__)
41 #include <sys/param.h>
42 #include <IOKit/IOKitLib.h>
43 #include <IOKit/IOBSD.h>
44 #include <IOKit/storage/IOMediaBSDClient.h>
45 #include <IOKit/storage/IOMedia.h>
46 #include <IOKit/storage/IOCDMedia.h>
47 //#include <IOKit/storage/IOCDTypes.h>
48 #include <IOKit/storage/IODVDMedia.h>
49 #include <CoreFoundation/CoreFoundation.h>
53 #define _POSIX_PTHREAD_SEMANTICS 1
57 #include <sys/ioctl.h>
58 #include <sys/param.h>
59 #include <linux/cdrom.h>
62 #include <linux/hdreg.h>
68 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
71 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
72 #include <linux/falloc.h>
74 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
80 #include <sys/ioctl.h>
81 #include <sys/disklabel.h>
86 #include <sys/ioctl.h>
87 #include <sys/disklabel.h>
93 #include <sys/ioctl.h>
94 #include <sys/diskslice.h>
101 //#define DEBUG_BLOCK
104 # define DEBUG_BLOCK_PRINT 1
106 # define DEBUG_BLOCK_PRINT 0
108 #define DPRINTF(fmt, ...) \
110 if (DEBUG_BLOCK_PRINT) { \
111 printf(fmt, ## __VA_ARGS__); \
115 /* OS X does not have O_DSYNC */
118 #define O_DSYNC O_SYNC
119 #elif defined(O_FSYNC)
120 #define O_DSYNC O_FSYNC
124 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
126 #define O_DIRECT O_DSYNC
132 #define MAX_BLOCKSIZE 4096
134 typedef struct BDRVRawState
{
144 bool has_write_zeroes
:1;
145 bool discard_zeroes
:1;
146 bool use_linux_aio
:1;
147 bool page_cache_inconsistent
:1;
149 bool needs_alignment
;
152 typedef struct BDRVRawReopenState
{
155 } BDRVRawReopenState
;
157 static int fd_open(BlockDriverState
*bs
);
158 static int64_t raw_getlength(BlockDriverState
*bs
);
160 typedef struct RawPosixAIOData
{
161 BlockDriverState
*bs
;
164 struct iovec
*aio_iov
;
169 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
174 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
175 static int cdrom_reopen(BlockDriverState
*bs
);
178 #if defined(__NetBSD__)
179 static int raw_normalize_devicepath(const char **filename
)
181 static char namebuf
[PATH_MAX
];
182 const char *dp
, *fname
;
186 dp
= strrchr(fname
, '/');
187 if (lstat(fname
, &sb
) < 0) {
188 fprintf(stderr
, "%s: stat failed: %s\n",
189 fname
, strerror(errno
));
193 if (!S_ISBLK(sb
.st_mode
)) {
198 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
200 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
201 (int)(dp
- fname
), fname
, dp
+ 1);
203 fprintf(stderr
, "%s is a block device", fname
);
205 fprintf(stderr
, ", using %s\n", *filename
);
210 static int raw_normalize_devicepath(const char **filename
)
217 * Get logical block size via ioctl. On success store it in @sector_size_p.
219 static int probe_logical_blocksize(int fd
, unsigned int *sector_size_p
)
221 unsigned int sector_size
;
222 bool success
= false;
226 static const unsigned long ioctl_list
[] = {
230 #ifdef DKIOCGETBLOCKSIZE
233 #ifdef DIOCGSECTORSIZE
238 /* Try a few ioctls to get the right size */
239 for (i
= 0; i
< (int)ARRAY_SIZE(ioctl_list
); i
++) {
240 if (ioctl(fd
, ioctl_list
[i
], §or_size
) >= 0) {
241 *sector_size_p
= sector_size
;
246 return success
? 0 : -errno
;
250 * Get physical block size of @fd.
251 * On success, store it in @blk_size and return 0.
252 * On failure, return -errno.
254 static int probe_physical_blocksize(int fd
, unsigned int *blk_size
)
257 if (ioctl(fd
, BLKPBSZGET
, blk_size
) < 0) {
266 /* Check if read is allowed with given memory buffer and length.
268 * This function is used to check O_DIRECT memory buffer and request alignment.
270 static bool raw_is_io_aligned(int fd
, void *buf
, size_t len
)
272 ssize_t ret
= pread(fd
, buf
, len
, 0);
279 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
280 * other errors (e.g. real I/O error), which could happen on a failed
281 * drive, since we only care about probing alignment.
283 if (errno
!= EINVAL
) {
291 static void raw_probe_alignment(BlockDriverState
*bs
, int fd
, Error
**errp
)
293 BDRVRawState
*s
= bs
->opaque
;
295 size_t max_align
= MAX(MAX_BLOCKSIZE
, getpagesize());
297 /* For SCSI generic devices the alignment is not really used.
298 With buffered I/O, we don't have any restrictions. */
299 if (bdrv_is_sg(bs
) || !s
->needs_alignment
) {
300 bs
->bl
.request_alignment
= 1;
305 bs
->bl
.request_alignment
= 0;
307 /* Let's try to use the logical blocksize for the alignment. */
308 if (probe_logical_blocksize(fd
, &bs
->bl
.request_alignment
) < 0) {
309 bs
->bl
.request_alignment
= 0;
314 if (xfsctl(NULL
, fd
, XFS_IOC_DIOINFO
, &da
) >= 0) {
315 bs
->bl
.request_alignment
= da
.d_miniosz
;
316 /* The kernel returns wrong information for d_mem */
317 /* s->buf_align = da.d_mem; */
322 /* If we could not get the sizes so far, we can only guess them */
325 buf
= qemu_memalign(max_align
, 2 * max_align
);
326 for (align
= 512; align
<= max_align
; align
<<= 1) {
327 if (raw_is_io_aligned(fd
, buf
+ align
, max_align
)) {
328 s
->buf_align
= align
;
335 if (!bs
->bl
.request_alignment
) {
337 buf
= qemu_memalign(s
->buf_align
, max_align
);
338 for (align
= 512; align
<= max_align
; align
<<= 1) {
339 if (raw_is_io_aligned(fd
, buf
, align
)) {
340 bs
->bl
.request_alignment
= align
;
347 if (!s
->buf_align
|| !bs
->bl
.request_alignment
) {
348 error_setg(errp
, "Could not find working O_DIRECT alignment");
349 error_append_hint(errp
, "Try cache.direct=off\n");
353 static void raw_parse_flags(int bdrv_flags
, int *open_flags
)
355 assert(open_flags
!= NULL
);
357 *open_flags
|= O_BINARY
;
358 *open_flags
&= ~O_ACCMODE
;
359 if (bdrv_flags
& BDRV_O_RDWR
) {
360 *open_flags
|= O_RDWR
;
362 *open_flags
|= O_RDONLY
;
365 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
366 * and O_DIRECT for no caching. */
367 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
368 *open_flags
|= O_DIRECT
;
372 static void raw_parse_filename(const char *filename
, QDict
*options
,
375 /* The filename does not have to be prefixed by the protocol name, since
376 * "file" is the default protocol; therefore, the return value of this
377 * function call can be ignored. */
378 strstart(filename
, "file:", &filename
);
380 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
383 static QemuOptsList raw_runtime_opts
= {
385 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
389 .type
= QEMU_OPT_STRING
,
390 .help
= "File name of the image",
394 .type
= QEMU_OPT_STRING
,
395 .help
= "host AIO implementation (threads, native)",
397 { /* end of list */ }
401 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
402 int bdrv_flags
, int open_flags
, Error
**errp
)
404 BDRVRawState
*s
= bs
->opaque
;
406 Error
*local_err
= NULL
;
407 const char *filename
= NULL
;
408 BlockdevAioOptions aio
, aio_default
;
412 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
413 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
415 error_propagate(errp
, local_err
);
420 filename
= qemu_opt_get(opts
, "filename");
422 ret
= raw_normalize_devicepath(&filename
);
424 error_setg_errno(errp
, -ret
, "Could not normalize device path");
428 aio_default
= (bdrv_flags
& BDRV_O_NATIVE_AIO
)
429 ? BLOCKDEV_AIO_OPTIONS_NATIVE
430 : BLOCKDEV_AIO_OPTIONS_THREADS
;
431 aio
= qapi_enum_parse(BlockdevAioOptions_lookup
, qemu_opt_get(opts
, "aio"),
432 BLOCKDEV_AIO_OPTIONS__MAX
, aio_default
, &local_err
);
434 error_propagate(errp
, local_err
);
438 s
->use_linux_aio
= (aio
== BLOCKDEV_AIO_OPTIONS_NATIVE
);
440 s
->open_flags
= open_flags
;
441 raw_parse_flags(bdrv_flags
, &s
->open_flags
);
444 fd
= qemu_open(filename
, s
->open_flags
, 0644);
447 error_setg_errno(errp
, errno
, "Could not open '%s'", filename
);
455 #ifdef CONFIG_LINUX_AIO
456 /* Currently Linux does AIO only for files opened with O_DIRECT */
457 if (s
->use_linux_aio
&& !(s
->open_flags
& O_DIRECT
)) {
458 error_setg(errp
, "aio=native was specified, but it requires "
459 "cache.direct=on, which was not specified.");
464 if (s
->use_linux_aio
) {
465 error_setg(errp
, "aio=native was specified, but is not supported "
470 #endif /* !defined(CONFIG_LINUX_AIO) */
472 s
->has_discard
= true;
473 s
->has_write_zeroes
= true;
474 bs
->supported_zero_flags
= BDRV_REQ_MAY_UNMAP
;
475 if ((bs
->open_flags
& BDRV_O_NOCACHE
) != 0) {
476 s
->needs_alignment
= true;
479 if (fstat(s
->fd
, &st
) < 0) {
481 error_setg_errno(errp
, errno
, "Could not stat file");
484 if (S_ISREG(st
.st_mode
)) {
485 s
->discard_zeroes
= true;
486 s
->has_fallocate
= true;
488 if (S_ISBLK(st
.st_mode
)) {
489 #ifdef BLKDISCARDZEROES
491 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
492 s
->discard_zeroes
= true;
496 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
497 * not rely on the contents of discarded blocks unless using O_DIRECT.
498 * Same for BLKZEROOUT.
500 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
501 s
->discard_zeroes
= false;
502 s
->has_write_zeroes
= false;
507 if (S_ISCHR(st
.st_mode
)) {
509 * The file is a char device (disk), which on FreeBSD isn't behind
510 * a pager, so force all requests to be aligned. This is needed
511 * so QEMU makes sure all IO operations on the device are aligned
512 * to sector size, or else FreeBSD will reject them with EINVAL.
514 s
->needs_alignment
= true;
519 if (platform_test_xfs_fd(s
->fd
)) {
526 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
533 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
536 BDRVRawState
*s
= bs
->opaque
;
538 s
->type
= FTYPE_FILE
;
539 return raw_open_common(bs
, options
, flags
, 0, errp
);
542 static int raw_reopen_prepare(BDRVReopenState
*state
,
543 BlockReopenQueue
*queue
, Error
**errp
)
546 BDRVRawReopenState
*rs
;
548 Error
*local_err
= NULL
;
550 assert(state
!= NULL
);
551 assert(state
->bs
!= NULL
);
553 s
= state
->bs
->opaque
;
555 state
->opaque
= g_new0(BDRVRawReopenState
, 1);
558 if (s
->type
== FTYPE_CD
) {
559 rs
->open_flags
|= O_NONBLOCK
;
562 raw_parse_flags(state
->flags
, &rs
->open_flags
);
566 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
568 fcntl_flags
|= O_NOATIME
;
572 /* Not all operating systems have O_ASYNC, and those that don't
573 * will not let us track the state into rs->open_flags (typically
574 * you achieve the same effect with an ioctl, for example I_SETSIG
575 * on Solaris). But we do not use O_ASYNC, so that's fine.
577 assert((s
->open_flags
& O_ASYNC
) == 0);
580 if ((rs
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
581 /* dup the original fd */
582 rs
->fd
= qemu_dup(s
->fd
);
584 ret
= fcntl_setfl(rs
->fd
, rs
->open_flags
);
592 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
594 const char *normalized_filename
= state
->bs
->filename
;
595 ret
= raw_normalize_devicepath(&normalized_filename
);
597 error_setg_errno(errp
, -ret
, "Could not normalize device path");
599 assert(!(rs
->open_flags
& O_CREAT
));
600 rs
->fd
= qemu_open(normalized_filename
, rs
->open_flags
);
602 error_setg_errno(errp
, errno
, "Could not reopen file");
608 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
609 * alignment with the new fd. */
611 raw_probe_alignment(state
->bs
, rs
->fd
, &local_err
);
615 error_propagate(errp
, local_err
);
623 static void raw_reopen_commit(BDRVReopenState
*state
)
625 BDRVRawReopenState
*rs
= state
->opaque
;
626 BDRVRawState
*s
= state
->bs
->opaque
;
628 s
->open_flags
= rs
->open_flags
;
633 g_free(state
->opaque
);
634 state
->opaque
= NULL
;
638 static void raw_reopen_abort(BDRVReopenState
*state
)
640 BDRVRawReopenState
*rs
= state
->opaque
;
642 /* nothing to do if NULL, we didn't get far enough */
651 g_free(state
->opaque
);
652 state
->opaque
= NULL
;
655 static int hdev_get_max_transfer_length(BlockDriverState
*bs
, int fd
)
659 short max_sectors
= 0;
660 if (bs
->sg
&& ioctl(fd
, BLKSECTGET
, &max_bytes
) == 0) {
662 } else if (!bs
->sg
&& ioctl(fd
, BLKSECTGET
, &max_sectors
) == 0) {
663 return max_sectors
<< BDRV_SECTOR_BITS
;
672 static int hdev_get_max_segments(const struct stat
*st
)
682 sysfspath
= g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
683 major(st
->st_rdev
), minor(st
->st_rdev
));
684 fd
= open(sysfspath
, O_RDONLY
);
690 ret
= read(fd
, buf
, sizeof(buf
) - 1);
691 } while (ret
== -1 && errno
== EINTR
);
695 } else if (ret
== 0) {
700 /* The file is ended with '\n', pass 'end' to accept that. */
701 ret
= qemu_strtol(buf
, &end
, 10, &max_segments
);
702 if (ret
== 0 && end
&& *end
== '\n') {
717 static void raw_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
719 BDRVRawState
*s
= bs
->opaque
;
722 if (!fstat(s
->fd
, &st
)) {
723 if (S_ISBLK(st
.st_mode
) || S_ISCHR(st
.st_mode
)) {
724 int ret
= hdev_get_max_transfer_length(bs
, s
->fd
);
725 if (ret
> 0 && ret
<= BDRV_REQUEST_MAX_BYTES
) {
726 bs
->bl
.max_transfer
= pow2floor(ret
);
728 ret
= hdev_get_max_segments(&st
);
730 bs
->bl
.max_transfer
= MIN(bs
->bl
.max_transfer
,
731 ret
* getpagesize());
736 raw_probe_alignment(bs
, s
->fd
, errp
);
737 bs
->bl
.min_mem_alignment
= s
->buf_align
;
738 bs
->bl
.opt_mem_alignment
= MAX(s
->buf_align
, getpagesize());
741 static int check_for_dasd(int fd
)
744 struct dasd_information2_t info
= {0};
746 return ioctl(fd
, BIODASDINFO2
, &info
);
753 * Try to get @bs's logical and physical block size.
754 * On success, store them in @bsz and return zero.
755 * On failure, return negative errno.
757 static int hdev_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
759 BDRVRawState
*s
= bs
->opaque
;
762 /* If DASD, get blocksizes */
763 if (check_for_dasd(s
->fd
) < 0) {
766 ret
= probe_logical_blocksize(s
->fd
, &bsz
->log
);
770 return probe_physical_blocksize(s
->fd
, &bsz
->phys
);
774 * Try to get @bs's geometry: cyls, heads, sectors.
775 * On success, store them in @geo and return 0.
776 * On failure return -errno.
777 * (Allows block driver to assign default geometry values that guest sees)
780 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
782 BDRVRawState
*s
= bs
->opaque
;
783 struct hd_geometry ioctl_geo
= {0};
785 /* If DASD, get its geometry */
786 if (check_for_dasd(s
->fd
) < 0) {
789 if (ioctl(s
->fd
, HDIO_GETGEO
, &ioctl_geo
) < 0) {
792 /* HDIO_GETGEO may return success even though geo contains zeros
793 (e.g. certain multipath setups) */
794 if (!ioctl_geo
.heads
|| !ioctl_geo
.sectors
|| !ioctl_geo
.cylinders
) {
797 /* Do not return a geometry for partition */
798 if (ioctl_geo
.start
!= 0) {
801 geo
->heads
= ioctl_geo
.heads
;
802 geo
->sectors
= ioctl_geo
.sectors
;
803 geo
->cylinders
= ioctl_geo
.cylinders
;
807 #else /* __linux__ */
808 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
814 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
818 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
826 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
828 BDRVRawState
*s
= aiocb
->bs
->opaque
;
831 if (s
->page_cache_inconsistent
) {
835 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
837 /* There is no clear definition of the semantics of a failing fsync(),
838 * so we may have to assume the worst. The sad truth is that this
839 * assumption is correct for Linux. Some pages are now probably marked
840 * clean in the page cache even though they are inconsistent with the
841 * on-disk contents. The next fdatasync() call would succeed, but no
842 * further writeback attempt will be made. We can't get back to a state
843 * in which we know what is on disk (we would have to rewrite
844 * everything that was touched since the last fdatasync() at least), so
845 * make bdrv_flush() fail permanently. Given that the behaviour isn't
846 * really defined, I have little hope that other OSes are doing better.
848 * Obviously, this doesn't affect O_DIRECT, which bypasses the page
850 if ((s
->open_flags
& O_DIRECT
) == 0) {
851 s
->page_cache_inconsistent
= true;
860 static bool preadv_present
= true;
863 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
865 return preadv(fd
, iov
, nr_iov
, offset
);
869 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
871 return pwritev(fd
, iov
, nr_iov
, offset
);
876 static bool preadv_present
= false;
879 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
885 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
892 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
897 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
898 len
= qemu_pwritev(aiocb
->aio_fildes
,
903 len
= qemu_preadv(aiocb
->aio_fildes
,
907 } while (len
== -1 && errno
== EINTR
);
916 * Read/writes the data to/from a given linear buffer.
918 * Returns the number of bytes handles or -errno in case of an error. Short
919 * reads are only returned if the end of the file is reached.
921 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
926 while (offset
< aiocb
->aio_nbytes
) {
927 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
928 len
= pwrite(aiocb
->aio_fildes
,
929 (const char *)buf
+ offset
,
930 aiocb
->aio_nbytes
- offset
,
931 aiocb
->aio_offset
+ offset
);
933 len
= pread(aiocb
->aio_fildes
,
935 aiocb
->aio_nbytes
- offset
,
936 aiocb
->aio_offset
+ offset
);
938 if (len
== -1 && errno
== EINTR
) {
940 } else if (len
== -1 && errno
== EINVAL
&&
941 (aiocb
->bs
->open_flags
& BDRV_O_NOCACHE
) &&
942 !(aiocb
->aio_type
& QEMU_AIO_WRITE
) &&
944 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
945 * after a short read. Assume that O_DIRECT short reads only occur
946 * at EOF. Therefore this is a short read, not an I/O error.
949 } else if (len
== -1) {
952 } else if (len
== 0) {
961 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
966 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
968 * If there is just a single buffer, and it is properly aligned
969 * we can just use plain pread/pwrite without any problems.
971 if (aiocb
->aio_niov
== 1) {
972 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
975 * We have more than one iovec, and all are properly aligned.
977 * Try preadv/pwritev first and fall back to linearizing the
978 * buffer if it's not supported.
980 if (preadv_present
) {
981 nbytes
= handle_aiocb_rw_vector(aiocb
);
982 if (nbytes
== aiocb
->aio_nbytes
||
983 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
986 preadv_present
= false;
990 * XXX(hch): short read/write. no easy way to handle the reminder
991 * using these interfaces. For now retry using plain
997 * Ok, we have to do it the hard way, copy all segments into
998 * a single aligned buffer.
1000 buf
= qemu_try_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
1005 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1009 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
1010 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
1011 p
+= aiocb
->aio_iov
[i
].iov_len
;
1013 assert(p
- buf
== aiocb
->aio_nbytes
);
1016 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
1017 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
1019 size_t count
= aiocb
->aio_nbytes
, copy
;
1022 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
1024 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
1025 copy
= aiocb
->aio_iov
[i
].iov_len
;
1027 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
1028 assert(count
>= copy
);
1040 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1042 struct xfs_flock64 fl
;
1045 memset(&fl
, 0, sizeof(fl
));
1046 fl
.l_whence
= SEEK_SET
;
1047 fl
.l_start
= offset
;
1050 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
1052 DPRINTF("cannot write zero range (%s)\n", strerror(errno
));
1059 static int xfs_discard(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1061 struct xfs_flock64 fl
;
1064 memset(&fl
, 0, sizeof(fl
));
1065 fl
.l_whence
= SEEK_SET
;
1066 fl
.l_start
= offset
;
1069 if (xfsctl(NULL
, s
->fd
, XFS_IOC_UNRESVSP64
, &fl
) < 0) {
1071 DPRINTF("cannot punch hole (%s)\n", strerror(errno
));
1079 static int translate_err(int err
)
1081 if (err
== -ENODEV
|| err
== -ENOSYS
|| err
== -EOPNOTSUPP
||
1088 #ifdef CONFIG_FALLOCATE
1089 static int do_fallocate(int fd
, int mode
, off_t offset
, off_t len
)
1092 if (fallocate(fd
, mode
, offset
, len
) == 0) {
1095 } while (errno
== EINTR
);
1096 return translate_err(-errno
);
1100 static ssize_t
handle_aiocb_write_zeroes_block(RawPosixAIOData
*aiocb
)
1103 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1105 if (!s
->has_write_zeroes
) {
1111 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1112 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
1115 } while (errno
== EINTR
);
1117 ret
= translate_err(-errno
);
1120 if (ret
== -ENOTSUP
) {
1121 s
->has_write_zeroes
= false;
1126 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
1128 #if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1129 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1132 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1133 return handle_aiocb_write_zeroes_block(aiocb
);
1138 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1142 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1143 if (s
->has_write_zeroes
) {
1144 int ret
= do_fallocate(s
->fd
, FALLOC_FL_ZERO_RANGE
,
1145 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1146 if (ret
== 0 || ret
!= -ENOTSUP
) {
1149 s
->has_write_zeroes
= false;
1153 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1154 if (s
->has_discard
&& s
->has_fallocate
) {
1155 int ret
= do_fallocate(s
->fd
,
1156 FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1157 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1159 ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1160 if (ret
== 0 || ret
!= -ENOTSUP
) {
1163 s
->has_fallocate
= false;
1164 } else if (ret
!= -ENOTSUP
) {
1167 s
->has_discard
= false;
1172 #ifdef CONFIG_FALLOCATE
1173 if (s
->has_fallocate
&& aiocb
->aio_offset
>= bdrv_getlength(aiocb
->bs
)) {
1174 int ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1175 if (ret
== 0 || ret
!= -ENOTSUP
) {
1178 s
->has_fallocate
= false;
1185 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
1187 int ret
= -EOPNOTSUPP
;
1188 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1190 if (!s
->has_discard
) {
1194 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1197 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1198 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
1201 } while (errno
== EINTR
);
1208 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1212 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1213 ret
= do_fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1214 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1218 ret
= translate_err(ret
);
1219 if (ret
== -ENOTSUP
) {
1220 s
->has_discard
= false;
1225 static int aio_worker(void *arg
)
1227 RawPosixAIOData
*aiocb
= arg
;
1230 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
1232 ret
= handle_aiocb_rw(aiocb
);
1233 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1234 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
1235 0, aiocb
->aio_nbytes
- ret
);
1237 ret
= aiocb
->aio_nbytes
;
1239 if (ret
== aiocb
->aio_nbytes
) {
1241 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1245 case QEMU_AIO_WRITE
:
1246 ret
= handle_aiocb_rw(aiocb
);
1247 if (ret
== aiocb
->aio_nbytes
) {
1249 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1253 case QEMU_AIO_FLUSH
:
1254 ret
= handle_aiocb_flush(aiocb
);
1256 case QEMU_AIO_IOCTL
:
1257 ret
= handle_aiocb_ioctl(aiocb
);
1259 case QEMU_AIO_DISCARD
:
1260 ret
= handle_aiocb_discard(aiocb
);
1262 case QEMU_AIO_WRITE_ZEROES
:
1263 ret
= handle_aiocb_write_zeroes(aiocb
);
1266 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
1275 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
1276 int64_t offset
, QEMUIOVector
*qiov
,
1277 int count
, int type
)
1279 RawPosixAIOData
*acb
= g_new(RawPosixAIOData
, 1);
1283 acb
->aio_type
= type
;
1284 acb
->aio_fildes
= fd
;
1286 acb
->aio_nbytes
= count
;
1287 acb
->aio_offset
= offset
;
1290 acb
->aio_iov
= qiov
->iov
;
1291 acb
->aio_niov
= qiov
->niov
;
1292 assert(qiov
->size
== count
);
1295 trace_paio_submit_co(offset
, count
, type
);
1296 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1297 return thread_pool_submit_co(pool
, aio_worker
, acb
);
1300 static BlockAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
1301 int64_t offset
, QEMUIOVector
*qiov
, int count
,
1302 BlockCompletionFunc
*cb
, void *opaque
, int type
)
1304 RawPosixAIOData
*acb
= g_new(RawPosixAIOData
, 1);
1308 acb
->aio_type
= type
;
1309 acb
->aio_fildes
= fd
;
1311 acb
->aio_nbytes
= count
;
1312 acb
->aio_offset
= offset
;
1315 acb
->aio_iov
= qiov
->iov
;
1316 acb
->aio_niov
= qiov
->niov
;
1317 assert(qiov
->size
== acb
->aio_nbytes
);
1320 trace_paio_submit(acb
, opaque
, offset
, count
, type
);
1321 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1322 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1325 static int coroutine_fn
raw_co_prw(BlockDriverState
*bs
, uint64_t offset
,
1326 uint64_t bytes
, QEMUIOVector
*qiov
, int type
)
1328 BDRVRawState
*s
= bs
->opaque
;
1330 if (fd_open(bs
) < 0)
1334 * Check if the underlying device requires requests to be aligned,
1335 * and if the request we are trying to submit is aligned or not.
1336 * If this is the case tell the low-level driver that it needs
1337 * to copy the buffer.
1339 if (s
->needs_alignment
) {
1340 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1341 type
|= QEMU_AIO_MISALIGNED
;
1342 #ifdef CONFIG_LINUX_AIO
1343 } else if (s
->use_linux_aio
) {
1344 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1345 assert(qiov
->size
== bytes
);
1346 return laio_co_submit(bs
, aio
, s
->fd
, offset
, qiov
, type
);
1351 return paio_submit_co(bs
, s
->fd
, offset
, qiov
, bytes
, type
);
1354 static int coroutine_fn
raw_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1355 uint64_t bytes
, QEMUIOVector
*qiov
,
1358 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_READ
);
1361 static int coroutine_fn
raw_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1362 uint64_t bytes
, QEMUIOVector
*qiov
,
1366 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_WRITE
);
1369 static void raw_aio_plug(BlockDriverState
*bs
)
1371 #ifdef CONFIG_LINUX_AIO
1372 BDRVRawState
*s
= bs
->opaque
;
1373 if (s
->use_linux_aio
) {
1374 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1375 laio_io_plug(bs
, aio
);
1380 static void raw_aio_unplug(BlockDriverState
*bs
)
1382 #ifdef CONFIG_LINUX_AIO
1383 BDRVRawState
*s
= bs
->opaque
;
1384 if (s
->use_linux_aio
) {
1385 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1386 laio_io_unplug(bs
, aio
);
1391 static BlockAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1392 BlockCompletionFunc
*cb
, void *opaque
)
1394 BDRVRawState
*s
= bs
->opaque
;
1396 if (fd_open(bs
) < 0)
1399 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1402 static void raw_close(BlockDriverState
*bs
)
1404 BDRVRawState
*s
= bs
->opaque
;
1412 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
1414 BDRVRawState
*s
= bs
->opaque
;
1417 if (fstat(s
->fd
, &st
)) {
1421 if (S_ISREG(st
.st_mode
)) {
1422 if (ftruncate(s
->fd
, offset
) < 0) {
1425 } else if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1426 if (offset
> raw_getlength(bs
)) {
1437 static int64_t raw_getlength(BlockDriverState
*bs
)
1439 BDRVRawState
*s
= bs
->opaque
;
1445 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1446 struct disklabel dl
;
1448 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1450 return (uint64_t)dl
.d_secsize
*
1451 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1455 #elif defined(__NetBSD__)
1456 static int64_t raw_getlength(BlockDriverState
*bs
)
1458 BDRVRawState
*s
= bs
->opaque
;
1464 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1465 struct dkwedge_info dkw
;
1467 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1468 return dkw
.dkw_size
* 512;
1470 struct disklabel dl
;
1472 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1474 return (uint64_t)dl
.d_secsize
*
1475 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1480 #elif defined(__sun__)
1481 static int64_t raw_getlength(BlockDriverState
*bs
)
1483 BDRVRawState
*s
= bs
->opaque
;
1484 struct dk_minfo minfo
;
1494 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1496 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1498 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1502 * There are reports that lseek on some devices fails, but
1503 * irc discussion said that contingency on contingency was overkill.
1505 size
= lseek(s
->fd
, 0, SEEK_END
);
1511 #elif defined(CONFIG_BSD)
1512 static int64_t raw_getlength(BlockDriverState
*bs
)
1514 BDRVRawState
*s
= bs
->opaque
;
1518 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1527 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1530 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1531 #ifdef DIOCGMEDIASIZE
1532 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1533 #elif defined(DIOCGPART)
1536 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1537 size
= pi
.media_size
;
1543 #if defined(__APPLE__) && defined(__MACH__)
1545 uint64_t sectors
= 0;
1546 uint32_t sector_size
= 0;
1548 if (ioctl(fd
, DKIOCGETBLOCKCOUNT
, §ors
) == 0
1549 && ioctl(fd
, DKIOCGETBLOCKSIZE
, §or_size
) == 0) {
1550 size
= sectors
* sector_size
;
1552 size
= lseek(fd
, 0LL, SEEK_END
);
1559 size
= lseek(fd
, 0LL, SEEK_END
);
1564 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1567 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1568 if (size
== 2048LL * (unsigned)-1)
1570 /* XXX no disc? maybe we need to reopen... */
1571 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1578 size
= lseek(fd
, 0, SEEK_END
);
1586 static int64_t raw_getlength(BlockDriverState
*bs
)
1588 BDRVRawState
*s
= bs
->opaque
;
1597 size
= lseek(s
->fd
, 0, SEEK_END
);
1605 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
1608 BDRVRawState
*s
= bs
->opaque
;
1610 if (fstat(s
->fd
, &st
) < 0) {
1613 return (int64_t)st
.st_blocks
* 512;
1616 static int raw_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1620 int64_t total_size
= 0;
1622 PreallocMode prealloc
;
1624 Error
*local_err
= NULL
;
1626 strstart(filename
, "file:", &filename
);
1628 /* Read out options */
1629 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1631 nocow
= qemu_opt_get_bool(opts
, BLOCK_OPT_NOCOW
, false);
1632 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
1633 prealloc
= qapi_enum_parse(PreallocMode_lookup
, buf
,
1634 PREALLOC_MODE__MAX
, PREALLOC_MODE_OFF
,
1638 error_propagate(errp
, local_err
);
1643 fd
= qemu_open(filename
, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
,
1647 error_setg_errno(errp
, -result
, "Could not create file");
1653 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1654 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1655 * will be ignored since any failure of this operation should not
1656 * block the left work.
1659 if (ioctl(fd
, FS_IOC_GETFLAGS
, &attr
) == 0) {
1660 attr
|= FS_NOCOW_FL
;
1661 ioctl(fd
, FS_IOC_SETFLAGS
, &attr
);
1667 #ifdef CONFIG_POSIX_FALLOCATE
1668 case PREALLOC_MODE_FALLOC
:
1670 * Truncating before posix_fallocate() makes it about twice slower on
1671 * file systems that do not support fallocate(), trying to check if a
1672 * block is allocated before allocating it, so don't do that here.
1674 result
= -posix_fallocate(fd
, 0, total_size
);
1676 /* posix_fallocate() doesn't set errno. */
1677 error_setg_errno(errp
, -result
,
1678 "Could not preallocate data for the new file");
1682 case PREALLOC_MODE_FULL
:
1685 * Knowing the final size from the beginning could allow the file
1686 * system driver to do less allocations and possibly avoid
1687 * fragmentation of the file.
1689 if (ftruncate(fd
, total_size
) != 0) {
1691 error_setg_errno(errp
, -result
, "Could not resize file");
1695 int64_t num
= 0, left
= total_size
;
1696 buf
= g_malloc0(65536);
1699 num
= MIN(left
, 65536);
1700 result
= write(fd
, buf
, num
);
1703 error_setg_errno(errp
, -result
,
1704 "Could not write to the new file");
1713 error_setg_errno(errp
, -result
,
1714 "Could not flush new file to disk");
1720 case PREALLOC_MODE_OFF
:
1721 if (ftruncate(fd
, total_size
) != 0) {
1723 error_setg_errno(errp
, -result
, "Could not resize file");
1728 error_setg(errp
, "Unsupported preallocation mode: %s",
1729 PreallocMode_lookup
[prealloc
]);
1734 if (qemu_close(fd
) != 0 && result
== 0) {
1736 error_setg_errno(errp
, -result
, "Could not close the new file");
1743 * Find allocation range in @bs around offset @start.
1744 * May change underlying file descriptor's file offset.
1745 * If @start is not in a hole, store @start in @data, and the
1746 * beginning of the next hole in @hole, and return 0.
1747 * If @start is in a non-trailing hole, store @start in @hole and the
1748 * beginning of the next non-hole in @data, and return 0.
1749 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1750 * If we can't find out, return a negative errno other than -ENXIO.
1752 static int find_allocation(BlockDriverState
*bs
, off_t start
,
1753 off_t
*data
, off_t
*hole
)
1755 #if defined SEEK_HOLE && defined SEEK_DATA
1756 BDRVRawState
*s
= bs
->opaque
;
1761 * D1. offs == start: start is in data
1762 * D2. offs > start: start is in a hole, next data at offs
1763 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1764 * or start is beyond EOF
1765 * If the latter happens, the file has been truncated behind
1766 * our back since we opened it. All bets are off then.
1767 * Treating like a trailing hole is simplest.
1768 * D4. offs < 0, errno != ENXIO: we learned nothing
1770 offs
= lseek(s
->fd
, start
, SEEK_DATA
);
1772 return -errno
; /* D3 or D4 */
1774 assert(offs
>= start
);
1777 /* D2: in hole, next data at offs */
1783 /* D1: in data, end not yet known */
1787 * H1. offs == start: start is in a hole
1788 * If this happens here, a hole has been dug behind our back
1789 * since the previous lseek().
1790 * H2. offs > start: either start is in data, next hole at offs,
1791 * or start is in trailing hole, EOF at offs
1792 * Linux treats trailing holes like any other hole: offs ==
1793 * start. Solaris seeks to EOF instead: offs > start (blech).
1794 * If that happens here, a hole has been dug behind our back
1795 * since the previous lseek().
1796 * H3. offs < 0, errno = ENXIO: start is beyond EOF
1797 * If this happens, the file has been truncated behind our
1798 * back since we opened it. Treat it like a trailing hole.
1799 * H4. offs < 0, errno != ENXIO: we learned nothing
1800 * Pretend we know nothing at all, i.e. "forget" about D1.
1802 offs
= lseek(s
->fd
, start
, SEEK_HOLE
);
1804 return -errno
; /* D1 and (H3 or H4) */
1806 assert(offs
>= start
);
1810 * D1 and H2: either in data, next hole at offs, or it was in
1811 * data but is now in a trailing hole. In the latter case,
1812 * all bets are off. Treating it as if it there was data all
1813 * the way to EOF is safe, so simply do that.
1828 * Returns the allocation status of the specified sectors.
1830 * If 'sector_num' is beyond the end of the disk image the return value is 0
1831 * and 'pnum' is set to 0.
1833 * 'pnum' is set to the number of sectors (including and immediately following
1834 * the specified sector) that are known to be in the same
1835 * allocated/unallocated state.
1837 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1838 * beyond the end of the disk image it will be clamped.
1840 static int64_t coroutine_fn
raw_co_get_block_status(BlockDriverState
*bs
,
1842 int nb_sectors
, int *pnum
,
1843 BlockDriverState
**file
)
1845 off_t start
, data
= 0, hole
= 0;
1854 start
= sector_num
* BDRV_SECTOR_SIZE
;
1855 total_size
= bdrv_getlength(bs
);
1856 if (total_size
< 0) {
1858 } else if (start
>= total_size
) {
1861 } else if (start
+ nb_sectors
* BDRV_SECTOR_SIZE
> total_size
) {
1862 nb_sectors
= DIV_ROUND_UP(total_size
- start
, BDRV_SECTOR_SIZE
);
1865 ret
= find_allocation(bs
, start
, &data
, &hole
);
1866 if (ret
== -ENXIO
) {
1869 ret
= BDRV_BLOCK_ZERO
;
1870 } else if (ret
< 0) {
1871 /* No info available, so pretend there are no holes */
1873 ret
= BDRV_BLOCK_DATA
;
1874 } else if (data
== start
) {
1875 /* On a data extent, compute sectors to the end of the extent,
1876 * possibly including a partial sector at EOF. */
1877 *pnum
= MIN(nb_sectors
, DIV_ROUND_UP(hole
- start
, BDRV_SECTOR_SIZE
));
1878 ret
= BDRV_BLOCK_DATA
;
1880 /* On a hole, compute sectors to the beginning of the next extent. */
1881 assert(hole
== start
);
1882 *pnum
= MIN(nb_sectors
, (data
- start
) / BDRV_SECTOR_SIZE
);
1883 ret
= BDRV_BLOCK_ZERO
;
1886 return ret
| BDRV_BLOCK_OFFSET_VALID
| start
;
1889 static coroutine_fn BlockAIOCB
*raw_aio_pdiscard(BlockDriverState
*bs
,
1890 int64_t offset
, int count
,
1891 BlockCompletionFunc
*cb
, void *opaque
)
1893 BDRVRawState
*s
= bs
->opaque
;
1895 return paio_submit(bs
, s
->fd
, offset
, NULL
, count
,
1896 cb
, opaque
, QEMU_AIO_DISCARD
);
1899 static int coroutine_fn
raw_co_pwrite_zeroes(
1900 BlockDriverState
*bs
, int64_t offset
,
1901 int count
, BdrvRequestFlags flags
)
1903 BDRVRawState
*s
= bs
->opaque
;
1905 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1906 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, count
,
1907 QEMU_AIO_WRITE_ZEROES
);
1908 } else if (s
->discard_zeroes
) {
1909 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, count
,
1915 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1917 BDRVRawState
*s
= bs
->opaque
;
1919 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
1920 bdi
->can_write_zeroes_with_unmap
= s
->discard_zeroes
;
1924 static QemuOptsList raw_create_opts
= {
1925 .name
= "raw-create-opts",
1926 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
1929 .name
= BLOCK_OPT_SIZE
,
1930 .type
= QEMU_OPT_SIZE
,
1931 .help
= "Virtual disk size"
1934 .name
= BLOCK_OPT_NOCOW
,
1935 .type
= QEMU_OPT_BOOL
,
1936 .help
= "Turn off copy-on-write (valid only on btrfs)"
1939 .name
= BLOCK_OPT_PREALLOC
,
1940 .type
= QEMU_OPT_STRING
,
1941 .help
= "Preallocation mode (allowed values: off, falloc, full)"
1943 { /* end of list */ }
1947 BlockDriver bdrv_file
= {
1948 .format_name
= "file",
1949 .protocol_name
= "file",
1950 .instance_size
= sizeof(BDRVRawState
),
1951 .bdrv_needs_filename
= true,
1952 .bdrv_probe
= NULL
, /* no probe for protocols */
1953 .bdrv_parse_filename
= raw_parse_filename
,
1954 .bdrv_file_open
= raw_open
,
1955 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1956 .bdrv_reopen_commit
= raw_reopen_commit
,
1957 .bdrv_reopen_abort
= raw_reopen_abort
,
1958 .bdrv_close
= raw_close
,
1959 .bdrv_create
= raw_create
,
1960 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
1961 .bdrv_co_get_block_status
= raw_co_get_block_status
,
1962 .bdrv_co_pwrite_zeroes
= raw_co_pwrite_zeroes
,
1964 .bdrv_co_preadv
= raw_co_preadv
,
1965 .bdrv_co_pwritev
= raw_co_pwritev
,
1966 .bdrv_aio_flush
= raw_aio_flush
,
1967 .bdrv_aio_pdiscard
= raw_aio_pdiscard
,
1968 .bdrv_refresh_limits
= raw_refresh_limits
,
1969 .bdrv_io_plug
= raw_aio_plug
,
1970 .bdrv_io_unplug
= raw_aio_unplug
,
1972 .bdrv_truncate
= raw_truncate
,
1973 .bdrv_getlength
= raw_getlength
,
1974 .bdrv_get_info
= raw_get_info
,
1975 .bdrv_get_allocated_file_size
1976 = raw_get_allocated_file_size
,
1978 .create_opts
= &raw_create_opts
,
1981 /***********************************************/
1984 #if defined(__APPLE__) && defined(__MACH__)
1985 static kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
1986 CFIndex maxPathSize
, int flags
);
1987 static char *FindEjectableOpticalMedia(io_iterator_t
*mediaIterator
)
1989 kern_return_t kernResult
= KERN_FAILURE
;
1990 mach_port_t masterPort
;
1991 CFMutableDictionaryRef classesToMatch
;
1992 const char *matching_array
[] = {kIODVDMediaClass
, kIOCDMediaClass
};
1993 char *mediaType
= NULL
;
1995 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
1996 if ( KERN_SUCCESS
!= kernResult
) {
1997 printf( "IOMasterPort returned %d\n", kernResult
);
2001 for (index
= 0; index
< ARRAY_SIZE(matching_array
); index
++) {
2002 classesToMatch
= IOServiceMatching(matching_array
[index
]);
2003 if (classesToMatch
== NULL
) {
2004 error_report("IOServiceMatching returned NULL for %s",
2005 matching_array
[index
]);
2008 CFDictionarySetValue(classesToMatch
, CFSTR(kIOMediaEjectableKey
),
2010 kernResult
= IOServiceGetMatchingServices(masterPort
, classesToMatch
,
2012 if (kernResult
!= KERN_SUCCESS
) {
2013 error_report("Note: IOServiceGetMatchingServices returned %d",
2018 /* If a match was found, leave the loop */
2019 if (*mediaIterator
!= 0) {
2020 DPRINTF("Matching using %s\n", matching_array
[index
]);
2021 mediaType
= g_strdup(matching_array
[index
]);
2028 kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
2029 CFIndex maxPathSize
, int flags
)
2031 io_object_t nextMedia
;
2032 kern_return_t kernResult
= KERN_FAILURE
;
2034 nextMedia
= IOIteratorNext( mediaIterator
);
2037 CFTypeRef bsdPathAsCFString
;
2038 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
2039 if ( bsdPathAsCFString
) {
2040 size_t devPathLength
;
2041 strcpy( bsdPath
, _PATH_DEV
);
2042 if (flags
& BDRV_O_NOCACHE
) {
2043 strcat(bsdPath
, "r");
2045 devPathLength
= strlen( bsdPath
);
2046 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
2047 kernResult
= KERN_SUCCESS
;
2049 CFRelease( bsdPathAsCFString
);
2051 IOObjectRelease( nextMedia
);
2057 /* Sets up a real cdrom for use in QEMU */
2058 static bool setup_cdrom(char *bsd_path
, Error
**errp
)
2060 int index
, num_of_test_partitions
= 2, fd
;
2061 char test_partition
[MAXPATHLEN
];
2062 bool partition_found
= false;
2064 /* look for a working partition */
2065 for (index
= 0; index
< num_of_test_partitions
; index
++) {
2066 snprintf(test_partition
, sizeof(test_partition
), "%ss%d", bsd_path
,
2068 fd
= qemu_open(test_partition
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
2070 partition_found
= true;
2076 /* if a working partition on the device was not found */
2077 if (partition_found
== false) {
2078 error_setg(errp
, "Failed to find a working partition on disc");
2080 DPRINTF("Using %s as optical disc\n", test_partition
);
2081 pstrcpy(bsd_path
, MAXPATHLEN
, test_partition
);
2083 return partition_found
;
2086 /* Prints directions on mounting and unmounting a device */
2087 static void print_unmounting_directions(const char *file_name
)
2089 error_report("If device %s is mounted on the desktop, unmount"
2090 " it first before using it in QEMU", file_name
);
2091 error_report("Command to unmount device: diskutil unmountDisk %s",
2093 error_report("Command to mount device: diskutil mountDisk %s", file_name
);
2096 #endif /* defined(__APPLE__) && defined(__MACH__) */
2098 static int hdev_probe_device(const char *filename
)
2102 /* allow a dedicated CD-ROM driver to match with a higher priority */
2103 if (strstart(filename
, "/dev/cdrom", NULL
))
2106 if (stat(filename
, &st
) >= 0 &&
2107 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
2114 static int check_hdev_writable(BDRVRawState
*s
)
2116 #if defined(BLKROGET)
2117 /* Linux block devices can be configured "read-only" using blockdev(8).
2118 * This is independent of device node permissions and therefore open(2)
2119 * with O_RDWR succeeds. Actual writes fail with EPERM.
2121 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
2122 * check for read-only block devices so that Linux block devices behave
2128 if (fstat(s
->fd
, &st
)) {
2132 if (!S_ISBLK(st
.st_mode
)) {
2136 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
2143 #endif /* defined(BLKROGET) */
2147 static void hdev_parse_filename(const char *filename
, QDict
*options
,
2150 /* The prefix is optional, just as for "file". */
2151 strstart(filename
, "host_device:", &filename
);
2153 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2156 static bool hdev_is_sg(BlockDriverState
*bs
)
2159 #if defined(__linux__)
2161 BDRVRawState
*s
= bs
->opaque
;
2163 struct sg_scsi_id scsiid
;
2167 if (stat(bs
->filename
, &st
) < 0 || !S_ISCHR(st
.st_mode
)) {
2171 ret
= ioctl(s
->fd
, SG_GET_VERSION_NUM
, &sg_version
);
2176 ret
= ioctl(s
->fd
, SG_GET_SCSI_ID
, &scsiid
);
2178 DPRINTF("SG device found: type=%d, version=%d\n",
2179 scsiid
.scsi_type
, sg_version
);
2188 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2191 BDRVRawState
*s
= bs
->opaque
;
2192 Error
*local_err
= NULL
;
2195 #if defined(__APPLE__) && defined(__MACH__)
2197 * Caution: while qdict_get_str() is fine, getting non-string types
2198 * would require more care. When @options come from -blockdev or
2199 * blockdev_add, its members are typed according to the QAPI
2200 * schema, but when they come from -drive, they're all QString.
2202 const char *filename
= qdict_get_str(options
, "filename");
2203 char bsd_path
[MAXPATHLEN
] = "";
2204 bool error_occurred
= false;
2206 /* If using a real cdrom */
2207 if (strcmp(filename
, "/dev/cdrom") == 0) {
2208 char *mediaType
= NULL
;
2209 kern_return_t ret_val
;
2210 io_iterator_t mediaIterator
= 0;
2212 mediaType
= FindEjectableOpticalMedia(&mediaIterator
);
2213 if (mediaType
== NULL
) {
2214 error_setg(errp
, "Please make sure your CD/DVD is in the optical"
2216 error_occurred
= true;
2217 goto hdev_open_Mac_error
;
2220 ret_val
= GetBSDPath(mediaIterator
, bsd_path
, sizeof(bsd_path
), flags
);
2221 if (ret_val
!= KERN_SUCCESS
) {
2222 error_setg(errp
, "Could not get BSD path for optical drive");
2223 error_occurred
= true;
2224 goto hdev_open_Mac_error
;
2227 /* If a real optical drive was not found */
2228 if (bsd_path
[0] == '\0') {
2229 error_setg(errp
, "Failed to obtain bsd path for optical drive");
2230 error_occurred
= true;
2231 goto hdev_open_Mac_error
;
2234 /* If using a cdrom disc and finding a partition on the disc failed */
2235 if (strncmp(mediaType
, kIOCDMediaClass
, 9) == 0 &&
2236 setup_cdrom(bsd_path
, errp
) == false) {
2237 print_unmounting_directions(bsd_path
);
2238 error_occurred
= true;
2239 goto hdev_open_Mac_error
;
2242 qdict_put(options
, "filename", qstring_from_str(bsd_path
));
2244 hdev_open_Mac_error
:
2246 if (mediaIterator
) {
2247 IOObjectRelease(mediaIterator
);
2249 if (error_occurred
) {
2253 #endif /* defined(__APPLE__) && defined(__MACH__) */
2255 s
->type
= FTYPE_FILE
;
2257 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2259 error_propagate(errp
, local_err
);
2260 #if defined(__APPLE__) && defined(__MACH__)
2262 filename
= bsd_path
;
2264 /* if a physical device experienced an error while being opened */
2265 if (strncmp(filename
, "/dev/", 5) == 0) {
2266 print_unmounting_directions(filename
);
2268 #endif /* defined(__APPLE__) && defined(__MACH__) */
2272 /* Since this does ioctl the device must be already opened */
2273 bs
->sg
= hdev_is_sg(bs
);
2275 if (flags
& BDRV_O_RDWR
) {
2276 ret
= check_hdev_writable(s
);
2279 error_setg_errno(errp
, -ret
, "The device is not writable");
2287 #if defined(__linux__)
2289 static BlockAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
2290 unsigned long int req
, void *buf
,
2291 BlockCompletionFunc
*cb
, void *opaque
)
2293 BDRVRawState
*s
= bs
->opaque
;
2294 RawPosixAIOData
*acb
;
2297 if (fd_open(bs
) < 0)
2300 acb
= g_new(RawPosixAIOData
, 1);
2302 acb
->aio_type
= QEMU_AIO_IOCTL
;
2303 acb
->aio_fildes
= s
->fd
;
2304 acb
->aio_offset
= 0;
2305 acb
->aio_ioctl_buf
= buf
;
2306 acb
->aio_ioctl_cmd
= req
;
2307 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
2308 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
2312 static int fd_open(BlockDriverState
*bs
)
2314 BDRVRawState
*s
= bs
->opaque
;
2316 /* this is just to ensure s->fd is sane (its called by io ops) */
2322 static coroutine_fn BlockAIOCB
*hdev_aio_pdiscard(BlockDriverState
*bs
,
2323 int64_t offset
, int count
,
2324 BlockCompletionFunc
*cb
, void *opaque
)
2326 BDRVRawState
*s
= bs
->opaque
;
2328 if (fd_open(bs
) < 0) {
2331 return paio_submit(bs
, s
->fd
, offset
, NULL
, count
,
2332 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2335 static coroutine_fn
int hdev_co_pwrite_zeroes(BlockDriverState
*bs
,
2336 int64_t offset
, int count
, BdrvRequestFlags flags
)
2338 BDRVRawState
*s
= bs
->opaque
;
2345 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
2346 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, count
,
2347 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
2348 } else if (s
->discard_zeroes
) {
2349 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, count
,
2350 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2355 static int hdev_create(const char *filename
, QemuOpts
*opts
,
2360 struct stat stat_buf
;
2361 int64_t total_size
= 0;
2364 /* This function is used by both protocol block drivers and therefore either
2365 * of these prefixes may be given.
2366 * The return value has to be stored somewhere, otherwise this is an error
2367 * due to -Werror=unused-value. */
2369 strstart(filename
, "host_device:", &filename
) ||
2370 strstart(filename
, "host_cdrom:" , &filename
);
2374 ret
= raw_normalize_devicepath(&filename
);
2376 error_setg_errno(errp
, -ret
, "Could not normalize device path");
2380 /* Read out options */
2381 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2384 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
2387 error_setg_errno(errp
, -ret
, "Could not open device");
2391 if (fstat(fd
, &stat_buf
) < 0) {
2393 error_setg_errno(errp
, -ret
, "Could not stat device");
2394 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
2396 "The given file is neither a block nor a character device");
2398 } else if (lseek(fd
, 0, SEEK_END
) < total_size
) {
2399 error_setg(errp
, "Device is too small");
2407 static BlockDriver bdrv_host_device
= {
2408 .format_name
= "host_device",
2409 .protocol_name
= "host_device",
2410 .instance_size
= sizeof(BDRVRawState
),
2411 .bdrv_needs_filename
= true,
2412 .bdrv_probe_device
= hdev_probe_device
,
2413 .bdrv_parse_filename
= hdev_parse_filename
,
2414 .bdrv_file_open
= hdev_open
,
2415 .bdrv_close
= raw_close
,
2416 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2417 .bdrv_reopen_commit
= raw_reopen_commit
,
2418 .bdrv_reopen_abort
= raw_reopen_abort
,
2419 .bdrv_create
= hdev_create
,
2420 .create_opts
= &raw_create_opts
,
2421 .bdrv_co_pwrite_zeroes
= hdev_co_pwrite_zeroes
,
2423 .bdrv_co_preadv
= raw_co_preadv
,
2424 .bdrv_co_pwritev
= raw_co_pwritev
,
2425 .bdrv_aio_flush
= raw_aio_flush
,
2426 .bdrv_aio_pdiscard
= hdev_aio_pdiscard
,
2427 .bdrv_refresh_limits
= raw_refresh_limits
,
2428 .bdrv_io_plug
= raw_aio_plug
,
2429 .bdrv_io_unplug
= raw_aio_unplug
,
2431 .bdrv_truncate
= raw_truncate
,
2432 .bdrv_getlength
= raw_getlength
,
2433 .bdrv_get_info
= raw_get_info
,
2434 .bdrv_get_allocated_file_size
2435 = raw_get_allocated_file_size
,
2436 .bdrv_probe_blocksizes
= hdev_probe_blocksizes
,
2437 .bdrv_probe_geometry
= hdev_probe_geometry
,
2439 /* generic scsi device */
2441 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2445 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2446 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2449 /* The prefix is optional, just as for "file". */
2450 strstart(filename
, "host_cdrom:", &filename
);
2452 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2457 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2460 BDRVRawState
*s
= bs
->opaque
;
2464 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2465 return raw_open_common(bs
, options
, flags
, O_NONBLOCK
, errp
);
2468 static int cdrom_probe_device(const char *filename
)
2474 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2478 ret
= fstat(fd
, &st
);
2479 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2483 /* Attempt to detect via a CDROM specific ioctl */
2484 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2494 static bool cdrom_is_inserted(BlockDriverState
*bs
)
2496 BDRVRawState
*s
= bs
->opaque
;
2499 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2500 return ret
== CDS_DISC_OK
;
2503 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2505 BDRVRawState
*s
= bs
->opaque
;
2508 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2509 perror("CDROMEJECT");
2511 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2512 perror("CDROMEJECT");
2516 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2518 BDRVRawState
*s
= bs
->opaque
;
2520 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2522 * Note: an error can happen if the distribution automatically
2525 /* perror("CDROM_LOCKDOOR"); */
2529 static BlockDriver bdrv_host_cdrom
= {
2530 .format_name
= "host_cdrom",
2531 .protocol_name
= "host_cdrom",
2532 .instance_size
= sizeof(BDRVRawState
),
2533 .bdrv_needs_filename
= true,
2534 .bdrv_probe_device
= cdrom_probe_device
,
2535 .bdrv_parse_filename
= cdrom_parse_filename
,
2536 .bdrv_file_open
= cdrom_open
,
2537 .bdrv_close
= raw_close
,
2538 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2539 .bdrv_reopen_commit
= raw_reopen_commit
,
2540 .bdrv_reopen_abort
= raw_reopen_abort
,
2541 .bdrv_create
= hdev_create
,
2542 .create_opts
= &raw_create_opts
,
2545 .bdrv_co_preadv
= raw_co_preadv
,
2546 .bdrv_co_pwritev
= raw_co_pwritev
,
2547 .bdrv_aio_flush
= raw_aio_flush
,
2548 .bdrv_refresh_limits
= raw_refresh_limits
,
2549 .bdrv_io_plug
= raw_aio_plug
,
2550 .bdrv_io_unplug
= raw_aio_unplug
,
2552 .bdrv_truncate
= raw_truncate
,
2553 .bdrv_getlength
= raw_getlength
,
2554 .has_variable_length
= true,
2555 .bdrv_get_allocated_file_size
2556 = raw_get_allocated_file_size
,
2558 /* removable device support */
2559 .bdrv_is_inserted
= cdrom_is_inserted
,
2560 .bdrv_eject
= cdrom_eject
,
2561 .bdrv_lock_medium
= cdrom_lock_medium
,
2563 /* generic scsi device */
2564 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2566 #endif /* __linux__ */
2568 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2569 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2572 BDRVRawState
*s
= bs
->opaque
;
2573 Error
*local_err
= NULL
;
2578 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2580 error_propagate(errp
, local_err
);
2584 /* make sure the door isn't locked at this time */
2585 ioctl(s
->fd
, CDIOCALLOW
);
2589 static int cdrom_probe_device(const char *filename
)
2591 if (strstart(filename
, "/dev/cd", NULL
) ||
2592 strstart(filename
, "/dev/acd", NULL
))
2597 static int cdrom_reopen(BlockDriverState
*bs
)
2599 BDRVRawState
*s
= bs
->opaque
;
2603 * Force reread of possibly changed/newly loaded disc,
2604 * FreeBSD seems to not notice sometimes...
2608 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
2615 /* make sure the door isn't locked at this time */
2616 ioctl(s
->fd
, CDIOCALLOW
);
2620 static bool cdrom_is_inserted(BlockDriverState
*bs
)
2622 return raw_getlength(bs
) > 0;
2625 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2627 BDRVRawState
*s
= bs
->opaque
;
2632 (void) ioctl(s
->fd
, CDIOCALLOW
);
2635 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
2636 perror("CDIOCEJECT");
2638 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
2639 perror("CDIOCCLOSE");
2645 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2647 BDRVRawState
*s
= bs
->opaque
;
2651 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
2653 * Note: an error can happen if the distribution automatically
2656 /* perror("CDROM_LOCKDOOR"); */
2660 static BlockDriver bdrv_host_cdrom
= {
2661 .format_name
= "host_cdrom",
2662 .protocol_name
= "host_cdrom",
2663 .instance_size
= sizeof(BDRVRawState
),
2664 .bdrv_needs_filename
= true,
2665 .bdrv_probe_device
= cdrom_probe_device
,
2666 .bdrv_parse_filename
= cdrom_parse_filename
,
2667 .bdrv_file_open
= cdrom_open
,
2668 .bdrv_close
= raw_close
,
2669 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2670 .bdrv_reopen_commit
= raw_reopen_commit
,
2671 .bdrv_reopen_abort
= raw_reopen_abort
,
2672 .bdrv_create
= hdev_create
,
2673 .create_opts
= &raw_create_opts
,
2675 .bdrv_co_preadv
= raw_co_preadv
,
2676 .bdrv_co_pwritev
= raw_co_pwritev
,
2677 .bdrv_aio_flush
= raw_aio_flush
,
2678 .bdrv_refresh_limits
= raw_refresh_limits
,
2679 .bdrv_io_plug
= raw_aio_plug
,
2680 .bdrv_io_unplug
= raw_aio_unplug
,
2682 .bdrv_truncate
= raw_truncate
,
2683 .bdrv_getlength
= raw_getlength
,
2684 .has_variable_length
= true,
2685 .bdrv_get_allocated_file_size
2686 = raw_get_allocated_file_size
,
2688 /* removable device support */
2689 .bdrv_is_inserted
= cdrom_is_inserted
,
2690 .bdrv_eject
= cdrom_eject
,
2691 .bdrv_lock_medium
= cdrom_lock_medium
,
2693 #endif /* __FreeBSD__ */
2695 static void bdrv_file_init(void)
2698 * Register all the drivers. Note that order is important, the driver
2699 * registered last will get probed first.
2701 bdrv_register(&bdrv_file
);
2702 bdrv_register(&bdrv_host_device
);
2704 bdrv_register(&bdrv_host_cdrom
);
2706 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2707 bdrv_register(&bdrv_host_cdrom
);
2711 block_init(bdrv_file_init
);