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-common.h"
25 #include "qemu/error-report.h"
26 #include "qemu/timer.h"
28 #include "block/block_int.h"
29 #include "qemu/module.h"
31 #include "block/thread-pool.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 <CoreFoundation/CoreFoundation.h>
50 #define _POSIX_PTHREAD_SEMANTICS 1
54 #include <sys/types.h>
56 #include <sys/ioctl.h>
57 #include <sys/param.h>
58 #include <linux/cdrom.h>
61 #include <linux/hdreg.h>
67 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
70 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
71 #include <linux/falloc.h>
73 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
79 #include <sys/ioctl.h>
80 #include <sys/disklabel.h>
85 #include <sys/ioctl.h>
86 #include <sys/disklabel.h>
92 #include <sys/ioctl.h>
93 #include <sys/diskslice.h>
100 //#define DEBUG_BLOCK
103 # define DEBUG_BLOCK_PRINT 1
105 # define DEBUG_BLOCK_PRINT 0
107 #define DPRINTF(fmt, ...) \
109 if (DEBUG_BLOCK_PRINT) { \
110 printf(fmt, ## __VA_ARGS__); \
114 /* OS X does not have O_DSYNC */
117 #define O_DSYNC O_SYNC
118 #elif defined(O_FSYNC)
119 #define O_DSYNC O_FSYNC
123 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
125 #define O_DIRECT O_DSYNC
132 /* if the FD is not accessed during that time (in ns), we try to
133 reopen it to see if the disk has been changed */
134 #define FD_OPEN_TIMEOUT (1000000000)
136 #define MAX_BLOCKSIZE 4096
138 typedef struct BDRVRawState
{
144 #if defined(__linux__)
145 /* linux floppy specific */
146 int64_t fd_open_time
;
147 int64_t fd_error_time
;
149 int fd_media_changed
;
151 #ifdef CONFIG_LINUX_AIO
159 bool has_write_zeroes
:1;
160 bool discard_zeroes
:1;
162 bool needs_alignment
;
165 typedef struct BDRVRawReopenState
{
168 #ifdef CONFIG_LINUX_AIO
171 } BDRVRawReopenState
;
173 static int fd_open(BlockDriverState
*bs
);
174 static int64_t raw_getlength(BlockDriverState
*bs
);
176 typedef struct RawPosixAIOData
{
177 BlockDriverState
*bs
;
180 struct iovec
*aio_iov
;
185 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
190 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
191 static int cdrom_reopen(BlockDriverState
*bs
);
194 #if defined(__NetBSD__)
195 static int raw_normalize_devicepath(const char **filename
)
197 static char namebuf
[PATH_MAX
];
198 const char *dp
, *fname
;
202 dp
= strrchr(fname
, '/');
203 if (lstat(fname
, &sb
) < 0) {
204 fprintf(stderr
, "%s: stat failed: %s\n",
205 fname
, strerror(errno
));
209 if (!S_ISBLK(sb
.st_mode
)) {
214 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
216 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
217 (int)(dp
- fname
), fname
, dp
+ 1);
219 fprintf(stderr
, "%s is a block device", fname
);
221 fprintf(stderr
, ", using %s\n", *filename
);
226 static int raw_normalize_devicepath(const char **filename
)
233 * Get logical block size via ioctl. On success store it in @sector_size_p.
235 static int probe_logical_blocksize(int fd
, unsigned int *sector_size_p
)
237 unsigned int sector_size
;
238 bool success
= false;
242 /* Try a few ioctls to get the right size */
244 if (ioctl(fd
, BLKSSZGET
, §or_size
) >= 0) {
245 *sector_size_p
= sector_size
;
249 #ifdef DKIOCGETBLOCKSIZE
250 if (ioctl(fd
, DKIOCGETBLOCKSIZE
, §or_size
) >= 0) {
251 *sector_size_p
= sector_size
;
255 #ifdef DIOCGSECTORSIZE
256 if (ioctl(fd
, DIOCGSECTORSIZE
, §or_size
) >= 0) {
257 *sector_size_p
= sector_size
;
262 return success
? 0 : -errno
;
266 * Get physical block size of @fd.
267 * On success, store it in @blk_size and return 0.
268 * On failure, return -errno.
270 static int probe_physical_blocksize(int fd
, unsigned int *blk_size
)
273 if (ioctl(fd
, BLKPBSZGET
, blk_size
) < 0) {
282 /* Check if read is allowed with given memory buffer and length.
284 * This function is used to check O_DIRECT memory buffer and request alignment.
286 static bool raw_is_io_aligned(int fd
, void *buf
, size_t len
)
288 ssize_t ret
= pread(fd
, buf
, len
, 0);
295 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
296 * other errors (e.g. real I/O error), which could happen on a failed
297 * drive, since we only care about probing alignment.
299 if (errno
!= EINVAL
) {
307 static void raw_probe_alignment(BlockDriverState
*bs
, int fd
, Error
**errp
)
309 BDRVRawState
*s
= bs
->opaque
;
311 size_t max_align
= MAX(MAX_BLOCKSIZE
, getpagesize());
313 /* For SCSI generic devices the alignment is not really used.
314 With buffered I/O, we don't have any restrictions. */
315 if (bdrv_is_sg(bs
) || !s
->needs_alignment
) {
316 bs
->request_alignment
= 1;
321 bs
->request_alignment
= 0;
323 /* Let's try to use the logical blocksize for the alignment. */
324 if (probe_logical_blocksize(fd
, &bs
->request_alignment
) < 0) {
325 bs
->request_alignment
= 0;
330 if (xfsctl(NULL
, fd
, XFS_IOC_DIOINFO
, &da
) >= 0) {
331 bs
->request_alignment
= da
.d_miniosz
;
332 /* The kernel returns wrong information for d_mem */
333 /* s->buf_align = da.d_mem; */
338 /* If we could not get the sizes so far, we can only guess them */
341 buf
= qemu_memalign(max_align
, 2 * max_align
);
342 for (align
= 512; align
<= max_align
; align
<<= 1) {
343 if (raw_is_io_aligned(fd
, buf
+ align
, max_align
)) {
344 s
->buf_align
= align
;
351 if (!bs
->request_alignment
) {
353 buf
= qemu_memalign(s
->buf_align
, max_align
);
354 for (align
= 512; align
<= max_align
; align
<<= 1) {
355 if (raw_is_io_aligned(fd
, buf
, align
)) {
356 bs
->request_alignment
= align
;
363 if (!s
->buf_align
|| !bs
->request_alignment
) {
364 error_setg(errp
, "Could not find working O_DIRECT alignment. "
365 "Try cache.direct=off.");
369 static void raw_parse_flags(int bdrv_flags
, int *open_flags
)
371 assert(open_flags
!= NULL
);
373 *open_flags
|= O_BINARY
;
374 *open_flags
&= ~O_ACCMODE
;
375 if (bdrv_flags
& BDRV_O_RDWR
) {
376 *open_flags
|= O_RDWR
;
378 *open_flags
|= O_RDONLY
;
381 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
382 * and O_DIRECT for no caching. */
383 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
384 *open_flags
|= O_DIRECT
;
388 static void raw_detach_aio_context(BlockDriverState
*bs
)
390 #ifdef CONFIG_LINUX_AIO
391 BDRVRawState
*s
= bs
->opaque
;
394 laio_detach_aio_context(s
->aio_ctx
, bdrv_get_aio_context(bs
));
399 static void raw_attach_aio_context(BlockDriverState
*bs
,
400 AioContext
*new_context
)
402 #ifdef CONFIG_LINUX_AIO
403 BDRVRawState
*s
= bs
->opaque
;
406 laio_attach_aio_context(s
->aio_ctx
, new_context
);
411 #ifdef CONFIG_LINUX_AIO
412 static int raw_set_aio(void **aio_ctx
, int *use_aio
, int bdrv_flags
)
415 assert(aio_ctx
!= NULL
);
416 assert(use_aio
!= NULL
);
418 * Currently Linux do AIO only for files opened with O_DIRECT
419 * specified so check NOCACHE flag too
421 if ((bdrv_flags
& (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) ==
422 (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) {
424 /* if non-NULL, laio_init() has already been run */
425 if (*aio_ctx
== NULL
) {
426 *aio_ctx
= laio_init();
443 static void raw_parse_filename(const char *filename
, QDict
*options
,
446 /* The filename does not have to be prefixed by the protocol name, since
447 * "file" is the default protocol; therefore, the return value of this
448 * function call can be ignored. */
449 strstart(filename
, "file:", &filename
);
451 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
454 static QemuOptsList raw_runtime_opts
= {
456 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
460 .type
= QEMU_OPT_STRING
,
461 .help
= "File name of the image",
463 { /* end of list */ }
467 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
468 int bdrv_flags
, int open_flags
, Error
**errp
)
470 BDRVRawState
*s
= bs
->opaque
;
472 Error
*local_err
= NULL
;
473 const char *filename
= NULL
;
477 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
478 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
480 error_propagate(errp
, local_err
);
485 filename
= qemu_opt_get(opts
, "filename");
487 ret
= raw_normalize_devicepath(&filename
);
489 error_setg_errno(errp
, -ret
, "Could not normalize device path");
493 s
->open_flags
= open_flags
;
494 raw_parse_flags(bdrv_flags
, &s
->open_flags
);
497 fd
= qemu_open(filename
, s
->open_flags
, 0644);
507 #ifdef CONFIG_LINUX_AIO
508 if (raw_set_aio(&s
->aio_ctx
, &s
->use_aio
, bdrv_flags
)) {
511 error_setg_errno(errp
, -ret
, "Could not set AIO state");
514 if (!s
->use_aio
&& (bdrv_flags
& BDRV_O_NATIVE_AIO
)) {
515 error_printf("WARNING: aio=native was specified for '%s', but "
516 "it requires cache.direct=on, which was not "
517 "specified. Falling back to aio=threads.\n"
518 " This will become an error condition in "
519 "future QEMU versions.\n",
524 s
->has_discard
= true;
525 s
->has_write_zeroes
= true;
526 if ((bs
->open_flags
& BDRV_O_NOCACHE
) != 0) {
527 s
->needs_alignment
= true;
530 if (fstat(s
->fd
, &st
) < 0) {
532 error_setg_errno(errp
, errno
, "Could not stat file");
535 if (S_ISREG(st
.st_mode
)) {
536 s
->discard_zeroes
= true;
537 s
->has_fallocate
= true;
539 if (S_ISBLK(st
.st_mode
)) {
540 #ifdef BLKDISCARDZEROES
542 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
543 s
->discard_zeroes
= true;
547 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
548 * not rely on the contents of discarded blocks unless using O_DIRECT.
549 * Same for BLKZEROOUT.
551 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
552 s
->discard_zeroes
= false;
553 s
->has_write_zeroes
= false;
558 if (S_ISCHR(st
.st_mode
)) {
560 * The file is a char device (disk), which on FreeBSD isn't behind
561 * a pager, so force all requests to be aligned. This is needed
562 * so QEMU makes sure all IO operations on the device are aligned
563 * to sector size, or else FreeBSD will reject them with EINVAL.
565 s
->needs_alignment
= true;
570 if (platform_test_xfs_fd(s
->fd
)) {
575 raw_attach_aio_context(bs
, bdrv_get_aio_context(bs
));
579 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
586 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
589 BDRVRawState
*s
= bs
->opaque
;
590 Error
*local_err
= NULL
;
593 s
->type
= FTYPE_FILE
;
594 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
596 error_propagate(errp
, local_err
);
601 static int raw_reopen_prepare(BDRVReopenState
*state
,
602 BlockReopenQueue
*queue
, Error
**errp
)
605 BDRVRawReopenState
*raw_s
;
607 Error
*local_err
= NULL
;
609 assert(state
!= NULL
);
610 assert(state
->bs
!= NULL
);
612 s
= state
->bs
->opaque
;
614 state
->opaque
= g_new0(BDRVRawReopenState
, 1);
615 raw_s
= state
->opaque
;
617 #ifdef CONFIG_LINUX_AIO
618 raw_s
->use_aio
= s
->use_aio
;
620 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
621 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
622 * won't override aio_ctx if aio_ctx is non-NULL */
623 if (raw_set_aio(&s
->aio_ctx
, &raw_s
->use_aio
, state
->flags
)) {
624 error_setg(errp
, "Could not set AIO state");
629 if (s
->type
== FTYPE_FD
|| s
->type
== FTYPE_CD
) {
630 raw_s
->open_flags
|= O_NONBLOCK
;
633 raw_parse_flags(state
->flags
, &raw_s
->open_flags
);
637 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
639 fcntl_flags
|= O_NOATIME
;
643 /* Not all operating systems have O_ASYNC, and those that don't
644 * will not let us track the state into raw_s->open_flags (typically
645 * you achieve the same effect with an ioctl, for example I_SETSIG
646 * on Solaris). But we do not use O_ASYNC, so that's fine.
648 assert((s
->open_flags
& O_ASYNC
) == 0);
651 if ((raw_s
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
652 /* dup the original fd */
653 /* TODO: use qemu fcntl wrapper */
654 #ifdef F_DUPFD_CLOEXEC
655 raw_s
->fd
= fcntl(s
->fd
, F_DUPFD_CLOEXEC
, 0);
657 raw_s
->fd
= dup(s
->fd
);
658 if (raw_s
->fd
!= -1) {
659 qemu_set_cloexec(raw_s
->fd
);
662 if (raw_s
->fd
>= 0) {
663 ret
= fcntl_setfl(raw_s
->fd
, raw_s
->open_flags
);
665 qemu_close(raw_s
->fd
);
671 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
672 if (raw_s
->fd
== -1) {
673 const char *normalized_filename
= state
->bs
->filename
;
674 ret
= raw_normalize_devicepath(&normalized_filename
);
676 error_setg_errno(errp
, -ret
, "Could not normalize device path");
678 assert(!(raw_s
->open_flags
& O_CREAT
));
679 raw_s
->fd
= qemu_open(normalized_filename
, raw_s
->open_flags
);
680 if (raw_s
->fd
== -1) {
681 error_setg_errno(errp
, errno
, "Could not reopen file");
687 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
688 * alignment with the new fd. */
689 if (raw_s
->fd
!= -1) {
690 raw_probe_alignment(state
->bs
, raw_s
->fd
, &local_err
);
692 qemu_close(raw_s
->fd
);
694 error_propagate(errp
, local_err
);
702 static void raw_reopen_commit(BDRVReopenState
*state
)
704 BDRVRawReopenState
*raw_s
= state
->opaque
;
705 BDRVRawState
*s
= state
->bs
->opaque
;
707 s
->open_flags
= raw_s
->open_flags
;
711 #ifdef CONFIG_LINUX_AIO
712 s
->use_aio
= raw_s
->use_aio
;
715 g_free(state
->opaque
);
716 state
->opaque
= NULL
;
720 static void raw_reopen_abort(BDRVReopenState
*state
)
722 BDRVRawReopenState
*raw_s
= state
->opaque
;
724 /* nothing to do if NULL, we didn't get far enough */
729 if (raw_s
->fd
>= 0) {
730 qemu_close(raw_s
->fd
);
733 g_free(state
->opaque
);
734 state
->opaque
= NULL
;
737 static void raw_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
739 BDRVRawState
*s
= bs
->opaque
;
741 raw_probe_alignment(bs
, s
->fd
, errp
);
742 bs
->bl
.min_mem_alignment
= s
->buf_align
;
743 bs
->bl
.opt_mem_alignment
= MAX(s
->buf_align
, getpagesize());
746 static int check_for_dasd(int fd
)
749 struct dasd_information2_t info
= {0};
751 return ioctl(fd
, BIODASDINFO2
, &info
);
758 * Try to get @bs's logical and physical block size.
759 * On success, store them in @bsz and return zero.
760 * On failure, return negative errno.
762 static int hdev_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
764 BDRVRawState
*s
= bs
->opaque
;
767 /* If DASD, get blocksizes */
768 if (check_for_dasd(s
->fd
) < 0) {
771 ret
= probe_logical_blocksize(s
->fd
, &bsz
->log
);
775 return probe_physical_blocksize(s
->fd
, &bsz
->phys
);
779 * Try to get @bs's geometry: cyls, heads, sectors.
780 * On success, store them in @geo and return 0.
781 * On failure return -errno.
782 * (Allows block driver to assign default geometry values that guest sees)
785 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
787 BDRVRawState
*s
= bs
->opaque
;
788 struct hd_geometry ioctl_geo
= {0};
791 /* If DASD, get its geometry */
792 if (check_for_dasd(s
->fd
) < 0) {
795 if (ioctl(s
->fd
, HDIO_GETGEO
, &ioctl_geo
) < 0) {
798 /* HDIO_GETGEO may return success even though geo contains zeros
799 (e.g. certain multipath setups) */
800 if (!ioctl_geo
.heads
|| !ioctl_geo
.sectors
|| !ioctl_geo
.cylinders
) {
803 /* Do not return a geometry for partition */
804 if (ioctl_geo
.start
!= 0) {
807 geo
->heads
= ioctl_geo
.heads
;
808 geo
->sectors
= ioctl_geo
.sectors
;
809 if (!probe_physical_blocksize(s
->fd
, &blksize
)) {
810 /* overwrite cyls: HDIO_GETGEO result is incorrect for big drives */
811 geo
->cylinders
= bdrv_nb_sectors(bs
) / (blksize
/ BDRV_SECTOR_SIZE
)
812 / (geo
->heads
* geo
->sectors
);
815 geo
->cylinders
= ioctl_geo
.cylinders
;
819 #else /* __linux__ */
820 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
826 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
830 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
838 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
842 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
851 static bool preadv_present
= true;
854 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
856 return preadv(fd
, iov
, nr_iov
, offset
);
860 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
862 return pwritev(fd
, iov
, nr_iov
, offset
);
867 static bool preadv_present
= false;
870 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
876 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
883 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
888 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
889 len
= qemu_pwritev(aiocb
->aio_fildes
,
894 len
= qemu_preadv(aiocb
->aio_fildes
,
898 } while (len
== -1 && errno
== EINTR
);
907 * Read/writes the data to/from a given linear buffer.
909 * Returns the number of bytes handles or -errno in case of an error. Short
910 * reads are only returned if the end of the file is reached.
912 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
917 while (offset
< aiocb
->aio_nbytes
) {
918 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
919 len
= pwrite(aiocb
->aio_fildes
,
920 (const char *)buf
+ offset
,
921 aiocb
->aio_nbytes
- offset
,
922 aiocb
->aio_offset
+ offset
);
924 len
= pread(aiocb
->aio_fildes
,
926 aiocb
->aio_nbytes
- offset
,
927 aiocb
->aio_offset
+ offset
);
929 if (len
== -1 && errno
== EINTR
) {
931 } else if (len
== -1 && errno
== EINVAL
&&
932 (aiocb
->bs
->open_flags
& BDRV_O_NOCACHE
) &&
933 !(aiocb
->aio_type
& QEMU_AIO_WRITE
) &&
935 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
936 * after a short read. Assume that O_DIRECT short reads only occur
937 * at EOF. Therefore this is a short read, not an I/O error.
940 } else if (len
== -1) {
943 } else if (len
== 0) {
952 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
957 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
959 * If there is just a single buffer, and it is properly aligned
960 * we can just use plain pread/pwrite without any problems.
962 if (aiocb
->aio_niov
== 1) {
963 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
966 * We have more than one iovec, and all are properly aligned.
968 * Try preadv/pwritev first and fall back to linearizing the
969 * buffer if it's not supported.
971 if (preadv_present
) {
972 nbytes
= handle_aiocb_rw_vector(aiocb
);
973 if (nbytes
== aiocb
->aio_nbytes
||
974 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
977 preadv_present
= false;
981 * XXX(hch): short read/write. no easy way to handle the reminder
982 * using these interfaces. For now retry using plain
988 * Ok, we have to do it the hard way, copy all segments into
989 * a single aligned buffer.
991 buf
= qemu_try_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
996 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1000 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
1001 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
1002 p
+= aiocb
->aio_iov
[i
].iov_len
;
1004 assert(p
- buf
== aiocb
->aio_nbytes
);
1007 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
1008 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
1010 size_t count
= aiocb
->aio_nbytes
, copy
;
1013 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
1015 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
1016 copy
= aiocb
->aio_iov
[i
].iov_len
;
1018 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
1019 assert(count
>= copy
);
1031 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1033 struct xfs_flock64 fl
;
1036 memset(&fl
, 0, sizeof(fl
));
1037 fl
.l_whence
= SEEK_SET
;
1038 fl
.l_start
= offset
;
1041 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
1043 DPRINTF("cannot write zero range (%s)\n", strerror(errno
));
1050 static int xfs_discard(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1052 struct xfs_flock64 fl
;
1055 memset(&fl
, 0, sizeof(fl
));
1056 fl
.l_whence
= SEEK_SET
;
1057 fl
.l_start
= offset
;
1060 if (xfsctl(NULL
, s
->fd
, XFS_IOC_UNRESVSP64
, &fl
) < 0) {
1062 DPRINTF("cannot punch hole (%s)\n", strerror(errno
));
1070 static int translate_err(int err
)
1072 if (err
== -ENODEV
|| err
== -ENOSYS
|| err
== -EOPNOTSUPP
||
1079 #ifdef CONFIG_FALLOCATE
1080 static int do_fallocate(int fd
, int mode
, off_t offset
, off_t len
)
1083 if (fallocate(fd
, mode
, offset
, len
) == 0) {
1086 } while (errno
== EINTR
);
1087 return translate_err(-errno
);
1091 static ssize_t
handle_aiocb_write_zeroes_block(RawPosixAIOData
*aiocb
)
1094 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1096 if (!s
->has_write_zeroes
) {
1102 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1103 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
1106 } while (errno
== EINTR
);
1108 ret
= translate_err(-errno
);
1111 if (ret
== -ENOTSUP
) {
1112 s
->has_write_zeroes
= false;
1117 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
1119 #if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1120 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1123 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1124 return handle_aiocb_write_zeroes_block(aiocb
);
1129 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1133 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1134 if (s
->has_write_zeroes
) {
1135 int ret
= do_fallocate(s
->fd
, FALLOC_FL_ZERO_RANGE
,
1136 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1137 if (ret
== 0 || ret
!= -ENOTSUP
) {
1140 s
->has_write_zeroes
= false;
1144 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1145 if (s
->has_discard
&& s
->has_fallocate
) {
1146 int ret
= do_fallocate(s
->fd
,
1147 FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1148 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1150 ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1151 if (ret
== 0 || ret
!= -ENOTSUP
) {
1154 s
->has_fallocate
= false;
1155 } else if (ret
!= -ENOTSUP
) {
1158 s
->has_discard
= false;
1163 #ifdef CONFIG_FALLOCATE
1164 if (s
->has_fallocate
&& aiocb
->aio_offset
>= bdrv_getlength(aiocb
->bs
)) {
1165 int ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1166 if (ret
== 0 || ret
!= -ENOTSUP
) {
1169 s
->has_fallocate
= false;
1176 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
1178 int ret
= -EOPNOTSUPP
;
1179 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1181 if (!s
->has_discard
) {
1185 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1188 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1189 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
1192 } while (errno
== EINTR
);
1199 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1203 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1204 ret
= do_fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1205 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1209 ret
= translate_err(ret
);
1210 if (ret
== -ENOTSUP
) {
1211 s
->has_discard
= false;
1216 static int aio_worker(void *arg
)
1218 RawPosixAIOData
*aiocb
= arg
;
1221 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
1223 ret
= handle_aiocb_rw(aiocb
);
1224 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1225 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
1226 0, aiocb
->aio_nbytes
- ret
);
1228 ret
= aiocb
->aio_nbytes
;
1230 if (ret
== aiocb
->aio_nbytes
) {
1232 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1236 case QEMU_AIO_WRITE
:
1237 ret
= handle_aiocb_rw(aiocb
);
1238 if (ret
== aiocb
->aio_nbytes
) {
1240 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1244 case QEMU_AIO_FLUSH
:
1245 ret
= handle_aiocb_flush(aiocb
);
1247 case QEMU_AIO_IOCTL
:
1248 ret
= handle_aiocb_ioctl(aiocb
);
1250 case QEMU_AIO_DISCARD
:
1251 ret
= handle_aiocb_discard(aiocb
);
1253 case QEMU_AIO_WRITE_ZEROES
:
1254 ret
= handle_aiocb_write_zeroes(aiocb
);
1257 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
1266 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
1267 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1270 RawPosixAIOData
*acb
= g_new(RawPosixAIOData
, 1);
1274 acb
->aio_type
= type
;
1275 acb
->aio_fildes
= fd
;
1277 acb
->aio_nbytes
= nb_sectors
* BDRV_SECTOR_SIZE
;
1278 acb
->aio_offset
= sector_num
* BDRV_SECTOR_SIZE
;
1281 acb
->aio_iov
= qiov
->iov
;
1282 acb
->aio_niov
= qiov
->niov
;
1283 assert(qiov
->size
== acb
->aio_nbytes
);
1286 trace_paio_submit_co(sector_num
, nb_sectors
, type
);
1287 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1288 return thread_pool_submit_co(pool
, aio_worker
, acb
);
1291 static BlockAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
1292 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1293 BlockCompletionFunc
*cb
, void *opaque
, int type
)
1295 RawPosixAIOData
*acb
= g_new(RawPosixAIOData
, 1);
1299 acb
->aio_type
= type
;
1300 acb
->aio_fildes
= fd
;
1302 acb
->aio_nbytes
= nb_sectors
* BDRV_SECTOR_SIZE
;
1303 acb
->aio_offset
= sector_num
* BDRV_SECTOR_SIZE
;
1306 acb
->aio_iov
= qiov
->iov
;
1307 acb
->aio_niov
= qiov
->niov
;
1308 assert(qiov
->size
== acb
->aio_nbytes
);
1311 trace_paio_submit(acb
, opaque
, sector_num
, nb_sectors
, type
);
1312 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1313 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1316 static BlockAIOCB
*raw_aio_submit(BlockDriverState
*bs
,
1317 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1318 BlockCompletionFunc
*cb
, void *opaque
, int type
)
1320 BDRVRawState
*s
= bs
->opaque
;
1322 if (fd_open(bs
) < 0)
1326 * Check if the underlying device requires requests to be aligned,
1327 * and if the request we are trying to submit is aligned or not.
1328 * If this is the case tell the low-level driver that it needs
1329 * to copy the buffer.
1331 if (s
->needs_alignment
) {
1332 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1333 type
|= QEMU_AIO_MISALIGNED
;
1334 #ifdef CONFIG_LINUX_AIO
1335 } else if (s
->use_aio
) {
1336 return laio_submit(bs
, s
->aio_ctx
, s
->fd
, sector_num
, qiov
,
1337 nb_sectors
, cb
, opaque
, type
);
1342 return paio_submit(bs
, s
->fd
, sector_num
, qiov
, nb_sectors
,
1346 static void raw_aio_plug(BlockDriverState
*bs
)
1348 #ifdef CONFIG_LINUX_AIO
1349 BDRVRawState
*s
= bs
->opaque
;
1351 laio_io_plug(bs
, s
->aio_ctx
);
1356 static void raw_aio_unplug(BlockDriverState
*bs
)
1358 #ifdef CONFIG_LINUX_AIO
1359 BDRVRawState
*s
= bs
->opaque
;
1361 laio_io_unplug(bs
, s
->aio_ctx
, true);
1366 static void raw_aio_flush_io_queue(BlockDriverState
*bs
)
1368 #ifdef CONFIG_LINUX_AIO
1369 BDRVRawState
*s
= bs
->opaque
;
1371 laio_io_unplug(bs
, s
->aio_ctx
, false);
1376 static BlockAIOCB
*raw_aio_readv(BlockDriverState
*bs
,
1377 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1378 BlockCompletionFunc
*cb
, void *opaque
)
1380 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1381 cb
, opaque
, QEMU_AIO_READ
);
1384 static BlockAIOCB
*raw_aio_writev(BlockDriverState
*bs
,
1385 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1386 BlockCompletionFunc
*cb
, void *opaque
)
1388 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1389 cb
, opaque
, QEMU_AIO_WRITE
);
1392 static BlockAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1393 BlockCompletionFunc
*cb
, void *opaque
)
1395 BDRVRawState
*s
= bs
->opaque
;
1397 if (fd_open(bs
) < 0)
1400 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1403 static void raw_close(BlockDriverState
*bs
)
1405 BDRVRawState
*s
= bs
->opaque
;
1407 raw_detach_aio_context(bs
);
1409 #ifdef CONFIG_LINUX_AIO
1411 laio_cleanup(s
->aio_ctx
);
1420 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
1422 BDRVRawState
*s
= bs
->opaque
;
1425 if (fstat(s
->fd
, &st
)) {
1429 if (S_ISREG(st
.st_mode
)) {
1430 if (ftruncate(s
->fd
, offset
) < 0) {
1433 } else if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1434 if (offset
> raw_getlength(bs
)) {
1445 static int64_t raw_getlength(BlockDriverState
*bs
)
1447 BDRVRawState
*s
= bs
->opaque
;
1453 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1454 struct disklabel dl
;
1456 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1458 return (uint64_t)dl
.d_secsize
*
1459 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1463 #elif defined(__NetBSD__)
1464 static int64_t raw_getlength(BlockDriverState
*bs
)
1466 BDRVRawState
*s
= bs
->opaque
;
1472 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1473 struct dkwedge_info dkw
;
1475 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1476 return dkw
.dkw_size
* 512;
1478 struct disklabel dl
;
1480 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1482 return (uint64_t)dl
.d_secsize
*
1483 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1488 #elif defined(__sun__)
1489 static int64_t raw_getlength(BlockDriverState
*bs
)
1491 BDRVRawState
*s
= bs
->opaque
;
1492 struct dk_minfo minfo
;
1502 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1504 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1506 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1510 * There are reports that lseek on some devices fails, but
1511 * irc discussion said that contingency on contingency was overkill.
1513 size
= lseek(s
->fd
, 0, SEEK_END
);
1519 #elif defined(CONFIG_BSD)
1520 static int64_t raw_getlength(BlockDriverState
*bs
)
1522 BDRVRawState
*s
= bs
->opaque
;
1526 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1535 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1538 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1539 #ifdef DIOCGMEDIASIZE
1540 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1541 #elif defined(DIOCGPART)
1544 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1545 size
= pi
.media_size
;
1551 #if defined(__APPLE__) && defined(__MACH__)
1553 uint64_t sectors
= 0;
1554 uint32_t sector_size
= 0;
1556 if (ioctl(fd
, DKIOCGETBLOCKCOUNT
, §ors
) == 0
1557 && ioctl(fd
, DKIOCGETBLOCKSIZE
, §or_size
) == 0) {
1558 size
= sectors
* sector_size
;
1560 size
= lseek(fd
, 0LL, SEEK_END
);
1567 size
= lseek(fd
, 0LL, SEEK_END
);
1572 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1575 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1576 if (size
== 2048LL * (unsigned)-1)
1578 /* XXX no disc? maybe we need to reopen... */
1579 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1586 size
= lseek(fd
, 0, SEEK_END
);
1594 static int64_t raw_getlength(BlockDriverState
*bs
)
1596 BDRVRawState
*s
= bs
->opaque
;
1605 size
= lseek(s
->fd
, 0, SEEK_END
);
1613 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
1616 BDRVRawState
*s
= bs
->opaque
;
1618 if (fstat(s
->fd
, &st
) < 0) {
1621 return (int64_t)st
.st_blocks
* 512;
1624 static int raw_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1628 int64_t total_size
= 0;
1630 PreallocMode prealloc
;
1632 Error
*local_err
= NULL
;
1634 strstart(filename
, "file:", &filename
);
1636 /* Read out options */
1637 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1639 nocow
= qemu_opt_get_bool(opts
, BLOCK_OPT_NOCOW
, false);
1640 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
1641 prealloc
= qapi_enum_parse(PreallocMode_lookup
, buf
,
1642 PREALLOC_MODE_MAX
, PREALLOC_MODE_OFF
,
1646 error_propagate(errp
, local_err
);
1651 fd
= qemu_open(filename
, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
,
1655 error_setg_errno(errp
, -result
, "Could not create file");
1661 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1662 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1663 * will be ignored since any failure of this operation should not
1664 * block the left work.
1667 if (ioctl(fd
, FS_IOC_GETFLAGS
, &attr
) == 0) {
1668 attr
|= FS_NOCOW_FL
;
1669 ioctl(fd
, FS_IOC_SETFLAGS
, &attr
);
1674 if (ftruncate(fd
, total_size
) != 0) {
1676 error_setg_errno(errp
, -result
, "Could not resize file");
1681 #ifdef CONFIG_POSIX_FALLOCATE
1682 case PREALLOC_MODE_FALLOC
:
1683 /* posix_fallocate() doesn't set errno. */
1684 result
= -posix_fallocate(fd
, 0, total_size
);
1686 error_setg_errno(errp
, -result
,
1687 "Could not preallocate data for the new file");
1691 case PREALLOC_MODE_FULL
:
1693 int64_t num
= 0, left
= total_size
;
1694 buf
= g_malloc0(65536);
1697 num
= MIN(left
, 65536);
1698 result
= write(fd
, buf
, num
);
1701 error_setg_errno(errp
, -result
,
1702 "Could not write to the new file");
1711 error_setg_errno(errp
, -result
,
1712 "Could not flush new file to disk");
1718 case PREALLOC_MODE_OFF
:
1722 error_setg(errp
, "Unsupported preallocation mode: %s",
1723 PreallocMode_lookup
[prealloc
]);
1728 if (qemu_close(fd
) != 0 && result
== 0) {
1730 error_setg_errno(errp
, -result
, "Could not close the new file");
1737 * Find allocation range in @bs around offset @start.
1738 * May change underlying file descriptor's file offset.
1739 * If @start is not in a hole, store @start in @data, and the
1740 * beginning of the next hole in @hole, and return 0.
1741 * If @start is in a non-trailing hole, store @start in @hole and the
1742 * beginning of the next non-hole in @data, and return 0.
1743 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1744 * If we can't find out, return a negative errno other than -ENXIO.
1746 static int find_allocation(BlockDriverState
*bs
, off_t start
,
1747 off_t
*data
, off_t
*hole
)
1749 #if defined SEEK_HOLE && defined SEEK_DATA
1750 BDRVRawState
*s
= bs
->opaque
;
1755 * D1. offs == start: start is in data
1756 * D2. offs > start: start is in a hole, next data at offs
1757 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1758 * or start is beyond EOF
1759 * If the latter happens, the file has been truncated behind
1760 * our back since we opened it. All bets are off then.
1761 * Treating like a trailing hole is simplest.
1762 * D4. offs < 0, errno != ENXIO: we learned nothing
1764 offs
= lseek(s
->fd
, start
, SEEK_DATA
);
1766 return -errno
; /* D3 or D4 */
1768 assert(offs
>= start
);
1771 /* D2: in hole, next data at offs */
1777 /* D1: in data, end not yet known */
1781 * H1. offs == start: start is in a hole
1782 * If this happens here, a hole has been dug behind our back
1783 * since the previous lseek().
1784 * H2. offs > start: either start is in data, next hole at offs,
1785 * or start is in trailing hole, EOF at offs
1786 * Linux treats trailing holes like any other hole: offs ==
1787 * start. Solaris seeks to EOF instead: offs > start (blech).
1788 * If that happens here, a hole has been dug behind our back
1789 * since the previous lseek().
1790 * H3. offs < 0, errno = ENXIO: start is beyond EOF
1791 * If this happens, the file has been truncated behind our
1792 * back since we opened it. Treat it like a trailing hole.
1793 * H4. offs < 0, errno != ENXIO: we learned nothing
1794 * Pretend we know nothing at all, i.e. "forget" about D1.
1796 offs
= lseek(s
->fd
, start
, SEEK_HOLE
);
1798 return -errno
; /* D1 and (H3 or H4) */
1800 assert(offs
>= start
);
1804 * D1 and H2: either in data, next hole at offs, or it was in
1805 * data but is now in a trailing hole. In the latter case,
1806 * all bets are off. Treating it as if it there was data all
1807 * the way to EOF is safe, so simply do that.
1822 * Returns the allocation status of the specified sectors.
1824 * If 'sector_num' is beyond the end of the disk image the return value is 0
1825 * and 'pnum' is set to 0.
1827 * 'pnum' is set to the number of sectors (including and immediately following
1828 * the specified sector) that are known to be in the same
1829 * allocated/unallocated state.
1831 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1832 * beyond the end of the disk image it will be clamped.
1834 static int64_t coroutine_fn
raw_co_get_block_status(BlockDriverState
*bs
,
1836 int nb_sectors
, int *pnum
)
1838 off_t start
, data
= 0, hole
= 0;
1847 start
= sector_num
* BDRV_SECTOR_SIZE
;
1848 total_size
= bdrv_getlength(bs
);
1849 if (total_size
< 0) {
1851 } else if (start
>= total_size
) {
1854 } else if (start
+ nb_sectors
* BDRV_SECTOR_SIZE
> total_size
) {
1855 nb_sectors
= DIV_ROUND_UP(total_size
- start
, BDRV_SECTOR_SIZE
);
1858 ret
= find_allocation(bs
, start
, &data
, &hole
);
1859 if (ret
== -ENXIO
) {
1862 ret
= BDRV_BLOCK_ZERO
;
1863 } else if (ret
< 0) {
1864 /* No info available, so pretend there are no holes */
1866 ret
= BDRV_BLOCK_DATA
;
1867 } else if (data
== start
) {
1868 /* On a data extent, compute sectors to the end of the extent,
1869 * possibly including a partial sector at EOF. */
1870 *pnum
= MIN(nb_sectors
, DIV_ROUND_UP(hole
- start
, BDRV_SECTOR_SIZE
));
1871 ret
= BDRV_BLOCK_DATA
;
1873 /* On a hole, compute sectors to the beginning of the next extent. */
1874 assert(hole
== start
);
1875 *pnum
= MIN(nb_sectors
, (data
- start
) / BDRV_SECTOR_SIZE
);
1876 ret
= BDRV_BLOCK_ZERO
;
1878 return ret
| BDRV_BLOCK_OFFSET_VALID
| start
;
1881 static coroutine_fn BlockAIOCB
*raw_aio_discard(BlockDriverState
*bs
,
1882 int64_t sector_num
, int nb_sectors
,
1883 BlockCompletionFunc
*cb
, void *opaque
)
1885 BDRVRawState
*s
= bs
->opaque
;
1887 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1888 cb
, opaque
, QEMU_AIO_DISCARD
);
1891 static int coroutine_fn
raw_co_write_zeroes(
1892 BlockDriverState
*bs
, int64_t sector_num
,
1893 int nb_sectors
, BdrvRequestFlags flags
)
1895 BDRVRawState
*s
= bs
->opaque
;
1897 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1898 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1899 QEMU_AIO_WRITE_ZEROES
);
1900 } else if (s
->discard_zeroes
) {
1901 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1907 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1909 BDRVRawState
*s
= bs
->opaque
;
1911 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
1912 bdi
->can_write_zeroes_with_unmap
= s
->discard_zeroes
;
1916 static QemuOptsList raw_create_opts
= {
1917 .name
= "raw-create-opts",
1918 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
1921 .name
= BLOCK_OPT_SIZE
,
1922 .type
= QEMU_OPT_SIZE
,
1923 .help
= "Virtual disk size"
1926 .name
= BLOCK_OPT_NOCOW
,
1927 .type
= QEMU_OPT_BOOL
,
1928 .help
= "Turn off copy-on-write (valid only on btrfs)"
1931 .name
= BLOCK_OPT_PREALLOC
,
1932 .type
= QEMU_OPT_STRING
,
1933 .help
= "Preallocation mode (allowed values: off, falloc, full)"
1935 { /* end of list */ }
1939 BlockDriver bdrv_file
= {
1940 .format_name
= "file",
1941 .protocol_name
= "file",
1942 .instance_size
= sizeof(BDRVRawState
),
1943 .bdrv_needs_filename
= true,
1944 .bdrv_probe
= NULL
, /* no probe for protocols */
1945 .bdrv_parse_filename
= raw_parse_filename
,
1946 .bdrv_file_open
= raw_open
,
1947 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1948 .bdrv_reopen_commit
= raw_reopen_commit
,
1949 .bdrv_reopen_abort
= raw_reopen_abort
,
1950 .bdrv_close
= raw_close
,
1951 .bdrv_create
= raw_create
,
1952 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
1953 .bdrv_co_get_block_status
= raw_co_get_block_status
,
1954 .bdrv_co_write_zeroes
= raw_co_write_zeroes
,
1956 .bdrv_aio_readv
= raw_aio_readv
,
1957 .bdrv_aio_writev
= raw_aio_writev
,
1958 .bdrv_aio_flush
= raw_aio_flush
,
1959 .bdrv_aio_discard
= raw_aio_discard
,
1960 .bdrv_refresh_limits
= raw_refresh_limits
,
1961 .bdrv_io_plug
= raw_aio_plug
,
1962 .bdrv_io_unplug
= raw_aio_unplug
,
1963 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
1965 .bdrv_truncate
= raw_truncate
,
1966 .bdrv_getlength
= raw_getlength
,
1967 .bdrv_get_info
= raw_get_info
,
1968 .bdrv_get_allocated_file_size
1969 = raw_get_allocated_file_size
,
1971 .bdrv_detach_aio_context
= raw_detach_aio_context
,
1972 .bdrv_attach_aio_context
= raw_attach_aio_context
,
1974 .create_opts
= &raw_create_opts
,
1977 /***********************************************/
1980 #if defined(__APPLE__) && defined(__MACH__)
1981 static kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
);
1982 static kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
);
1984 kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
)
1986 kern_return_t kernResult
;
1987 mach_port_t masterPort
;
1988 CFMutableDictionaryRef classesToMatch
;
1990 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
1991 if ( KERN_SUCCESS
!= kernResult
) {
1992 printf( "IOMasterPort returned %d\n", kernResult
);
1995 classesToMatch
= IOServiceMatching( kIOCDMediaClass
);
1996 if ( classesToMatch
== NULL
) {
1997 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1999 CFDictionarySetValue( classesToMatch
, CFSTR( kIOMediaEjectableKey
), kCFBooleanTrue
);
2001 kernResult
= IOServiceGetMatchingServices( masterPort
, classesToMatch
, mediaIterator
);
2002 if ( KERN_SUCCESS
!= kernResult
)
2004 printf( "IOServiceGetMatchingServices returned %d\n", kernResult
);
2010 kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
)
2012 io_object_t nextMedia
;
2013 kern_return_t kernResult
= KERN_FAILURE
;
2015 nextMedia
= IOIteratorNext( mediaIterator
);
2018 CFTypeRef bsdPathAsCFString
;
2019 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
2020 if ( bsdPathAsCFString
) {
2021 size_t devPathLength
;
2022 strcpy( bsdPath
, _PATH_DEV
);
2023 strcat( bsdPath
, "r" );
2024 devPathLength
= strlen( bsdPath
);
2025 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
2026 kernResult
= KERN_SUCCESS
;
2028 CFRelease( bsdPathAsCFString
);
2030 IOObjectRelease( nextMedia
);
2038 static int hdev_probe_device(const char *filename
)
2042 /* allow a dedicated CD-ROM driver to match with a higher priority */
2043 if (strstart(filename
, "/dev/cdrom", NULL
))
2046 if (stat(filename
, &st
) >= 0 &&
2047 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
2054 static int check_hdev_writable(BDRVRawState
*s
)
2056 #if defined(BLKROGET)
2057 /* Linux block devices can be configured "read-only" using blockdev(8).
2058 * This is independent of device node permissions and therefore open(2)
2059 * with O_RDWR succeeds. Actual writes fail with EPERM.
2061 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
2062 * check for read-only block devices so that Linux block devices behave
2068 if (fstat(s
->fd
, &st
)) {
2072 if (!S_ISBLK(st
.st_mode
)) {
2076 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
2083 #endif /* defined(BLKROGET) */
2087 static void hdev_parse_filename(const char *filename
, QDict
*options
,
2090 /* The prefix is optional, just as for "file". */
2091 strstart(filename
, "host_device:", &filename
);
2093 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2096 static bool hdev_is_sg(BlockDriverState
*bs
)
2099 #if defined(__linux__)
2102 struct sg_scsi_id scsiid
;
2105 if (stat(bs
->filename
, &st
) >= 0 && S_ISCHR(st
.st_mode
) &&
2106 !bdrv_ioctl(bs
, SG_GET_VERSION_NUM
, &sg_version
) &&
2107 !bdrv_ioctl(bs
, SG_GET_SCSI_ID
, &scsiid
)) {
2108 DPRINTF("SG device found: type=%d, version=%d\n",
2109 scsiid
.scsi_type
, sg_version
);
2118 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2121 BDRVRawState
*s
= bs
->opaque
;
2122 Error
*local_err
= NULL
;
2125 #if defined(__APPLE__) && defined(__MACH__)
2126 const char *filename
= qdict_get_str(options
, "filename");
2128 if (strstart(filename
, "/dev/cdrom", NULL
)) {
2129 kern_return_t kernResult
;
2130 io_iterator_t mediaIterator
;
2131 char bsdPath
[ MAXPATHLEN
];
2134 kernResult
= FindEjectableCDMedia( &mediaIterator
);
2135 kernResult
= GetBSDPath( mediaIterator
, bsdPath
, sizeof( bsdPath
) );
2137 if ( bsdPath
[ 0 ] != '\0' ) {
2138 strcat(bsdPath
,"s0");
2139 /* some CDs don't have a partition 0 */
2140 fd
= qemu_open(bsdPath
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
2142 bsdPath
[strlen(bsdPath
)-1] = '1';
2147 qdict_put(options
, "filename", qstring_from_str(filename
));
2150 if ( mediaIterator
)
2151 IOObjectRelease( mediaIterator
);
2155 s
->type
= FTYPE_FILE
;
2157 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2160 error_propagate(errp
, local_err
);
2165 /* Since this does ioctl the device must be already opened */
2166 bs
->sg
= hdev_is_sg(bs
);
2168 if (flags
& BDRV_O_RDWR
) {
2169 ret
= check_hdev_writable(s
);
2172 error_setg_errno(errp
, -ret
, "The device is not writable");
2180 #if defined(__linux__)
2181 /* Note: we do not have a reliable method to detect if the floppy is
2182 present. The current method is to try to open the floppy at every
2183 I/O and to keep it opened during a few hundreds of ms. */
2184 static int fd_open(BlockDriverState
*bs
)
2186 BDRVRawState
*s
= bs
->opaque
;
2187 int last_media_present
;
2189 if (s
->type
!= FTYPE_FD
)
2191 last_media_present
= (s
->fd
>= 0);
2193 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) - s
->fd_open_time
) >= FD_OPEN_TIMEOUT
) {
2196 DPRINTF("Floppy closed\n");
2199 if (s
->fd_got_error
&&
2200 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) - s
->fd_error_time
) < FD_OPEN_TIMEOUT
) {
2201 DPRINTF("No floppy (open delayed)\n");
2204 s
->fd
= qemu_open(bs
->filename
, s
->open_flags
& ~O_NONBLOCK
);
2206 s
->fd_error_time
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
2207 s
->fd_got_error
= 1;
2208 if (last_media_present
)
2209 s
->fd_media_changed
= 1;
2210 DPRINTF("No floppy\n");
2213 DPRINTF("Floppy opened\n");
2215 if (!last_media_present
)
2216 s
->fd_media_changed
= 1;
2217 s
->fd_open_time
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
2218 s
->fd_got_error
= 0;
2222 static int hdev_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
2224 BDRVRawState
*s
= bs
->opaque
;
2226 return ioctl(s
->fd
, req
, buf
);
2229 static BlockAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
2230 unsigned long int req
, void *buf
,
2231 BlockCompletionFunc
*cb
, void *opaque
)
2233 BDRVRawState
*s
= bs
->opaque
;
2234 RawPosixAIOData
*acb
;
2237 if (fd_open(bs
) < 0)
2240 acb
= g_new(RawPosixAIOData
, 1);
2242 acb
->aio_type
= QEMU_AIO_IOCTL
;
2243 acb
->aio_fildes
= s
->fd
;
2244 acb
->aio_offset
= 0;
2245 acb
->aio_ioctl_buf
= buf
;
2246 acb
->aio_ioctl_cmd
= req
;
2247 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
2248 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
2251 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2252 static int fd_open(BlockDriverState
*bs
)
2254 BDRVRawState
*s
= bs
->opaque
;
2256 /* this is just to ensure s->fd is sane (its called by io ops) */
2261 #else /* !linux && !FreeBSD */
2263 static int fd_open(BlockDriverState
*bs
)
2268 #endif /* !linux && !FreeBSD */
2270 static coroutine_fn BlockAIOCB
*hdev_aio_discard(BlockDriverState
*bs
,
2271 int64_t sector_num
, int nb_sectors
,
2272 BlockCompletionFunc
*cb
, void *opaque
)
2274 BDRVRawState
*s
= bs
->opaque
;
2276 if (fd_open(bs
) < 0) {
2279 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
2280 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2283 static coroutine_fn
int hdev_co_write_zeroes(BlockDriverState
*bs
,
2284 int64_t sector_num
, int nb_sectors
, BdrvRequestFlags flags
)
2286 BDRVRawState
*s
= bs
->opaque
;
2293 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
2294 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
2295 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
2296 } else if (s
->discard_zeroes
) {
2297 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
2298 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2303 static int hdev_create(const char *filename
, QemuOpts
*opts
,
2308 struct stat stat_buf
;
2309 int64_t total_size
= 0;
2312 /* This function is used by all three protocol block drivers and therefore
2313 * any of these three prefixes may be given.
2314 * The return value has to be stored somewhere, otherwise this is an error
2315 * due to -Werror=unused-value. */
2317 strstart(filename
, "host_device:", &filename
) ||
2318 strstart(filename
, "host_cdrom:" , &filename
) ||
2319 strstart(filename
, "host_floppy:", &filename
);
2323 ret
= raw_normalize_devicepath(&filename
);
2325 error_setg_errno(errp
, -ret
, "Could not normalize device path");
2329 /* Read out options */
2330 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2333 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
2336 error_setg_errno(errp
, -ret
, "Could not open device");
2340 if (fstat(fd
, &stat_buf
) < 0) {
2342 error_setg_errno(errp
, -ret
, "Could not stat device");
2343 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
2345 "The given file is neither a block nor a character device");
2347 } else if (lseek(fd
, 0, SEEK_END
) < total_size
) {
2348 error_setg(errp
, "Device is too small");
2356 static BlockDriver bdrv_host_device
= {
2357 .format_name
= "host_device",
2358 .protocol_name
= "host_device",
2359 .instance_size
= sizeof(BDRVRawState
),
2360 .bdrv_needs_filename
= true,
2361 .bdrv_probe_device
= hdev_probe_device
,
2362 .bdrv_parse_filename
= hdev_parse_filename
,
2363 .bdrv_file_open
= hdev_open
,
2364 .bdrv_close
= raw_close
,
2365 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2366 .bdrv_reopen_commit
= raw_reopen_commit
,
2367 .bdrv_reopen_abort
= raw_reopen_abort
,
2368 .bdrv_create
= hdev_create
,
2369 .create_opts
= &raw_create_opts
,
2370 .bdrv_co_write_zeroes
= hdev_co_write_zeroes
,
2372 .bdrv_aio_readv
= raw_aio_readv
,
2373 .bdrv_aio_writev
= raw_aio_writev
,
2374 .bdrv_aio_flush
= raw_aio_flush
,
2375 .bdrv_aio_discard
= hdev_aio_discard
,
2376 .bdrv_refresh_limits
= raw_refresh_limits
,
2377 .bdrv_io_plug
= raw_aio_plug
,
2378 .bdrv_io_unplug
= raw_aio_unplug
,
2379 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2381 .bdrv_truncate
= raw_truncate
,
2382 .bdrv_getlength
= raw_getlength
,
2383 .bdrv_get_info
= raw_get_info
,
2384 .bdrv_get_allocated_file_size
2385 = raw_get_allocated_file_size
,
2386 .bdrv_probe_blocksizes
= hdev_probe_blocksizes
,
2387 .bdrv_probe_geometry
= hdev_probe_geometry
,
2389 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2390 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2392 /* generic scsi device */
2394 .bdrv_ioctl
= hdev_ioctl
,
2395 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2400 static void floppy_parse_filename(const char *filename
, QDict
*options
,
2403 /* The prefix is optional, just as for "file". */
2404 strstart(filename
, "host_floppy:", &filename
);
2406 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2409 static int floppy_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2412 BDRVRawState
*s
= bs
->opaque
;
2413 Error
*local_err
= NULL
;
2418 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2419 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2422 error_propagate(errp
, local_err
);
2427 /* close fd so that we can reopen it as needed */
2430 s
->fd_media_changed
= 1;
2432 error_report("Host floppy pass-through is deprecated");
2433 error_printf("Support for it will be removed in a future release.\n");
2437 static int floppy_probe_device(const char *filename
)
2441 struct floppy_struct fdparam
;
2444 if (strstart(filename
, "/dev/fd", NULL
) &&
2445 !strstart(filename
, "/dev/fdset/", NULL
) &&
2446 !strstart(filename
, "/dev/fd/", NULL
)) {
2450 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2454 ret
= fstat(fd
, &st
);
2455 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2459 /* Attempt to detect via a floppy specific ioctl */
2460 ret
= ioctl(fd
, FDGETPRM
, &fdparam
);
2471 static int floppy_is_inserted(BlockDriverState
*bs
)
2473 return fd_open(bs
) >= 0;
2476 static int floppy_media_changed(BlockDriverState
*bs
)
2478 BDRVRawState
*s
= bs
->opaque
;
2482 * XXX: we do not have a true media changed indication.
2483 * It does not work if the floppy is changed without trying to read it.
2486 ret
= s
->fd_media_changed
;
2487 s
->fd_media_changed
= 0;
2488 DPRINTF("Floppy changed=%d\n", ret
);
2492 static void floppy_eject(BlockDriverState
*bs
, bool eject_flag
)
2494 BDRVRawState
*s
= bs
->opaque
;
2501 fd
= qemu_open(bs
->filename
, s
->open_flags
| O_NONBLOCK
);
2503 if (ioctl(fd
, FDEJECT
, 0) < 0)
2509 static BlockDriver bdrv_host_floppy
= {
2510 .format_name
= "host_floppy",
2511 .protocol_name
= "host_floppy",
2512 .instance_size
= sizeof(BDRVRawState
),
2513 .bdrv_needs_filename
= true,
2514 .bdrv_probe_device
= floppy_probe_device
,
2515 .bdrv_parse_filename
= floppy_parse_filename
,
2516 .bdrv_file_open
= floppy_open
,
2517 .bdrv_close
= raw_close
,
2518 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2519 .bdrv_reopen_commit
= raw_reopen_commit
,
2520 .bdrv_reopen_abort
= raw_reopen_abort
,
2521 .bdrv_create
= hdev_create
,
2522 .create_opts
= &raw_create_opts
,
2524 .bdrv_aio_readv
= raw_aio_readv
,
2525 .bdrv_aio_writev
= raw_aio_writev
,
2526 .bdrv_aio_flush
= raw_aio_flush
,
2527 .bdrv_refresh_limits
= raw_refresh_limits
,
2528 .bdrv_io_plug
= raw_aio_plug
,
2529 .bdrv_io_unplug
= raw_aio_unplug
,
2530 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2532 .bdrv_truncate
= raw_truncate
,
2533 .bdrv_getlength
= raw_getlength
,
2534 .has_variable_length
= true,
2535 .bdrv_get_allocated_file_size
2536 = raw_get_allocated_file_size
,
2538 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2539 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2541 /* removable device support */
2542 .bdrv_is_inserted
= floppy_is_inserted
,
2543 .bdrv_media_changed
= floppy_media_changed
,
2544 .bdrv_eject
= floppy_eject
,
2548 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2549 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2552 /* The prefix is optional, just as for "file". */
2553 strstart(filename
, "host_cdrom:", &filename
);
2555 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2560 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2563 BDRVRawState
*s
= bs
->opaque
;
2564 Error
*local_err
= NULL
;
2569 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2570 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2572 error_propagate(errp
, local_err
);
2577 static int cdrom_probe_device(const char *filename
)
2583 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2587 ret
= fstat(fd
, &st
);
2588 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2592 /* Attempt to detect via a CDROM specific ioctl */
2593 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2603 static int cdrom_is_inserted(BlockDriverState
*bs
)
2605 BDRVRawState
*s
= bs
->opaque
;
2608 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2609 if (ret
== CDS_DISC_OK
)
2614 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2616 BDRVRawState
*s
= bs
->opaque
;
2619 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2620 perror("CDROMEJECT");
2622 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2623 perror("CDROMEJECT");
2627 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2629 BDRVRawState
*s
= bs
->opaque
;
2631 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2633 * Note: an error can happen if the distribution automatically
2636 /* perror("CDROM_LOCKDOOR"); */
2640 static BlockDriver bdrv_host_cdrom
= {
2641 .format_name
= "host_cdrom",
2642 .protocol_name
= "host_cdrom",
2643 .instance_size
= sizeof(BDRVRawState
),
2644 .bdrv_needs_filename
= true,
2645 .bdrv_probe_device
= cdrom_probe_device
,
2646 .bdrv_parse_filename
= cdrom_parse_filename
,
2647 .bdrv_file_open
= cdrom_open
,
2648 .bdrv_close
= raw_close
,
2649 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2650 .bdrv_reopen_commit
= raw_reopen_commit
,
2651 .bdrv_reopen_abort
= raw_reopen_abort
,
2652 .bdrv_create
= hdev_create
,
2653 .create_opts
= &raw_create_opts
,
2655 .bdrv_aio_readv
= raw_aio_readv
,
2656 .bdrv_aio_writev
= raw_aio_writev
,
2657 .bdrv_aio_flush
= raw_aio_flush
,
2658 .bdrv_refresh_limits
= raw_refresh_limits
,
2659 .bdrv_io_plug
= raw_aio_plug
,
2660 .bdrv_io_unplug
= raw_aio_unplug
,
2661 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2663 .bdrv_truncate
= raw_truncate
,
2664 .bdrv_getlength
= raw_getlength
,
2665 .has_variable_length
= true,
2666 .bdrv_get_allocated_file_size
2667 = raw_get_allocated_file_size
,
2669 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2670 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2672 /* removable device support */
2673 .bdrv_is_inserted
= cdrom_is_inserted
,
2674 .bdrv_eject
= cdrom_eject
,
2675 .bdrv_lock_medium
= cdrom_lock_medium
,
2677 /* generic scsi device */
2678 .bdrv_ioctl
= hdev_ioctl
,
2679 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2681 #endif /* __linux__ */
2683 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2684 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2687 BDRVRawState
*s
= bs
->opaque
;
2688 Error
*local_err
= NULL
;
2693 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2696 error_propagate(errp
, local_err
);
2701 /* make sure the door isn't locked at this time */
2702 ioctl(s
->fd
, CDIOCALLOW
);
2706 static int cdrom_probe_device(const char *filename
)
2708 if (strstart(filename
, "/dev/cd", NULL
) ||
2709 strstart(filename
, "/dev/acd", NULL
))
2714 static int cdrom_reopen(BlockDriverState
*bs
)
2716 BDRVRawState
*s
= bs
->opaque
;
2720 * Force reread of possibly changed/newly loaded disc,
2721 * FreeBSD seems to not notice sometimes...
2725 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
2732 /* make sure the door isn't locked at this time */
2733 ioctl(s
->fd
, CDIOCALLOW
);
2737 static int cdrom_is_inserted(BlockDriverState
*bs
)
2739 return raw_getlength(bs
) > 0;
2742 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2744 BDRVRawState
*s
= bs
->opaque
;
2749 (void) ioctl(s
->fd
, CDIOCALLOW
);
2752 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
2753 perror("CDIOCEJECT");
2755 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
2756 perror("CDIOCCLOSE");
2762 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2764 BDRVRawState
*s
= bs
->opaque
;
2768 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
2770 * Note: an error can happen if the distribution automatically
2773 /* perror("CDROM_LOCKDOOR"); */
2777 static BlockDriver bdrv_host_cdrom
= {
2778 .format_name
= "host_cdrom",
2779 .protocol_name
= "host_cdrom",
2780 .instance_size
= sizeof(BDRVRawState
),
2781 .bdrv_needs_filename
= true,
2782 .bdrv_probe_device
= cdrom_probe_device
,
2783 .bdrv_parse_filename
= cdrom_parse_filename
,
2784 .bdrv_file_open
= cdrom_open
,
2785 .bdrv_close
= raw_close
,
2786 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2787 .bdrv_reopen_commit
= raw_reopen_commit
,
2788 .bdrv_reopen_abort
= raw_reopen_abort
,
2789 .bdrv_create
= hdev_create
,
2790 .create_opts
= &raw_create_opts
,
2792 .bdrv_aio_readv
= raw_aio_readv
,
2793 .bdrv_aio_writev
= raw_aio_writev
,
2794 .bdrv_aio_flush
= raw_aio_flush
,
2795 .bdrv_refresh_limits
= raw_refresh_limits
,
2796 .bdrv_io_plug
= raw_aio_plug
,
2797 .bdrv_io_unplug
= raw_aio_unplug
,
2798 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2800 .bdrv_truncate
= raw_truncate
,
2801 .bdrv_getlength
= raw_getlength
,
2802 .has_variable_length
= true,
2803 .bdrv_get_allocated_file_size
2804 = raw_get_allocated_file_size
,
2806 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2807 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2809 /* removable device support */
2810 .bdrv_is_inserted
= cdrom_is_inserted
,
2811 .bdrv_eject
= cdrom_eject
,
2812 .bdrv_lock_medium
= cdrom_lock_medium
,
2814 #endif /* __FreeBSD__ */
2816 static void bdrv_file_init(void)
2819 * Register all the drivers. Note that order is important, the driver
2820 * registered last will get probed first.
2822 bdrv_register(&bdrv_file
);
2823 bdrv_register(&bdrv_host_device
);
2825 bdrv_register(&bdrv_host_floppy
);
2826 bdrv_register(&bdrv_host_cdrom
);
2828 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2829 bdrv_register(&bdrv_host_cdrom
);
2833 block_init(bdrv_file_init
);