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/timer.h"
27 #include "block/block_int.h"
28 #include "qemu/module.h"
30 #include "block/thread-pool.h"
33 #include "qapi/util.h"
35 #if defined(__APPLE__) && (__MACH__)
37 #include <sys/param.h>
38 #include <IOKit/IOKitLib.h>
39 #include <IOKit/IOBSD.h>
40 #include <IOKit/storage/IOMediaBSDClient.h>
41 #include <IOKit/storage/IOMedia.h>
42 #include <IOKit/storage/IOCDMedia.h>
43 //#include <IOKit/storage/IOCDTypes.h>
44 #include <CoreFoundation/CoreFoundation.h>
48 #define _POSIX_PTHREAD_SEMANTICS 1
52 #include <sys/types.h>
54 #include <sys/ioctl.h>
55 #include <sys/param.h>
56 #include <linux/cdrom.h>
59 #include <linux/hdreg.h>
64 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
67 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
68 #include <linux/falloc.h>
70 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
76 #include <sys/ioctl.h>
77 #include <sys/disklabel.h>
82 #include <sys/ioctl.h>
83 #include <sys/disklabel.h>
89 #include <sys/ioctl.h>
90 #include <sys/diskslice.h>
97 //#define DEBUG_FLOPPY
100 #if defined(DEBUG_BLOCK)
101 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
102 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
104 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
107 /* OS X does not have O_DSYNC */
110 #define O_DSYNC O_SYNC
111 #elif defined(O_FSYNC)
112 #define O_DSYNC O_FSYNC
116 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
118 #define O_DIRECT O_DSYNC
125 /* if the FD is not accessed during that time (in ns), we try to
126 reopen it to see if the disk has been changed */
127 #define FD_OPEN_TIMEOUT (1000000000)
129 #define MAX_BLOCKSIZE 4096
131 typedef struct BDRVRawState
{
137 #if defined(__linux__)
138 /* linux floppy specific */
139 int64_t fd_open_time
;
140 int64_t fd_error_time
;
142 int fd_media_changed
;
144 #ifdef CONFIG_LINUX_AIO
152 bool has_write_zeroes
:1;
153 bool discard_zeroes
:1;
155 bool needs_alignment
;
158 typedef struct BDRVRawReopenState
{
161 #ifdef CONFIG_LINUX_AIO
164 } BDRVRawReopenState
;
166 static int fd_open(BlockDriverState
*bs
);
167 static int64_t raw_getlength(BlockDriverState
*bs
);
169 typedef struct RawPosixAIOData
{
170 BlockDriverState
*bs
;
173 struct iovec
*aio_iov
;
178 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
183 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
184 static int cdrom_reopen(BlockDriverState
*bs
);
187 #if defined(__NetBSD__)
188 static int raw_normalize_devicepath(const char **filename
)
190 static char namebuf
[PATH_MAX
];
191 const char *dp
, *fname
;
195 dp
= strrchr(fname
, '/');
196 if (lstat(fname
, &sb
) < 0) {
197 fprintf(stderr
, "%s: stat failed: %s\n",
198 fname
, strerror(errno
));
202 if (!S_ISBLK(sb
.st_mode
)) {
207 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
209 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
210 (int)(dp
- fname
), fname
, dp
+ 1);
212 fprintf(stderr
, "%s is a block device", fname
);
214 fprintf(stderr
, ", using %s\n", *filename
);
219 static int raw_normalize_devicepath(const char **filename
)
226 * Get logical block size via ioctl. On success store it in @sector_size_p.
228 static int probe_logical_blocksize(int fd
, unsigned int *sector_size_p
)
230 unsigned int sector_size
;
231 bool success
= false;
235 /* Try a few ioctls to get the right size */
237 if (ioctl(fd
, BLKSSZGET
, §or_size
) >= 0) {
238 *sector_size_p
= sector_size
;
242 #ifdef DKIOCGETBLOCKSIZE
243 if (ioctl(fd
, DKIOCGETBLOCKSIZE
, §or_size
) >= 0) {
244 *sector_size_p
= sector_size
;
248 #ifdef DIOCGSECTORSIZE
249 if (ioctl(fd
, DIOCGSECTORSIZE
, §or_size
) >= 0) {
250 *sector_size_p
= sector_size
;
255 return success
? 0 : -errno
;
259 * Get physical block size of @fd.
260 * On success, store it in @blk_size and return 0.
261 * On failure, return -errno.
263 static int probe_physical_blocksize(int fd
, unsigned int *blk_size
)
266 if (ioctl(fd
, BLKPBSZGET
, blk_size
) < 0) {
275 /* Check if read is allowed with given memory buffer and length.
277 * This function is used to check O_DIRECT memory buffer and request alignment.
279 static bool raw_is_io_aligned(int fd
, void *buf
, size_t len
)
281 ssize_t ret
= pread(fd
, buf
, len
, 0);
288 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
289 * other errors (e.g. real I/O error), which could happen on a failed
290 * drive, since we only care about probing alignment.
292 if (errno
!= EINVAL
) {
300 static void raw_probe_alignment(BlockDriverState
*bs
, int fd
, Error
**errp
)
302 BDRVRawState
*s
= bs
->opaque
;
304 size_t max_align
= MAX(MAX_BLOCKSIZE
, getpagesize());
306 /* For /dev/sg devices the alignment is not really used.
307 With buffered I/O, we don't have any restrictions. */
308 if (bs
->sg
|| !s
->needs_alignment
) {
309 bs
->request_alignment
= 1;
314 bs
->request_alignment
= 0;
316 /* Let's try to use the logical blocksize for the alignment. */
317 if (probe_logical_blocksize(fd
, &bs
->request_alignment
) < 0) {
318 bs
->request_alignment
= 0;
323 if (xfsctl(NULL
, fd
, XFS_IOC_DIOINFO
, &da
) >= 0) {
324 bs
->request_alignment
= da
.d_miniosz
;
325 /* The kernel returns wrong information for d_mem */
326 /* s->buf_align = da.d_mem; */
331 /* If we could not get the sizes so far, we can only guess them */
334 buf
= qemu_memalign(max_align
, 2 * max_align
);
335 for (align
= 512; align
<= max_align
; align
<<= 1) {
336 if (raw_is_io_aligned(fd
, buf
+ align
, max_align
)) {
337 s
->buf_align
= align
;
344 if (!bs
->request_alignment
) {
346 buf
= qemu_memalign(s
->buf_align
, max_align
);
347 for (align
= 512; align
<= max_align
; align
<<= 1) {
348 if (raw_is_io_aligned(fd
, buf
, align
)) {
349 bs
->request_alignment
= align
;
356 if (!s
->buf_align
|| !bs
->request_alignment
) {
357 error_setg(errp
, "Could not find working O_DIRECT alignment. "
358 "Try cache.direct=off.");
362 static void raw_parse_flags(int bdrv_flags
, int *open_flags
)
364 assert(open_flags
!= NULL
);
366 *open_flags
|= O_BINARY
;
367 *open_flags
&= ~O_ACCMODE
;
368 if (bdrv_flags
& BDRV_O_RDWR
) {
369 *open_flags
|= O_RDWR
;
371 *open_flags
|= O_RDONLY
;
374 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
375 * and O_DIRECT for no caching. */
376 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
377 *open_flags
|= O_DIRECT
;
381 static void raw_detach_aio_context(BlockDriverState
*bs
)
383 #ifdef CONFIG_LINUX_AIO
384 BDRVRawState
*s
= bs
->opaque
;
387 laio_detach_aio_context(s
->aio_ctx
, bdrv_get_aio_context(bs
));
392 static void raw_attach_aio_context(BlockDriverState
*bs
,
393 AioContext
*new_context
)
395 #ifdef CONFIG_LINUX_AIO
396 BDRVRawState
*s
= bs
->opaque
;
399 laio_attach_aio_context(s
->aio_ctx
, new_context
);
404 #ifdef CONFIG_LINUX_AIO
405 static int raw_set_aio(void **aio_ctx
, int *use_aio
, int bdrv_flags
)
408 assert(aio_ctx
!= NULL
);
409 assert(use_aio
!= NULL
);
411 * Currently Linux do AIO only for files opened with O_DIRECT
412 * specified so check NOCACHE flag too
414 if ((bdrv_flags
& (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) ==
415 (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) {
417 /* if non-NULL, laio_init() has already been run */
418 if (*aio_ctx
== NULL
) {
419 *aio_ctx
= laio_init();
436 static void raw_parse_filename(const char *filename
, QDict
*options
,
439 /* The filename does not have to be prefixed by the protocol name, since
440 * "file" is the default protocol; therefore, the return value of this
441 * function call can be ignored. */
442 strstart(filename
, "file:", &filename
);
444 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
447 static QemuOptsList raw_runtime_opts
= {
449 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
453 .type
= QEMU_OPT_STRING
,
454 .help
= "File name of the image",
456 { /* end of list */ }
460 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
461 int bdrv_flags
, int open_flags
, Error
**errp
)
463 BDRVRawState
*s
= bs
->opaque
;
465 Error
*local_err
= NULL
;
466 const char *filename
= NULL
;
470 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
471 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
473 error_propagate(errp
, local_err
);
478 filename
= qemu_opt_get(opts
, "filename");
480 ret
= raw_normalize_devicepath(&filename
);
482 error_setg_errno(errp
, -ret
, "Could not normalize device path");
486 s
->open_flags
= open_flags
;
487 raw_parse_flags(bdrv_flags
, &s
->open_flags
);
490 fd
= qemu_open(filename
, s
->open_flags
, 0644);
500 #ifdef CONFIG_LINUX_AIO
501 if (raw_set_aio(&s
->aio_ctx
, &s
->use_aio
, bdrv_flags
)) {
504 error_setg_errno(errp
, -ret
, "Could not set AIO state");
507 if (!s
->use_aio
&& (bdrv_flags
& BDRV_O_NATIVE_AIO
)) {
508 error_printf("WARNING: aio=native was specified for '%s', but "
509 "it requires cache.direct=on, which was not "
510 "specified. Falling back to aio=threads.\n"
511 " This will become an error condition in "
512 "future QEMU versions.\n",
517 s
->has_discard
= true;
518 s
->has_write_zeroes
= true;
519 if ((bs
->open_flags
& BDRV_O_NOCACHE
) != 0) {
520 s
->needs_alignment
= true;
523 if (fstat(s
->fd
, &st
) < 0) {
525 error_setg_errno(errp
, errno
, "Could not stat file");
528 if (S_ISREG(st
.st_mode
)) {
529 s
->discard_zeroes
= true;
530 s
->has_fallocate
= true;
532 if (S_ISBLK(st
.st_mode
)) {
533 #ifdef BLKDISCARDZEROES
535 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
536 s
->discard_zeroes
= true;
540 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
541 * not rely on the contents of discarded blocks unless using O_DIRECT.
542 * Same for BLKZEROOUT.
544 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
545 s
->discard_zeroes
= false;
546 s
->has_write_zeroes
= false;
551 if (S_ISCHR(st
.st_mode
)) {
553 * The file is a char device (disk), which on FreeBSD isn't behind
554 * a pager, so force all requests to be aligned. This is needed
555 * so QEMU makes sure all IO operations on the device are aligned
556 * to sector size, or else FreeBSD will reject them with EINVAL.
558 s
->needs_alignment
= true;
563 if (platform_test_xfs_fd(s
->fd
)) {
568 raw_attach_aio_context(bs
, bdrv_get_aio_context(bs
));
572 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
579 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
582 BDRVRawState
*s
= bs
->opaque
;
583 Error
*local_err
= NULL
;
586 s
->type
= FTYPE_FILE
;
587 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
589 error_propagate(errp
, local_err
);
594 static int raw_reopen_prepare(BDRVReopenState
*state
,
595 BlockReopenQueue
*queue
, Error
**errp
)
598 BDRVRawReopenState
*raw_s
;
600 Error
*local_err
= NULL
;
602 assert(state
!= NULL
);
603 assert(state
->bs
!= NULL
);
605 s
= state
->bs
->opaque
;
607 state
->opaque
= g_new0(BDRVRawReopenState
, 1);
608 raw_s
= state
->opaque
;
610 #ifdef CONFIG_LINUX_AIO
611 raw_s
->use_aio
= s
->use_aio
;
613 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
614 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
615 * won't override aio_ctx if aio_ctx is non-NULL */
616 if (raw_set_aio(&s
->aio_ctx
, &raw_s
->use_aio
, state
->flags
)) {
617 error_setg(errp
, "Could not set AIO state");
622 if (s
->type
== FTYPE_FD
|| s
->type
== FTYPE_CD
) {
623 raw_s
->open_flags
|= O_NONBLOCK
;
626 raw_parse_flags(state
->flags
, &raw_s
->open_flags
);
630 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
632 fcntl_flags
|= O_NOATIME
;
636 /* Not all operating systems have O_ASYNC, and those that don't
637 * will not let us track the state into raw_s->open_flags (typically
638 * you achieve the same effect with an ioctl, for example I_SETSIG
639 * on Solaris). But we do not use O_ASYNC, so that's fine.
641 assert((s
->open_flags
& O_ASYNC
) == 0);
644 if ((raw_s
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
645 /* dup the original fd */
646 /* TODO: use qemu fcntl wrapper */
647 #ifdef F_DUPFD_CLOEXEC
648 raw_s
->fd
= fcntl(s
->fd
, F_DUPFD_CLOEXEC
, 0);
650 raw_s
->fd
= dup(s
->fd
);
651 if (raw_s
->fd
!= -1) {
652 qemu_set_cloexec(raw_s
->fd
);
655 if (raw_s
->fd
>= 0) {
656 ret
= fcntl_setfl(raw_s
->fd
, raw_s
->open_flags
);
658 qemu_close(raw_s
->fd
);
664 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
665 if (raw_s
->fd
== -1) {
666 assert(!(raw_s
->open_flags
& O_CREAT
));
667 raw_s
->fd
= qemu_open(state
->bs
->filename
, raw_s
->open_flags
);
668 if (raw_s
->fd
== -1) {
669 error_setg_errno(errp
, errno
, "Could not reopen file");
674 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
675 * alignment with the new fd. */
676 if (raw_s
->fd
!= -1) {
677 raw_probe_alignment(state
->bs
, raw_s
->fd
, &local_err
);
679 qemu_close(raw_s
->fd
);
681 error_propagate(errp
, local_err
);
689 static void raw_reopen_commit(BDRVReopenState
*state
)
691 BDRVRawReopenState
*raw_s
= state
->opaque
;
692 BDRVRawState
*s
= state
->bs
->opaque
;
694 s
->open_flags
= raw_s
->open_flags
;
698 #ifdef CONFIG_LINUX_AIO
699 s
->use_aio
= raw_s
->use_aio
;
702 g_free(state
->opaque
);
703 state
->opaque
= NULL
;
707 static void raw_reopen_abort(BDRVReopenState
*state
)
709 BDRVRawReopenState
*raw_s
= state
->opaque
;
711 /* nothing to do if NULL, we didn't get far enough */
716 if (raw_s
->fd
>= 0) {
717 qemu_close(raw_s
->fd
);
720 g_free(state
->opaque
);
721 state
->opaque
= NULL
;
724 static void raw_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
726 BDRVRawState
*s
= bs
->opaque
;
728 raw_probe_alignment(bs
, s
->fd
, errp
);
729 bs
->bl
.min_mem_alignment
= s
->buf_align
;
730 bs
->bl
.opt_mem_alignment
= MAX(s
->buf_align
, getpagesize());
733 static int check_for_dasd(int fd
)
736 struct dasd_information2_t info
= {0};
738 return ioctl(fd
, BIODASDINFO2
, &info
);
745 * Try to get @bs's logical and physical block size.
746 * On success, store them in @bsz and return zero.
747 * On failure, return negative errno.
749 static int hdev_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
751 BDRVRawState
*s
= bs
->opaque
;
754 /* If DASD, get blocksizes */
755 if (check_for_dasd(s
->fd
) < 0) {
758 ret
= probe_logical_blocksize(s
->fd
, &bsz
->log
);
762 return probe_physical_blocksize(s
->fd
, &bsz
->phys
);
766 * Try to get @bs's geometry: cyls, heads, sectors.
767 * On success, store them in @geo and return 0.
768 * On failure return -errno.
769 * (Allows block driver to assign default geometry values that guest sees)
772 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
774 BDRVRawState
*s
= bs
->opaque
;
775 struct hd_geometry ioctl_geo
= {0};
778 /* If DASD, get its geometry */
779 if (check_for_dasd(s
->fd
) < 0) {
782 if (ioctl(s
->fd
, HDIO_GETGEO
, &ioctl_geo
) < 0) {
785 /* HDIO_GETGEO may return success even though geo contains zeros
786 (e.g. certain multipath setups) */
787 if (!ioctl_geo
.heads
|| !ioctl_geo
.sectors
|| !ioctl_geo
.cylinders
) {
790 /* Do not return a geometry for partition */
791 if (ioctl_geo
.start
!= 0) {
794 geo
->heads
= ioctl_geo
.heads
;
795 geo
->sectors
= ioctl_geo
.sectors
;
796 if (!probe_physical_blocksize(s
->fd
, &blksize
)) {
797 /* overwrite cyls: HDIO_GETGEO result is incorrect for big drives */
798 geo
->cylinders
= bdrv_nb_sectors(bs
) / (blksize
/ BDRV_SECTOR_SIZE
)
799 / (geo
->heads
* geo
->sectors
);
802 geo
->cylinders
= ioctl_geo
.cylinders
;
806 #else /* __linux__ */
807 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
813 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
817 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
825 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
829 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
838 static bool preadv_present
= true;
841 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
843 return preadv(fd
, iov
, nr_iov
, offset
);
847 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
849 return pwritev(fd
, iov
, nr_iov
, offset
);
854 static bool preadv_present
= false;
857 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
863 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
870 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
875 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
876 len
= qemu_pwritev(aiocb
->aio_fildes
,
881 len
= qemu_preadv(aiocb
->aio_fildes
,
885 } while (len
== -1 && errno
== EINTR
);
894 * Read/writes the data to/from a given linear buffer.
896 * Returns the number of bytes handles or -errno in case of an error. Short
897 * reads are only returned if the end of the file is reached.
899 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
904 while (offset
< aiocb
->aio_nbytes
) {
905 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
906 len
= pwrite(aiocb
->aio_fildes
,
907 (const char *)buf
+ offset
,
908 aiocb
->aio_nbytes
- offset
,
909 aiocb
->aio_offset
+ offset
);
911 len
= pread(aiocb
->aio_fildes
,
913 aiocb
->aio_nbytes
- offset
,
914 aiocb
->aio_offset
+ offset
);
916 if (len
== -1 && errno
== EINTR
) {
918 } else if (len
== -1 && errno
== EINVAL
&&
919 (aiocb
->bs
->open_flags
& BDRV_O_NOCACHE
) &&
920 !(aiocb
->aio_type
& QEMU_AIO_WRITE
) &&
922 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
923 * after a short read. Assume that O_DIRECT short reads only occur
924 * at EOF. Therefore this is a short read, not an I/O error.
927 } else if (len
== -1) {
930 } else if (len
== 0) {
939 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
944 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
946 * If there is just a single buffer, and it is properly aligned
947 * we can just use plain pread/pwrite without any problems.
949 if (aiocb
->aio_niov
== 1) {
950 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
953 * We have more than one iovec, and all are properly aligned.
955 * Try preadv/pwritev first and fall back to linearizing the
956 * buffer if it's not supported.
958 if (preadv_present
) {
959 nbytes
= handle_aiocb_rw_vector(aiocb
);
960 if (nbytes
== aiocb
->aio_nbytes
||
961 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
964 preadv_present
= false;
968 * XXX(hch): short read/write. no easy way to handle the reminder
969 * using these interfaces. For now retry using plain
975 * Ok, we have to do it the hard way, copy all segments into
976 * a single aligned buffer.
978 buf
= qemu_try_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
983 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
987 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
988 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
989 p
+= aiocb
->aio_iov
[i
].iov_len
;
991 assert(p
- buf
== aiocb
->aio_nbytes
);
994 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
995 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
997 size_t count
= aiocb
->aio_nbytes
, copy
;
1000 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
1002 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
1003 copy
= aiocb
->aio_iov
[i
].iov_len
;
1005 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
1006 assert(count
>= copy
);
1018 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1020 struct xfs_flock64 fl
;
1022 memset(&fl
, 0, sizeof(fl
));
1023 fl
.l_whence
= SEEK_SET
;
1024 fl
.l_start
= offset
;
1027 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
1028 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno
));
1035 static int xfs_discard(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1037 struct xfs_flock64 fl
;
1039 memset(&fl
, 0, sizeof(fl
));
1040 fl
.l_whence
= SEEK_SET
;
1041 fl
.l_start
= offset
;
1044 if (xfsctl(NULL
, s
->fd
, XFS_IOC_UNRESVSP64
, &fl
) < 0) {
1045 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno
));
1053 static int translate_err(int err
)
1055 if (err
== -ENODEV
|| err
== -ENOSYS
|| err
== -EOPNOTSUPP
||
1062 #ifdef CONFIG_FALLOCATE
1063 static int do_fallocate(int fd
, int mode
, off_t offset
, off_t len
)
1066 if (fallocate(fd
, mode
, offset
, len
) == 0) {
1069 } while (errno
== EINTR
);
1070 return translate_err(-errno
);
1074 static ssize_t
handle_aiocb_write_zeroes_block(RawPosixAIOData
*aiocb
)
1077 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1079 if (!s
->has_write_zeroes
) {
1085 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1086 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
1089 } while (errno
== EINTR
);
1091 ret
= translate_err(-errno
);
1094 if (ret
== -ENOTSUP
) {
1095 s
->has_write_zeroes
= false;
1100 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
1102 #if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1103 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1106 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1107 return handle_aiocb_write_zeroes_block(aiocb
);
1112 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1116 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1117 if (s
->has_write_zeroes
) {
1118 int ret
= do_fallocate(s
->fd
, FALLOC_FL_ZERO_RANGE
,
1119 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1120 if (ret
== 0 || ret
!= -ENOTSUP
) {
1123 s
->has_write_zeroes
= false;
1127 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1128 if (s
->has_discard
&& s
->has_fallocate
) {
1129 int ret
= do_fallocate(s
->fd
,
1130 FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1131 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1133 ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1134 if (ret
== 0 || ret
!= -ENOTSUP
) {
1137 s
->has_fallocate
= false;
1138 } else if (ret
!= -ENOTSUP
) {
1141 s
->has_discard
= false;
1146 #ifdef CONFIG_FALLOCATE
1147 if (s
->has_fallocate
&& aiocb
->aio_offset
>= bdrv_getlength(aiocb
->bs
)) {
1148 int ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1149 if (ret
== 0 || ret
!= -ENOTSUP
) {
1152 s
->has_fallocate
= false;
1159 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
1161 int ret
= -EOPNOTSUPP
;
1162 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1164 if (!s
->has_discard
) {
1168 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1171 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1172 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
1175 } while (errno
== EINTR
);
1182 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1186 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1187 ret
= do_fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1188 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1192 ret
= translate_err(ret
);
1193 if (ret
== -ENOTSUP
) {
1194 s
->has_discard
= false;
1199 static int aio_worker(void *arg
)
1201 RawPosixAIOData
*aiocb
= arg
;
1204 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
1206 ret
= handle_aiocb_rw(aiocb
);
1207 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1208 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
1209 0, aiocb
->aio_nbytes
- ret
);
1211 ret
= aiocb
->aio_nbytes
;
1213 if (ret
== aiocb
->aio_nbytes
) {
1215 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1219 case QEMU_AIO_WRITE
:
1220 ret
= handle_aiocb_rw(aiocb
);
1221 if (ret
== aiocb
->aio_nbytes
) {
1223 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1227 case QEMU_AIO_FLUSH
:
1228 ret
= handle_aiocb_flush(aiocb
);
1230 case QEMU_AIO_IOCTL
:
1231 ret
= handle_aiocb_ioctl(aiocb
);
1233 case QEMU_AIO_DISCARD
:
1234 ret
= handle_aiocb_discard(aiocb
);
1236 case QEMU_AIO_WRITE_ZEROES
:
1237 ret
= handle_aiocb_write_zeroes(aiocb
);
1240 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
1245 g_slice_free(RawPosixAIOData
, aiocb
);
1249 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
1250 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1253 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
1257 acb
->aio_type
= type
;
1258 acb
->aio_fildes
= fd
;
1260 acb
->aio_nbytes
= nb_sectors
* BDRV_SECTOR_SIZE
;
1261 acb
->aio_offset
= sector_num
* BDRV_SECTOR_SIZE
;
1264 acb
->aio_iov
= qiov
->iov
;
1265 acb
->aio_niov
= qiov
->niov
;
1266 assert(qiov
->size
== acb
->aio_nbytes
);
1269 trace_paio_submit_co(sector_num
, nb_sectors
, type
);
1270 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1271 return thread_pool_submit_co(pool
, aio_worker
, acb
);
1274 static BlockAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
1275 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1276 BlockCompletionFunc
*cb
, void *opaque
, int type
)
1278 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
1282 acb
->aio_type
= type
;
1283 acb
->aio_fildes
= fd
;
1285 acb
->aio_nbytes
= nb_sectors
* BDRV_SECTOR_SIZE
;
1286 acb
->aio_offset
= sector_num
* BDRV_SECTOR_SIZE
;
1289 acb
->aio_iov
= qiov
->iov
;
1290 acb
->aio_niov
= qiov
->niov
;
1291 assert(qiov
->size
== acb
->aio_nbytes
);
1294 trace_paio_submit(acb
, opaque
, sector_num
, nb_sectors
, type
);
1295 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1296 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1299 static BlockAIOCB
*raw_aio_submit(BlockDriverState
*bs
,
1300 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1301 BlockCompletionFunc
*cb
, void *opaque
, int type
)
1303 BDRVRawState
*s
= bs
->opaque
;
1305 if (fd_open(bs
) < 0)
1309 * Check if the underlying device requires requests to be aligned,
1310 * and if the request we are trying to submit is aligned or not.
1311 * If this is the case tell the low-level driver that it needs
1312 * to copy the buffer.
1314 if (s
->needs_alignment
) {
1315 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1316 type
|= QEMU_AIO_MISALIGNED
;
1317 #ifdef CONFIG_LINUX_AIO
1318 } else if (s
->use_aio
) {
1319 return laio_submit(bs
, s
->aio_ctx
, s
->fd
, sector_num
, qiov
,
1320 nb_sectors
, cb
, opaque
, type
);
1325 return paio_submit(bs
, s
->fd
, sector_num
, qiov
, nb_sectors
,
1329 static void raw_aio_plug(BlockDriverState
*bs
)
1331 #ifdef CONFIG_LINUX_AIO
1332 BDRVRawState
*s
= bs
->opaque
;
1334 laio_io_plug(bs
, s
->aio_ctx
);
1339 static void raw_aio_unplug(BlockDriverState
*bs
)
1341 #ifdef CONFIG_LINUX_AIO
1342 BDRVRawState
*s
= bs
->opaque
;
1344 laio_io_unplug(bs
, s
->aio_ctx
, true);
1349 static void raw_aio_flush_io_queue(BlockDriverState
*bs
)
1351 #ifdef CONFIG_LINUX_AIO
1352 BDRVRawState
*s
= bs
->opaque
;
1354 laio_io_unplug(bs
, s
->aio_ctx
, false);
1359 static BlockAIOCB
*raw_aio_readv(BlockDriverState
*bs
,
1360 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1361 BlockCompletionFunc
*cb
, void *opaque
)
1363 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1364 cb
, opaque
, QEMU_AIO_READ
);
1367 static BlockAIOCB
*raw_aio_writev(BlockDriverState
*bs
,
1368 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1369 BlockCompletionFunc
*cb
, void *opaque
)
1371 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1372 cb
, opaque
, QEMU_AIO_WRITE
);
1375 static BlockAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1376 BlockCompletionFunc
*cb
, void *opaque
)
1378 BDRVRawState
*s
= bs
->opaque
;
1380 if (fd_open(bs
) < 0)
1383 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1386 static void raw_close(BlockDriverState
*bs
)
1388 BDRVRawState
*s
= bs
->opaque
;
1390 raw_detach_aio_context(bs
);
1392 #ifdef CONFIG_LINUX_AIO
1394 laio_cleanup(s
->aio_ctx
);
1403 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
1405 BDRVRawState
*s
= bs
->opaque
;
1408 if (fstat(s
->fd
, &st
)) {
1412 if (S_ISREG(st
.st_mode
)) {
1413 if (ftruncate(s
->fd
, offset
) < 0) {
1416 } else if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1417 if (offset
> raw_getlength(bs
)) {
1428 static int64_t raw_getlength(BlockDriverState
*bs
)
1430 BDRVRawState
*s
= bs
->opaque
;
1436 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1437 struct disklabel dl
;
1439 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1441 return (uint64_t)dl
.d_secsize
*
1442 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1446 #elif defined(__NetBSD__)
1447 static int64_t raw_getlength(BlockDriverState
*bs
)
1449 BDRVRawState
*s
= bs
->opaque
;
1455 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1456 struct dkwedge_info dkw
;
1458 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1459 return dkw
.dkw_size
* 512;
1461 struct disklabel dl
;
1463 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1465 return (uint64_t)dl
.d_secsize
*
1466 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1471 #elif defined(__sun__)
1472 static int64_t raw_getlength(BlockDriverState
*bs
)
1474 BDRVRawState
*s
= bs
->opaque
;
1475 struct dk_minfo minfo
;
1485 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1487 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1489 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1493 * There are reports that lseek on some devices fails, but
1494 * irc discussion said that contingency on contingency was overkill.
1496 size
= lseek(s
->fd
, 0, SEEK_END
);
1502 #elif defined(CONFIG_BSD)
1503 static int64_t raw_getlength(BlockDriverState
*bs
)
1505 BDRVRawState
*s
= bs
->opaque
;
1509 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1518 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1521 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1522 #ifdef DIOCGMEDIASIZE
1523 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1524 #elif defined(DIOCGPART)
1527 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1528 size
= pi
.media_size
;
1534 #if defined(__APPLE__) && defined(__MACH__)
1536 uint64_t sectors
= 0;
1537 uint32_t sector_size
= 0;
1539 if (ioctl(fd
, DKIOCGETBLOCKCOUNT
, §ors
) == 0
1540 && ioctl(fd
, DKIOCGETBLOCKSIZE
, §or_size
) == 0) {
1541 size
= sectors
* sector_size
;
1543 size
= lseek(fd
, 0LL, SEEK_END
);
1550 size
= lseek(fd
, 0LL, SEEK_END
);
1555 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1558 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1559 if (size
== 2048LL * (unsigned)-1)
1561 /* XXX no disc? maybe we need to reopen... */
1562 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1569 size
= lseek(fd
, 0, SEEK_END
);
1577 static int64_t raw_getlength(BlockDriverState
*bs
)
1579 BDRVRawState
*s
= bs
->opaque
;
1588 size
= lseek(s
->fd
, 0, SEEK_END
);
1596 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
1599 BDRVRawState
*s
= bs
->opaque
;
1601 if (fstat(s
->fd
, &st
) < 0) {
1604 return (int64_t)st
.st_blocks
* 512;
1607 static int raw_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1611 int64_t total_size
= 0;
1613 PreallocMode prealloc
;
1615 Error
*local_err
= NULL
;
1617 strstart(filename
, "file:", &filename
);
1619 /* Read out options */
1620 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1622 nocow
= qemu_opt_get_bool(opts
, BLOCK_OPT_NOCOW
, false);
1623 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
1624 prealloc
= qapi_enum_parse(PreallocMode_lookup
, buf
,
1625 PREALLOC_MODE_MAX
, PREALLOC_MODE_OFF
,
1629 error_propagate(errp
, local_err
);
1634 fd
= qemu_open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
1638 error_setg_errno(errp
, -result
, "Could not create file");
1644 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1645 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1646 * will be ignored since any failure of this operation should not
1647 * block the left work.
1650 if (ioctl(fd
, FS_IOC_GETFLAGS
, &attr
) == 0) {
1651 attr
|= FS_NOCOW_FL
;
1652 ioctl(fd
, FS_IOC_SETFLAGS
, &attr
);
1657 if (ftruncate(fd
, total_size
) != 0) {
1659 error_setg_errno(errp
, -result
, "Could not resize file");
1664 #ifdef CONFIG_POSIX_FALLOCATE
1665 case PREALLOC_MODE_FALLOC
:
1666 /* posix_fallocate() doesn't set errno. */
1667 result
= -posix_fallocate(fd
, 0, total_size
);
1669 error_setg_errno(errp
, -result
,
1670 "Could not preallocate data for the new file");
1674 case PREALLOC_MODE_FULL
:
1676 int64_t num
= 0, left
= total_size
;
1677 buf
= g_malloc0(65536);
1680 num
= MIN(left
, 65536);
1681 result
= write(fd
, buf
, num
);
1684 error_setg_errno(errp
, -result
,
1685 "Could not write to the new file");
1694 error_setg_errno(errp
, -result
,
1695 "Could not flush new file to disk");
1701 case PREALLOC_MODE_OFF
:
1705 error_setg(errp
, "Unsupported preallocation mode: %s",
1706 PreallocMode_lookup
[prealloc
]);
1711 if (qemu_close(fd
) != 0 && result
== 0) {
1713 error_setg_errno(errp
, -result
, "Could not close the new file");
1720 * Find allocation range in @bs around offset @start.
1721 * May change underlying file descriptor's file offset.
1722 * If @start is not in a hole, store @start in @data, and the
1723 * beginning of the next hole in @hole, and return 0.
1724 * If @start is in a non-trailing hole, store @start in @hole and the
1725 * beginning of the next non-hole in @data, and return 0.
1726 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
1727 * If we can't find out, return a negative errno other than -ENXIO.
1729 static int find_allocation(BlockDriverState
*bs
, off_t start
,
1730 off_t
*data
, off_t
*hole
)
1732 #if defined SEEK_HOLE && defined SEEK_DATA
1733 BDRVRawState
*s
= bs
->opaque
;
1738 * D1. offs == start: start is in data
1739 * D2. offs > start: start is in a hole, next data at offs
1740 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
1741 * or start is beyond EOF
1742 * If the latter happens, the file has been truncated behind
1743 * our back since we opened it. All bets are off then.
1744 * Treating like a trailing hole is simplest.
1745 * D4. offs < 0, errno != ENXIO: we learned nothing
1747 offs
= lseek(s
->fd
, start
, SEEK_DATA
);
1749 return -errno
; /* D3 or D4 */
1751 assert(offs
>= start
);
1754 /* D2: in hole, next data at offs */
1760 /* D1: in data, end not yet known */
1764 * H1. offs == start: start is in a hole
1765 * If this happens here, a hole has been dug behind our back
1766 * since the previous lseek().
1767 * H2. offs > start: either start is in data, next hole at offs,
1768 * or start is in trailing hole, EOF at offs
1769 * Linux treats trailing holes like any other hole: offs ==
1770 * start. Solaris seeks to EOF instead: offs > start (blech).
1771 * If that happens here, a hole has been dug behind our back
1772 * since the previous lseek().
1773 * H3. offs < 0, errno = ENXIO: start is beyond EOF
1774 * If this happens, the file has been truncated behind our
1775 * back since we opened it. Treat it like a trailing hole.
1776 * H4. offs < 0, errno != ENXIO: we learned nothing
1777 * Pretend we know nothing at all, i.e. "forget" about D1.
1779 offs
= lseek(s
->fd
, start
, SEEK_HOLE
);
1781 return -errno
; /* D1 and (H3 or H4) */
1783 assert(offs
>= start
);
1787 * D1 and H2: either in data, next hole at offs, or it was in
1788 * data but is now in a trailing hole. In the latter case,
1789 * all bets are off. Treating it as if it there was data all
1790 * the way to EOF is safe, so simply do that.
1805 * Returns the allocation status of the specified sectors.
1807 * If 'sector_num' is beyond the end of the disk image the return value is 0
1808 * and 'pnum' is set to 0.
1810 * 'pnum' is set to the number of sectors (including and immediately following
1811 * the specified sector) that are known to be in the same
1812 * allocated/unallocated state.
1814 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1815 * beyond the end of the disk image it will be clamped.
1817 static int64_t coroutine_fn
raw_co_get_block_status(BlockDriverState
*bs
,
1819 int nb_sectors
, int *pnum
)
1821 off_t start
, data
= 0, hole
= 0;
1830 start
= sector_num
* BDRV_SECTOR_SIZE
;
1831 total_size
= bdrv_getlength(bs
);
1832 if (total_size
< 0) {
1834 } else if (start
>= total_size
) {
1837 } else if (start
+ nb_sectors
* BDRV_SECTOR_SIZE
> total_size
) {
1838 nb_sectors
= DIV_ROUND_UP(total_size
- start
, BDRV_SECTOR_SIZE
);
1841 ret
= find_allocation(bs
, start
, &data
, &hole
);
1842 if (ret
== -ENXIO
) {
1845 ret
= BDRV_BLOCK_ZERO
;
1846 } else if (ret
< 0) {
1847 /* No info available, so pretend there are no holes */
1849 ret
= BDRV_BLOCK_DATA
;
1850 } else if (data
== start
) {
1851 /* On a data extent, compute sectors to the end of the extent. */
1852 *pnum
= MIN(nb_sectors
, (hole
- start
) / BDRV_SECTOR_SIZE
);
1853 ret
= BDRV_BLOCK_DATA
;
1855 /* On a hole, compute sectors to the beginning of the next extent. */
1856 assert(hole
== start
);
1857 *pnum
= MIN(nb_sectors
, (data
- start
) / BDRV_SECTOR_SIZE
);
1858 ret
= BDRV_BLOCK_ZERO
;
1860 return ret
| BDRV_BLOCK_OFFSET_VALID
| start
;
1863 static coroutine_fn BlockAIOCB
*raw_aio_discard(BlockDriverState
*bs
,
1864 int64_t sector_num
, int nb_sectors
,
1865 BlockCompletionFunc
*cb
, void *opaque
)
1867 BDRVRawState
*s
= bs
->opaque
;
1869 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1870 cb
, opaque
, QEMU_AIO_DISCARD
);
1873 static int coroutine_fn
raw_co_write_zeroes(
1874 BlockDriverState
*bs
, int64_t sector_num
,
1875 int nb_sectors
, BdrvRequestFlags flags
)
1877 BDRVRawState
*s
= bs
->opaque
;
1879 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1880 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1881 QEMU_AIO_WRITE_ZEROES
);
1882 } else if (s
->discard_zeroes
) {
1883 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1889 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1891 BDRVRawState
*s
= bs
->opaque
;
1893 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
1894 bdi
->can_write_zeroes_with_unmap
= s
->discard_zeroes
;
1898 static QemuOptsList raw_create_opts
= {
1899 .name
= "raw-create-opts",
1900 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
1903 .name
= BLOCK_OPT_SIZE
,
1904 .type
= QEMU_OPT_SIZE
,
1905 .help
= "Virtual disk size"
1908 .name
= BLOCK_OPT_NOCOW
,
1909 .type
= QEMU_OPT_BOOL
,
1910 .help
= "Turn off copy-on-write (valid only on btrfs)"
1913 .name
= BLOCK_OPT_PREALLOC
,
1914 .type
= QEMU_OPT_STRING
,
1915 .help
= "Preallocation mode (allowed values: off, falloc, full)"
1917 { /* end of list */ }
1921 BlockDriver bdrv_file
= {
1922 .format_name
= "file",
1923 .protocol_name
= "file",
1924 .instance_size
= sizeof(BDRVRawState
),
1925 .bdrv_needs_filename
= true,
1926 .bdrv_probe
= NULL
, /* no probe for protocols */
1927 .bdrv_parse_filename
= raw_parse_filename
,
1928 .bdrv_file_open
= raw_open
,
1929 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1930 .bdrv_reopen_commit
= raw_reopen_commit
,
1931 .bdrv_reopen_abort
= raw_reopen_abort
,
1932 .bdrv_close
= raw_close
,
1933 .bdrv_create
= raw_create
,
1934 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
1935 .bdrv_co_get_block_status
= raw_co_get_block_status
,
1936 .bdrv_co_write_zeroes
= raw_co_write_zeroes
,
1938 .bdrv_aio_readv
= raw_aio_readv
,
1939 .bdrv_aio_writev
= raw_aio_writev
,
1940 .bdrv_aio_flush
= raw_aio_flush
,
1941 .bdrv_aio_discard
= raw_aio_discard
,
1942 .bdrv_refresh_limits
= raw_refresh_limits
,
1943 .bdrv_io_plug
= raw_aio_plug
,
1944 .bdrv_io_unplug
= raw_aio_unplug
,
1945 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
1947 .bdrv_truncate
= raw_truncate
,
1948 .bdrv_getlength
= raw_getlength
,
1949 .bdrv_get_info
= raw_get_info
,
1950 .bdrv_get_allocated_file_size
1951 = raw_get_allocated_file_size
,
1953 .bdrv_detach_aio_context
= raw_detach_aio_context
,
1954 .bdrv_attach_aio_context
= raw_attach_aio_context
,
1956 .create_opts
= &raw_create_opts
,
1959 /***********************************************/
1962 #if defined(__APPLE__) && defined(__MACH__)
1963 static kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
);
1964 static kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
);
1966 kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
)
1968 kern_return_t kernResult
;
1969 mach_port_t masterPort
;
1970 CFMutableDictionaryRef classesToMatch
;
1972 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
1973 if ( KERN_SUCCESS
!= kernResult
) {
1974 printf( "IOMasterPort returned %d\n", kernResult
);
1977 classesToMatch
= IOServiceMatching( kIOCDMediaClass
);
1978 if ( classesToMatch
== NULL
) {
1979 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1981 CFDictionarySetValue( classesToMatch
, CFSTR( kIOMediaEjectableKey
), kCFBooleanTrue
);
1983 kernResult
= IOServiceGetMatchingServices( masterPort
, classesToMatch
, mediaIterator
);
1984 if ( KERN_SUCCESS
!= kernResult
)
1986 printf( "IOServiceGetMatchingServices returned %d\n", kernResult
);
1992 kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
)
1994 io_object_t nextMedia
;
1995 kern_return_t kernResult
= KERN_FAILURE
;
1997 nextMedia
= IOIteratorNext( mediaIterator
);
2000 CFTypeRef bsdPathAsCFString
;
2001 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
2002 if ( bsdPathAsCFString
) {
2003 size_t devPathLength
;
2004 strcpy( bsdPath
, _PATH_DEV
);
2005 strcat( bsdPath
, "r" );
2006 devPathLength
= strlen( bsdPath
);
2007 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
2008 kernResult
= KERN_SUCCESS
;
2010 CFRelease( bsdPathAsCFString
);
2012 IOObjectRelease( nextMedia
);
2020 static int hdev_probe_device(const char *filename
)
2024 /* allow a dedicated CD-ROM driver to match with a higher priority */
2025 if (strstart(filename
, "/dev/cdrom", NULL
))
2028 if (stat(filename
, &st
) >= 0 &&
2029 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
2036 static int check_hdev_writable(BDRVRawState
*s
)
2038 #if defined(BLKROGET)
2039 /* Linux block devices can be configured "read-only" using blockdev(8).
2040 * This is independent of device node permissions and therefore open(2)
2041 * with O_RDWR succeeds. Actual writes fail with EPERM.
2043 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
2044 * check for read-only block devices so that Linux block devices behave
2050 if (fstat(s
->fd
, &st
)) {
2054 if (!S_ISBLK(st
.st_mode
)) {
2058 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
2065 #endif /* defined(BLKROGET) */
2069 static void hdev_parse_filename(const char *filename
, QDict
*options
,
2072 /* The prefix is optional, just as for "file". */
2073 strstart(filename
, "host_device:", &filename
);
2075 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2078 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2081 BDRVRawState
*s
= bs
->opaque
;
2082 Error
*local_err
= NULL
;
2084 const char *filename
= qdict_get_str(options
, "filename");
2086 #if defined(__APPLE__) && defined(__MACH__)
2087 if (strstart(filename
, "/dev/cdrom", NULL
)) {
2088 kern_return_t kernResult
;
2089 io_iterator_t mediaIterator
;
2090 char bsdPath
[ MAXPATHLEN
];
2093 kernResult
= FindEjectableCDMedia( &mediaIterator
);
2094 kernResult
= GetBSDPath( mediaIterator
, bsdPath
, sizeof( bsdPath
) );
2096 if ( bsdPath
[ 0 ] != '\0' ) {
2097 strcat(bsdPath
,"s0");
2098 /* some CDs don't have a partition 0 */
2099 fd
= qemu_open(bsdPath
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
2101 bsdPath
[strlen(bsdPath
)-1] = '1';
2106 qdict_put(options
, "filename", qstring_from_str(filename
));
2109 if ( mediaIterator
)
2110 IOObjectRelease( mediaIterator
);
2114 s
->type
= FTYPE_FILE
;
2115 #if defined(__linux__)
2117 char resolved_path
[ MAXPATHLEN
], *temp
;
2119 temp
= realpath(filename
, resolved_path
);
2120 if (temp
&& strstart(temp
, "/dev/sg", NULL
)) {
2126 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2129 error_propagate(errp
, local_err
);
2134 if (flags
& BDRV_O_RDWR
) {
2135 ret
= check_hdev_writable(s
);
2138 error_setg_errno(errp
, -ret
, "The device is not writable");
2146 #if defined(__linux__)
2147 /* Note: we do not have a reliable method to detect if the floppy is
2148 present. The current method is to try to open the floppy at every
2149 I/O and to keep it opened during a few hundreds of ms. */
2150 static int fd_open(BlockDriverState
*bs
)
2152 BDRVRawState
*s
= bs
->opaque
;
2153 int last_media_present
;
2155 if (s
->type
!= FTYPE_FD
)
2157 last_media_present
= (s
->fd
>= 0);
2159 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) - s
->fd_open_time
) >= FD_OPEN_TIMEOUT
) {
2163 printf("Floppy closed\n");
2167 if (s
->fd_got_error
&&
2168 (qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) - s
->fd_error_time
) < FD_OPEN_TIMEOUT
) {
2170 printf("No floppy (open delayed)\n");
2174 s
->fd
= qemu_open(bs
->filename
, s
->open_flags
& ~O_NONBLOCK
);
2176 s
->fd_error_time
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
2177 s
->fd_got_error
= 1;
2178 if (last_media_present
)
2179 s
->fd_media_changed
= 1;
2181 printf("No floppy\n");
2186 printf("Floppy opened\n");
2189 if (!last_media_present
)
2190 s
->fd_media_changed
= 1;
2191 s
->fd_open_time
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
2192 s
->fd_got_error
= 0;
2196 static int hdev_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
2198 BDRVRawState
*s
= bs
->opaque
;
2200 return ioctl(s
->fd
, req
, buf
);
2203 static BlockAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
2204 unsigned long int req
, void *buf
,
2205 BlockCompletionFunc
*cb
, void *opaque
)
2207 BDRVRawState
*s
= bs
->opaque
;
2208 RawPosixAIOData
*acb
;
2211 if (fd_open(bs
) < 0)
2214 acb
= g_slice_new(RawPosixAIOData
);
2216 acb
->aio_type
= QEMU_AIO_IOCTL
;
2217 acb
->aio_fildes
= s
->fd
;
2218 acb
->aio_offset
= 0;
2219 acb
->aio_ioctl_buf
= buf
;
2220 acb
->aio_ioctl_cmd
= req
;
2221 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
2222 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
2225 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2226 static int fd_open(BlockDriverState
*bs
)
2228 BDRVRawState
*s
= bs
->opaque
;
2230 /* this is just to ensure s->fd is sane (its called by io ops) */
2235 #else /* !linux && !FreeBSD */
2237 static int fd_open(BlockDriverState
*bs
)
2242 #endif /* !linux && !FreeBSD */
2244 static coroutine_fn BlockAIOCB
*hdev_aio_discard(BlockDriverState
*bs
,
2245 int64_t sector_num
, int nb_sectors
,
2246 BlockCompletionFunc
*cb
, void *opaque
)
2248 BDRVRawState
*s
= bs
->opaque
;
2250 if (fd_open(bs
) < 0) {
2253 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
2254 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2257 static coroutine_fn
int hdev_co_write_zeroes(BlockDriverState
*bs
,
2258 int64_t sector_num
, int nb_sectors
, BdrvRequestFlags flags
)
2260 BDRVRawState
*s
= bs
->opaque
;
2267 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
2268 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
2269 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
2270 } else if (s
->discard_zeroes
) {
2271 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
2272 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2277 static int hdev_create(const char *filename
, QemuOpts
*opts
,
2282 struct stat stat_buf
;
2283 int64_t total_size
= 0;
2286 /* This function is used by all three protocol block drivers and therefore
2287 * any of these three prefixes may be given.
2288 * The return value has to be stored somewhere, otherwise this is an error
2289 * due to -Werror=unused-value. */
2291 strstart(filename
, "host_device:", &filename
) ||
2292 strstart(filename
, "host_cdrom:" , &filename
) ||
2293 strstart(filename
, "host_floppy:", &filename
);
2297 /* Read out options */
2298 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2301 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
2304 error_setg_errno(errp
, -ret
, "Could not open device");
2308 if (fstat(fd
, &stat_buf
) < 0) {
2310 error_setg_errno(errp
, -ret
, "Could not stat device");
2311 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
2313 "The given file is neither a block nor a character device");
2315 } else if (lseek(fd
, 0, SEEK_END
) < total_size
) {
2316 error_setg(errp
, "Device is too small");
2324 static BlockDriver bdrv_host_device
= {
2325 .format_name
= "host_device",
2326 .protocol_name
= "host_device",
2327 .instance_size
= sizeof(BDRVRawState
),
2328 .bdrv_needs_filename
= true,
2329 .bdrv_probe_device
= hdev_probe_device
,
2330 .bdrv_parse_filename
= hdev_parse_filename
,
2331 .bdrv_file_open
= hdev_open
,
2332 .bdrv_close
= raw_close
,
2333 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2334 .bdrv_reopen_commit
= raw_reopen_commit
,
2335 .bdrv_reopen_abort
= raw_reopen_abort
,
2336 .bdrv_create
= hdev_create
,
2337 .create_opts
= &raw_create_opts
,
2338 .bdrv_co_write_zeroes
= hdev_co_write_zeroes
,
2340 .bdrv_aio_readv
= raw_aio_readv
,
2341 .bdrv_aio_writev
= raw_aio_writev
,
2342 .bdrv_aio_flush
= raw_aio_flush
,
2343 .bdrv_aio_discard
= hdev_aio_discard
,
2344 .bdrv_refresh_limits
= raw_refresh_limits
,
2345 .bdrv_io_plug
= raw_aio_plug
,
2346 .bdrv_io_unplug
= raw_aio_unplug
,
2347 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2349 .bdrv_truncate
= raw_truncate
,
2350 .bdrv_getlength
= raw_getlength
,
2351 .bdrv_get_info
= raw_get_info
,
2352 .bdrv_get_allocated_file_size
2353 = raw_get_allocated_file_size
,
2354 .bdrv_probe_blocksizes
= hdev_probe_blocksizes
,
2355 .bdrv_probe_geometry
= hdev_probe_geometry
,
2357 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2358 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2360 /* generic scsi device */
2362 .bdrv_ioctl
= hdev_ioctl
,
2363 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2368 static void floppy_parse_filename(const char *filename
, QDict
*options
,
2371 /* The prefix is optional, just as for "file". */
2372 strstart(filename
, "host_floppy:", &filename
);
2374 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2377 static int floppy_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2380 BDRVRawState
*s
= bs
->opaque
;
2381 Error
*local_err
= NULL
;
2386 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2387 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2390 error_propagate(errp
, local_err
);
2395 /* close fd so that we can reopen it as needed */
2398 s
->fd_media_changed
= 1;
2400 error_report("Host floppy pass-through is deprecated");
2401 error_printf("Support for it will be removed in a future release.\n");
2405 static int floppy_probe_device(const char *filename
)
2409 struct floppy_struct fdparam
;
2412 if (strstart(filename
, "/dev/fd", NULL
) &&
2413 !strstart(filename
, "/dev/fdset/", NULL
)) {
2417 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2421 ret
= fstat(fd
, &st
);
2422 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2426 /* Attempt to detect via a floppy specific ioctl */
2427 ret
= ioctl(fd
, FDGETPRM
, &fdparam
);
2438 static int floppy_is_inserted(BlockDriverState
*bs
)
2440 return fd_open(bs
) >= 0;
2443 static int floppy_media_changed(BlockDriverState
*bs
)
2445 BDRVRawState
*s
= bs
->opaque
;
2449 * XXX: we do not have a true media changed indication.
2450 * It does not work if the floppy is changed without trying to read it.
2453 ret
= s
->fd_media_changed
;
2454 s
->fd_media_changed
= 0;
2456 printf("Floppy changed=%d\n", ret
);
2461 static void floppy_eject(BlockDriverState
*bs
, bool eject_flag
)
2463 BDRVRawState
*s
= bs
->opaque
;
2470 fd
= qemu_open(bs
->filename
, s
->open_flags
| O_NONBLOCK
);
2472 if (ioctl(fd
, FDEJECT
, 0) < 0)
2478 static BlockDriver bdrv_host_floppy
= {
2479 .format_name
= "host_floppy",
2480 .protocol_name
= "host_floppy",
2481 .instance_size
= sizeof(BDRVRawState
),
2482 .bdrv_needs_filename
= true,
2483 .bdrv_probe_device
= floppy_probe_device
,
2484 .bdrv_parse_filename
= floppy_parse_filename
,
2485 .bdrv_file_open
= floppy_open
,
2486 .bdrv_close
= raw_close
,
2487 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2488 .bdrv_reopen_commit
= raw_reopen_commit
,
2489 .bdrv_reopen_abort
= raw_reopen_abort
,
2490 .bdrv_create
= hdev_create
,
2491 .create_opts
= &raw_create_opts
,
2493 .bdrv_aio_readv
= raw_aio_readv
,
2494 .bdrv_aio_writev
= raw_aio_writev
,
2495 .bdrv_aio_flush
= raw_aio_flush
,
2496 .bdrv_refresh_limits
= raw_refresh_limits
,
2497 .bdrv_io_plug
= raw_aio_plug
,
2498 .bdrv_io_unplug
= raw_aio_unplug
,
2499 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2501 .bdrv_truncate
= raw_truncate
,
2502 .bdrv_getlength
= raw_getlength
,
2503 .has_variable_length
= true,
2504 .bdrv_get_allocated_file_size
2505 = raw_get_allocated_file_size
,
2507 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2508 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2510 /* removable device support */
2511 .bdrv_is_inserted
= floppy_is_inserted
,
2512 .bdrv_media_changed
= floppy_media_changed
,
2513 .bdrv_eject
= floppy_eject
,
2517 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2518 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2521 /* The prefix is optional, just as for "file". */
2522 strstart(filename
, "host_cdrom:", &filename
);
2524 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2529 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2532 BDRVRawState
*s
= bs
->opaque
;
2533 Error
*local_err
= NULL
;
2538 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2539 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2541 error_propagate(errp
, local_err
);
2546 static int cdrom_probe_device(const char *filename
)
2552 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2556 ret
= fstat(fd
, &st
);
2557 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2561 /* Attempt to detect via a CDROM specific ioctl */
2562 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2572 static int cdrom_is_inserted(BlockDriverState
*bs
)
2574 BDRVRawState
*s
= bs
->opaque
;
2577 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2578 if (ret
== CDS_DISC_OK
)
2583 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2585 BDRVRawState
*s
= bs
->opaque
;
2588 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2589 perror("CDROMEJECT");
2591 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2592 perror("CDROMEJECT");
2596 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2598 BDRVRawState
*s
= bs
->opaque
;
2600 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2602 * Note: an error can happen if the distribution automatically
2605 /* perror("CDROM_LOCKDOOR"); */
2609 static BlockDriver bdrv_host_cdrom
= {
2610 .format_name
= "host_cdrom",
2611 .protocol_name
= "host_cdrom",
2612 .instance_size
= sizeof(BDRVRawState
),
2613 .bdrv_needs_filename
= true,
2614 .bdrv_probe_device
= cdrom_probe_device
,
2615 .bdrv_parse_filename
= cdrom_parse_filename
,
2616 .bdrv_file_open
= cdrom_open
,
2617 .bdrv_close
= raw_close
,
2618 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2619 .bdrv_reopen_commit
= raw_reopen_commit
,
2620 .bdrv_reopen_abort
= raw_reopen_abort
,
2621 .bdrv_create
= hdev_create
,
2622 .create_opts
= &raw_create_opts
,
2624 .bdrv_aio_readv
= raw_aio_readv
,
2625 .bdrv_aio_writev
= raw_aio_writev
,
2626 .bdrv_aio_flush
= raw_aio_flush
,
2627 .bdrv_refresh_limits
= raw_refresh_limits
,
2628 .bdrv_io_plug
= raw_aio_plug
,
2629 .bdrv_io_unplug
= raw_aio_unplug
,
2630 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2632 .bdrv_truncate
= raw_truncate
,
2633 .bdrv_getlength
= raw_getlength
,
2634 .has_variable_length
= true,
2635 .bdrv_get_allocated_file_size
2636 = raw_get_allocated_file_size
,
2638 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2639 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2641 /* removable device support */
2642 .bdrv_is_inserted
= cdrom_is_inserted
,
2643 .bdrv_eject
= cdrom_eject
,
2644 .bdrv_lock_medium
= cdrom_lock_medium
,
2646 /* generic scsi device */
2647 .bdrv_ioctl
= hdev_ioctl
,
2648 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2650 #endif /* __linux__ */
2652 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2653 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2656 BDRVRawState
*s
= bs
->opaque
;
2657 Error
*local_err
= NULL
;
2662 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2665 error_propagate(errp
, local_err
);
2670 /* make sure the door isn't locked at this time */
2671 ioctl(s
->fd
, CDIOCALLOW
);
2675 static int cdrom_probe_device(const char *filename
)
2677 if (strstart(filename
, "/dev/cd", NULL
) ||
2678 strstart(filename
, "/dev/acd", NULL
))
2683 static int cdrom_reopen(BlockDriverState
*bs
)
2685 BDRVRawState
*s
= bs
->opaque
;
2689 * Force reread of possibly changed/newly loaded disc,
2690 * FreeBSD seems to not notice sometimes...
2694 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
2701 /* make sure the door isn't locked at this time */
2702 ioctl(s
->fd
, CDIOCALLOW
);
2706 static int cdrom_is_inserted(BlockDriverState
*bs
)
2708 return raw_getlength(bs
) > 0;
2711 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2713 BDRVRawState
*s
= bs
->opaque
;
2718 (void) ioctl(s
->fd
, CDIOCALLOW
);
2721 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
2722 perror("CDIOCEJECT");
2724 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
2725 perror("CDIOCCLOSE");
2731 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2733 BDRVRawState
*s
= bs
->opaque
;
2737 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
2739 * Note: an error can happen if the distribution automatically
2742 /* perror("CDROM_LOCKDOOR"); */
2746 static BlockDriver bdrv_host_cdrom
= {
2747 .format_name
= "host_cdrom",
2748 .protocol_name
= "host_cdrom",
2749 .instance_size
= sizeof(BDRVRawState
),
2750 .bdrv_needs_filename
= true,
2751 .bdrv_probe_device
= cdrom_probe_device
,
2752 .bdrv_parse_filename
= cdrom_parse_filename
,
2753 .bdrv_file_open
= cdrom_open
,
2754 .bdrv_close
= raw_close
,
2755 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2756 .bdrv_reopen_commit
= raw_reopen_commit
,
2757 .bdrv_reopen_abort
= raw_reopen_abort
,
2758 .bdrv_create
= hdev_create
,
2759 .create_opts
= &raw_create_opts
,
2761 .bdrv_aio_readv
= raw_aio_readv
,
2762 .bdrv_aio_writev
= raw_aio_writev
,
2763 .bdrv_aio_flush
= raw_aio_flush
,
2764 .bdrv_refresh_limits
= raw_refresh_limits
,
2765 .bdrv_io_plug
= raw_aio_plug
,
2766 .bdrv_io_unplug
= raw_aio_unplug
,
2767 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2769 .bdrv_truncate
= raw_truncate
,
2770 .bdrv_getlength
= raw_getlength
,
2771 .has_variable_length
= true,
2772 .bdrv_get_allocated_file_size
2773 = raw_get_allocated_file_size
,
2775 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2776 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2778 /* removable device support */
2779 .bdrv_is_inserted
= cdrom_is_inserted
,
2780 .bdrv_eject
= cdrom_eject
,
2781 .bdrv_lock_medium
= cdrom_lock_medium
,
2783 #endif /* __FreeBSD__ */
2785 static void bdrv_file_init(void)
2788 * Register all the drivers. Note that order is important, the driver
2789 * registered last will get probed first.
2791 bdrv_register(&bdrv_file
);
2792 bdrv_register(&bdrv_host_device
);
2794 bdrv_register(&bdrv_host_floppy
);
2795 bdrv_register(&bdrv_host_cdrom
);
2797 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2798 bdrv_register(&bdrv_host_cdrom
);
2802 block_init(bdrv_file_init
);