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>
60 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
64 #include <linux/fiemap.h>
66 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
67 #include <linux/falloc.h>
69 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
75 #include <sys/ioctl.h>
76 #include <sys/disklabel.h>
81 #include <sys/ioctl.h>
82 #include <sys/disklabel.h>
88 #include <sys/ioctl.h>
89 #include <sys/diskslice.h>
96 //#define DEBUG_FLOPPY
99 #if defined(DEBUG_BLOCK)
100 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
101 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
103 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
106 /* OS X does not have O_DSYNC */
109 #define O_DSYNC O_SYNC
110 #elif defined(O_FSYNC)
111 #define O_DSYNC O_FSYNC
115 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
117 #define O_DIRECT O_DSYNC
124 /* if the FD is not accessed during that time (in ns), we try to
125 reopen it to see if the disk has been changed */
126 #define FD_OPEN_TIMEOUT (1000000000)
128 #define MAX_BLOCKSIZE 4096
130 typedef struct BDRVRawState
{
136 #if defined(__linux__)
137 /* linux floppy specific */
138 int64_t fd_open_time
;
139 int64_t fd_error_time
;
141 int fd_media_changed
;
143 #ifdef CONFIG_LINUX_AIO
151 bool has_write_zeroes
:1;
152 bool discard_zeroes
:1;
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
)
225 static void raw_probe_alignment(BlockDriverState
*bs
, int fd
, Error
**errp
)
227 BDRVRawState
*s
= bs
->opaque
;
229 unsigned int sector_size
;
231 /* For /dev/sg devices the alignment is not really used.
232 With buffered I/O, we don't have any restrictions. */
233 if (bs
->sg
|| !(s
->open_flags
& O_DIRECT
)) {
234 bs
->request_alignment
= 1;
239 /* Try a few ioctls to get the right size */
240 bs
->request_alignment
= 0;
244 if (ioctl(fd
, BLKSSZGET
, §or_size
) >= 0) {
245 bs
->request_alignment
= sector_size
;
248 #ifdef DKIOCGETBLOCKSIZE
249 if (ioctl(fd
, DKIOCGETBLOCKSIZE
, §or_size
) >= 0) {
250 bs
->request_alignment
= sector_size
;
253 #ifdef DIOCGSECTORSIZE
254 if (ioctl(fd
, DIOCGSECTORSIZE
, §or_size
) >= 0) {
255 bs
->request_alignment
= sector_size
;
261 if (xfsctl(NULL
, fd
, XFS_IOC_DIOINFO
, &da
) >= 0) {
262 bs
->request_alignment
= da
.d_miniosz
;
263 /* The kernel returns wrong information for d_mem */
264 /* s->buf_align = da.d_mem; */
269 /* If we could not get the sizes so far, we can only guess them */
272 buf
= qemu_memalign(MAX_BLOCKSIZE
, 2 * MAX_BLOCKSIZE
);
273 for (align
= 512; align
<= MAX_BLOCKSIZE
; align
<<= 1) {
274 if (pread(fd
, buf
+ align
, MAX_BLOCKSIZE
, 0) >= 0) {
275 s
->buf_align
= align
;
282 if (!bs
->request_alignment
) {
284 buf
= qemu_memalign(s
->buf_align
, MAX_BLOCKSIZE
);
285 for (align
= 512; align
<= MAX_BLOCKSIZE
; align
<<= 1) {
286 if (pread(fd
, buf
, align
, 0) >= 0) {
287 bs
->request_alignment
= align
;
294 if (!s
->buf_align
|| !bs
->request_alignment
) {
295 error_setg(errp
, "Could not find working O_DIRECT alignment. "
296 "Try cache.direct=off.");
300 static void raw_parse_flags(int bdrv_flags
, int *open_flags
)
302 assert(open_flags
!= NULL
);
304 *open_flags
|= O_BINARY
;
305 *open_flags
&= ~O_ACCMODE
;
306 if (bdrv_flags
& BDRV_O_RDWR
) {
307 *open_flags
|= O_RDWR
;
309 *open_flags
|= O_RDONLY
;
312 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
313 * and O_DIRECT for no caching. */
314 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
315 *open_flags
|= O_DIRECT
;
319 static void raw_detach_aio_context(BlockDriverState
*bs
)
321 #ifdef CONFIG_LINUX_AIO
322 BDRVRawState
*s
= bs
->opaque
;
325 laio_detach_aio_context(s
->aio_ctx
, bdrv_get_aio_context(bs
));
330 static void raw_attach_aio_context(BlockDriverState
*bs
,
331 AioContext
*new_context
)
333 #ifdef CONFIG_LINUX_AIO
334 BDRVRawState
*s
= bs
->opaque
;
337 laio_attach_aio_context(s
->aio_ctx
, new_context
);
342 #ifdef CONFIG_LINUX_AIO
343 static int raw_set_aio(void **aio_ctx
, int *use_aio
, int bdrv_flags
)
346 assert(aio_ctx
!= NULL
);
347 assert(use_aio
!= NULL
);
349 * Currently Linux do AIO only for files opened with O_DIRECT
350 * specified so check NOCACHE flag too
352 if ((bdrv_flags
& (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) ==
353 (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) {
355 /* if non-NULL, laio_init() has already been run */
356 if (*aio_ctx
== NULL
) {
357 *aio_ctx
= laio_init();
374 static void raw_parse_filename(const char *filename
, QDict
*options
,
377 /* The filename does not have to be prefixed by the protocol name, since
378 * "file" is the default protocol; therefore, the return value of this
379 * function call can be ignored. */
380 strstart(filename
, "file:", &filename
);
382 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
385 static QemuOptsList raw_runtime_opts
= {
387 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
391 .type
= QEMU_OPT_STRING
,
392 .help
= "File name of the image",
394 { /* end of list */ }
398 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
399 int bdrv_flags
, int open_flags
, Error
**errp
)
401 BDRVRawState
*s
= bs
->opaque
;
403 Error
*local_err
= NULL
;
404 const char *filename
= NULL
;
408 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
409 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
411 error_propagate(errp
, local_err
);
416 filename
= qemu_opt_get(opts
, "filename");
418 ret
= raw_normalize_devicepath(&filename
);
420 error_setg_errno(errp
, -ret
, "Could not normalize device path");
424 s
->open_flags
= open_flags
;
425 raw_parse_flags(bdrv_flags
, &s
->open_flags
);
428 fd
= qemu_open(filename
, s
->open_flags
, 0644);
438 #ifdef CONFIG_LINUX_AIO
439 if (raw_set_aio(&s
->aio_ctx
, &s
->use_aio
, bdrv_flags
)) {
442 error_setg_errno(errp
, -ret
, "Could not set AIO state");
447 s
->has_discard
= true;
448 s
->has_write_zeroes
= true;
450 if (fstat(s
->fd
, &st
) < 0) {
451 error_setg_errno(errp
, errno
, "Could not stat file");
454 if (S_ISREG(st
.st_mode
)) {
455 s
->discard_zeroes
= true;
457 if (S_ISBLK(st
.st_mode
)) {
458 #ifdef BLKDISCARDZEROES
460 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
461 s
->discard_zeroes
= true;
465 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
466 * not rely on the contents of discarded blocks unless using O_DIRECT.
467 * Same for BLKZEROOUT.
469 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
470 s
->discard_zeroes
= false;
471 s
->has_write_zeroes
= false;
477 if (platform_test_xfs_fd(s
->fd
)) {
482 raw_attach_aio_context(bs
, bdrv_get_aio_context(bs
));
486 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
493 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
496 BDRVRawState
*s
= bs
->opaque
;
497 Error
*local_err
= NULL
;
500 s
->type
= FTYPE_FILE
;
501 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
503 error_propagate(errp
, local_err
);
508 static int raw_reopen_prepare(BDRVReopenState
*state
,
509 BlockReopenQueue
*queue
, Error
**errp
)
512 BDRVRawReopenState
*raw_s
;
514 Error
*local_err
= NULL
;
516 assert(state
!= NULL
);
517 assert(state
->bs
!= NULL
);
519 s
= state
->bs
->opaque
;
521 state
->opaque
= g_new0(BDRVRawReopenState
, 1);
522 raw_s
= state
->opaque
;
524 #ifdef CONFIG_LINUX_AIO
525 raw_s
->use_aio
= s
->use_aio
;
527 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
528 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
529 * won't override aio_ctx if aio_ctx is non-NULL */
530 if (raw_set_aio(&s
->aio_ctx
, &raw_s
->use_aio
, state
->flags
)) {
531 error_setg(errp
, "Could not set AIO state");
536 if (s
->type
== FTYPE_FD
|| s
->type
== FTYPE_CD
) {
537 raw_s
->open_flags
|= O_NONBLOCK
;
540 raw_parse_flags(state
->flags
, &raw_s
->open_flags
);
544 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
546 fcntl_flags
|= O_NOATIME
;
550 /* Not all operating systems have O_ASYNC, and those that don't
551 * will not let us track the state into raw_s->open_flags (typically
552 * you achieve the same effect with an ioctl, for example I_SETSIG
553 * on Solaris). But we do not use O_ASYNC, so that's fine.
555 assert((s
->open_flags
& O_ASYNC
) == 0);
558 if ((raw_s
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
559 /* dup the original fd */
560 /* TODO: use qemu fcntl wrapper */
561 #ifdef F_DUPFD_CLOEXEC
562 raw_s
->fd
= fcntl(s
->fd
, F_DUPFD_CLOEXEC
, 0);
564 raw_s
->fd
= dup(s
->fd
);
565 if (raw_s
->fd
!= -1) {
566 qemu_set_cloexec(raw_s
->fd
);
569 if (raw_s
->fd
>= 0) {
570 ret
= fcntl_setfl(raw_s
->fd
, raw_s
->open_flags
);
572 qemu_close(raw_s
->fd
);
578 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
579 if (raw_s
->fd
== -1) {
580 assert(!(raw_s
->open_flags
& O_CREAT
));
581 raw_s
->fd
= qemu_open(state
->bs
->filename
, raw_s
->open_flags
);
582 if (raw_s
->fd
== -1) {
583 error_setg_errno(errp
, errno
, "Could not reopen file");
588 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
589 * alignment with the new fd. */
590 if (raw_s
->fd
!= -1) {
591 raw_probe_alignment(state
->bs
, raw_s
->fd
, &local_err
);
593 qemu_close(raw_s
->fd
);
595 error_propagate(errp
, local_err
);
603 static void raw_reopen_commit(BDRVReopenState
*state
)
605 BDRVRawReopenState
*raw_s
= state
->opaque
;
606 BDRVRawState
*s
= state
->bs
->opaque
;
608 s
->open_flags
= raw_s
->open_flags
;
612 #ifdef CONFIG_LINUX_AIO
613 s
->use_aio
= raw_s
->use_aio
;
616 g_free(state
->opaque
);
617 state
->opaque
= NULL
;
621 static void raw_reopen_abort(BDRVReopenState
*state
)
623 BDRVRawReopenState
*raw_s
= state
->opaque
;
625 /* nothing to do if NULL, we didn't get far enough */
630 if (raw_s
->fd
>= 0) {
631 qemu_close(raw_s
->fd
);
634 g_free(state
->opaque
);
635 state
->opaque
= NULL
;
638 static void raw_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
640 BDRVRawState
*s
= bs
->opaque
;
642 raw_probe_alignment(bs
, s
->fd
, errp
);
643 bs
->bl
.opt_mem_alignment
= s
->buf_align
;
646 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
650 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
658 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
662 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
671 static bool preadv_present
= true;
674 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
676 return preadv(fd
, iov
, nr_iov
, offset
);
680 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
682 return pwritev(fd
, iov
, nr_iov
, offset
);
687 static bool preadv_present
= false;
690 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
696 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
703 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
708 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
709 len
= qemu_pwritev(aiocb
->aio_fildes
,
714 len
= qemu_preadv(aiocb
->aio_fildes
,
718 } while (len
== -1 && errno
== EINTR
);
727 * Read/writes the data to/from a given linear buffer.
729 * Returns the number of bytes handles or -errno in case of an error. Short
730 * reads are only returned if the end of the file is reached.
732 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
737 while (offset
< aiocb
->aio_nbytes
) {
738 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
739 len
= pwrite(aiocb
->aio_fildes
,
740 (const char *)buf
+ offset
,
741 aiocb
->aio_nbytes
- offset
,
742 aiocb
->aio_offset
+ offset
);
744 len
= pread(aiocb
->aio_fildes
,
746 aiocb
->aio_nbytes
- offset
,
747 aiocb
->aio_offset
+ offset
);
749 if (len
== -1 && errno
== EINTR
) {
751 } else if (len
== -1 && errno
== EINVAL
&&
752 (aiocb
->bs
->open_flags
& BDRV_O_NOCACHE
) &&
753 !(aiocb
->aio_type
& QEMU_AIO_WRITE
) &&
755 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
756 * after a short read. Assume that O_DIRECT short reads only occur
757 * at EOF. Therefore this is a short read, not an I/O error.
760 } else if (len
== -1) {
763 } else if (len
== 0) {
772 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
777 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
779 * If there is just a single buffer, and it is properly aligned
780 * we can just use plain pread/pwrite without any problems.
782 if (aiocb
->aio_niov
== 1) {
783 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
786 * We have more than one iovec, and all are properly aligned.
788 * Try preadv/pwritev first and fall back to linearizing the
789 * buffer if it's not supported.
791 if (preadv_present
) {
792 nbytes
= handle_aiocb_rw_vector(aiocb
);
793 if (nbytes
== aiocb
->aio_nbytes
||
794 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
797 preadv_present
= false;
801 * XXX(hch): short read/write. no easy way to handle the reminder
802 * using these interfaces. For now retry using plain
808 * Ok, we have to do it the hard way, copy all segments into
809 * a single aligned buffer.
811 buf
= qemu_try_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
816 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
820 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
821 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
822 p
+= aiocb
->aio_iov
[i
].iov_len
;
824 assert(p
- buf
== aiocb
->aio_nbytes
);
827 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
828 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
830 size_t count
= aiocb
->aio_nbytes
, copy
;
833 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
835 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
836 copy
= aiocb
->aio_iov
[i
].iov_len
;
838 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
839 assert(count
>= copy
);
851 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
853 struct xfs_flock64 fl
;
855 memset(&fl
, 0, sizeof(fl
));
856 fl
.l_whence
= SEEK_SET
;
860 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
861 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno
));
868 static int xfs_discard(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
870 struct xfs_flock64 fl
;
872 memset(&fl
, 0, sizeof(fl
));
873 fl
.l_whence
= SEEK_SET
;
877 if (xfsctl(NULL
, s
->fd
, XFS_IOC_UNRESVSP64
, &fl
) < 0) {
878 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno
));
886 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
888 int ret
= -EOPNOTSUPP
;
889 BDRVRawState
*s
= aiocb
->bs
->opaque
;
891 if (s
->has_write_zeroes
== 0) {
895 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
898 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
899 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
902 } while (errno
== EINTR
);
909 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
914 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
916 s
->has_write_zeroes
= false;
922 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
924 int ret
= -EOPNOTSUPP
;
925 BDRVRawState
*s
= aiocb
->bs
->opaque
;
927 if (!s
->has_discard
) {
931 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
934 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
935 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
938 } while (errno
== EINTR
);
945 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
949 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
951 if (fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
952 aiocb
->aio_offset
, aiocb
->aio_nbytes
) == 0) {
955 } while (errno
== EINTR
);
961 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
963 s
->has_discard
= false;
969 static int aio_worker(void *arg
)
971 RawPosixAIOData
*aiocb
= arg
;
974 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
976 ret
= handle_aiocb_rw(aiocb
);
977 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
&& aiocb
->bs
->growable
) {
978 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
979 0, aiocb
->aio_nbytes
- ret
);
981 ret
= aiocb
->aio_nbytes
;
983 if (ret
== aiocb
->aio_nbytes
) {
985 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
990 ret
= handle_aiocb_rw(aiocb
);
991 if (ret
== aiocb
->aio_nbytes
) {
993 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
998 ret
= handle_aiocb_flush(aiocb
);
1000 case QEMU_AIO_IOCTL
:
1001 ret
= handle_aiocb_ioctl(aiocb
);
1003 case QEMU_AIO_DISCARD
:
1004 ret
= handle_aiocb_discard(aiocb
);
1006 case QEMU_AIO_WRITE_ZEROES
:
1007 ret
= handle_aiocb_write_zeroes(aiocb
);
1010 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
1015 g_slice_free(RawPosixAIOData
, aiocb
);
1019 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
1020 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1023 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
1027 acb
->aio_type
= type
;
1028 acb
->aio_fildes
= fd
;
1030 acb
->aio_nbytes
= nb_sectors
* BDRV_SECTOR_SIZE
;
1031 acb
->aio_offset
= sector_num
* BDRV_SECTOR_SIZE
;
1034 acb
->aio_iov
= qiov
->iov
;
1035 acb
->aio_niov
= qiov
->niov
;
1036 assert(qiov
->size
== acb
->aio_nbytes
);
1039 trace_paio_submit_co(sector_num
, nb_sectors
, type
);
1040 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1041 return thread_pool_submit_co(pool
, aio_worker
, acb
);
1044 static BlockDriverAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
1045 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1046 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
1048 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
1052 acb
->aio_type
= type
;
1053 acb
->aio_fildes
= fd
;
1055 acb
->aio_nbytes
= nb_sectors
* BDRV_SECTOR_SIZE
;
1056 acb
->aio_offset
= sector_num
* BDRV_SECTOR_SIZE
;
1059 acb
->aio_iov
= qiov
->iov
;
1060 acb
->aio_niov
= qiov
->niov
;
1061 assert(qiov
->size
== acb
->aio_nbytes
);
1064 trace_paio_submit(acb
, opaque
, sector_num
, nb_sectors
, type
);
1065 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1066 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1069 static BlockDriverAIOCB
*raw_aio_submit(BlockDriverState
*bs
,
1070 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1071 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
1073 BDRVRawState
*s
= bs
->opaque
;
1075 if (fd_open(bs
) < 0)
1079 * If O_DIRECT is used the buffer needs to be aligned on a sector
1080 * boundary. Check if this is the case or tell the low-level
1081 * driver that it needs to copy the buffer.
1083 if ((bs
->open_flags
& BDRV_O_NOCACHE
)) {
1084 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1085 type
|= QEMU_AIO_MISALIGNED
;
1086 #ifdef CONFIG_LINUX_AIO
1087 } else if (s
->use_aio
) {
1088 return laio_submit(bs
, s
->aio_ctx
, s
->fd
, sector_num
, qiov
,
1089 nb_sectors
, cb
, opaque
, type
);
1094 return paio_submit(bs
, s
->fd
, sector_num
, qiov
, nb_sectors
,
1098 static void raw_aio_plug(BlockDriverState
*bs
)
1100 #ifdef CONFIG_LINUX_AIO
1101 BDRVRawState
*s
= bs
->opaque
;
1103 laio_io_plug(bs
, s
->aio_ctx
);
1108 static void raw_aio_unplug(BlockDriverState
*bs
)
1110 #ifdef CONFIG_LINUX_AIO
1111 BDRVRawState
*s
= bs
->opaque
;
1113 laio_io_unplug(bs
, s
->aio_ctx
, true);
1118 static void raw_aio_flush_io_queue(BlockDriverState
*bs
)
1120 #ifdef CONFIG_LINUX_AIO
1121 BDRVRawState
*s
= bs
->opaque
;
1123 laio_io_unplug(bs
, s
->aio_ctx
, false);
1128 static BlockDriverAIOCB
*raw_aio_readv(BlockDriverState
*bs
,
1129 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1130 BlockDriverCompletionFunc
*cb
, void *opaque
)
1132 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1133 cb
, opaque
, QEMU_AIO_READ
);
1136 static BlockDriverAIOCB
*raw_aio_writev(BlockDriverState
*bs
,
1137 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1138 BlockDriverCompletionFunc
*cb
, void *opaque
)
1140 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1141 cb
, opaque
, QEMU_AIO_WRITE
);
1144 static BlockDriverAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1145 BlockDriverCompletionFunc
*cb
, void *opaque
)
1147 BDRVRawState
*s
= bs
->opaque
;
1149 if (fd_open(bs
) < 0)
1152 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1155 static void raw_close(BlockDriverState
*bs
)
1157 BDRVRawState
*s
= bs
->opaque
;
1159 raw_detach_aio_context(bs
);
1161 #ifdef CONFIG_LINUX_AIO
1163 laio_cleanup(s
->aio_ctx
);
1172 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
1174 BDRVRawState
*s
= bs
->opaque
;
1177 if (fstat(s
->fd
, &st
)) {
1181 if (S_ISREG(st
.st_mode
)) {
1182 if (ftruncate(s
->fd
, offset
) < 0) {
1185 } else if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1186 if (offset
> raw_getlength(bs
)) {
1197 static int64_t raw_getlength(BlockDriverState
*bs
)
1199 BDRVRawState
*s
= bs
->opaque
;
1205 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1206 struct disklabel dl
;
1208 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1210 return (uint64_t)dl
.d_secsize
*
1211 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1215 #elif defined(__NetBSD__)
1216 static int64_t raw_getlength(BlockDriverState
*bs
)
1218 BDRVRawState
*s
= bs
->opaque
;
1224 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1225 struct dkwedge_info dkw
;
1227 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1228 return dkw
.dkw_size
* 512;
1230 struct disklabel dl
;
1232 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1234 return (uint64_t)dl
.d_secsize
*
1235 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1240 #elif defined(__sun__)
1241 static int64_t raw_getlength(BlockDriverState
*bs
)
1243 BDRVRawState
*s
= bs
->opaque
;
1244 struct dk_minfo minfo
;
1254 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1256 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1258 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1262 * There are reports that lseek on some devices fails, but
1263 * irc discussion said that contingency on contingency was overkill.
1265 size
= lseek(s
->fd
, 0, SEEK_END
);
1271 #elif defined(CONFIG_BSD)
1272 static int64_t raw_getlength(BlockDriverState
*bs
)
1274 BDRVRawState
*s
= bs
->opaque
;
1278 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1287 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1290 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1291 #ifdef DIOCGMEDIASIZE
1292 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1293 #elif defined(DIOCGPART)
1296 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1297 size
= pi
.media_size
;
1303 #if defined(__APPLE__) && defined(__MACH__)
1306 size
= lseek(fd
, 0LL, SEEK_END
);
1311 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1314 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1315 if (size
== 2048LL * (unsigned)-1)
1317 /* XXX no disc? maybe we need to reopen... */
1318 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1325 size
= lseek(fd
, 0, SEEK_END
);
1333 static int64_t raw_getlength(BlockDriverState
*bs
)
1335 BDRVRawState
*s
= bs
->opaque
;
1344 size
= lseek(s
->fd
, 0, SEEK_END
);
1352 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
1355 BDRVRawState
*s
= bs
->opaque
;
1357 if (fstat(s
->fd
, &st
) < 0) {
1360 return (int64_t)st
.st_blocks
* 512;
1363 static int raw_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1367 int64_t total_size
= 0;
1369 PreallocMode prealloc
;
1371 Error
*local_err
= NULL
;
1373 strstart(filename
, "file:", &filename
);
1375 /* Read out options */
1376 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1378 nocow
= qemu_opt_get_bool(opts
, BLOCK_OPT_NOCOW
, false);
1379 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
1380 prealloc
= qapi_enum_parse(PreallocMode_lookup
, buf
,
1381 PREALLOC_MODE_MAX
, PREALLOC_MODE_OFF
,
1385 error_propagate(errp
, local_err
);
1390 fd
= qemu_open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
1394 error_setg_errno(errp
, -result
, "Could not create file");
1400 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1401 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1402 * will be ignored since any failure of this operation should not
1403 * block the left work.
1406 if (ioctl(fd
, FS_IOC_GETFLAGS
, &attr
) == 0) {
1407 attr
|= FS_NOCOW_FL
;
1408 ioctl(fd
, FS_IOC_SETFLAGS
, &attr
);
1413 if (ftruncate(fd
, total_size
) != 0) {
1415 error_setg_errno(errp
, -result
, "Could not resize file");
1420 #ifdef CONFIG_POSIX_FALLOCATE
1421 case PREALLOC_MODE_FALLOC
:
1422 /* posix_fallocate() doesn't set errno. */
1423 result
= -posix_fallocate(fd
, 0, total_size
);
1425 error_setg_errno(errp
, -result
,
1426 "Could not preallocate data for the new file");
1430 case PREALLOC_MODE_FULL
:
1432 int64_t num
= 0, left
= total_size
;
1433 buf
= g_malloc0(65536);
1436 num
= MIN(left
, 65536);
1437 result
= write(fd
, buf
, num
);
1440 error_setg_errno(errp
, -result
,
1441 "Could not write to the new file");
1450 case PREALLOC_MODE_OFF
:
1454 error_setg(errp
, "Unsupported preallocation mode: %s",
1455 PreallocMode_lookup
[prealloc
]);
1460 if (qemu_close(fd
) != 0 && result
== 0) {
1462 error_setg_errno(errp
, -result
, "Could not close the new file");
1468 static int64_t try_fiemap(BlockDriverState
*bs
, off_t start
, off_t
*data
,
1469 off_t
*hole
, int nb_sectors
, int *pnum
)
1471 #ifdef CONFIG_FIEMAP
1472 BDRVRawState
*s
= bs
->opaque
;
1473 int64_t ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1476 struct fiemap_extent fe
;
1479 if (s
->skip_fiemap
) {
1483 f
.fm
.fm_start
= start
;
1484 f
.fm
.fm_length
= (int64_t)nb_sectors
* BDRV_SECTOR_SIZE
;
1486 f
.fm
.fm_extent_count
= 1;
1487 f
.fm
.fm_reserved
= 0;
1488 if (ioctl(s
->fd
, FS_IOC_FIEMAP
, &f
) == -1) {
1489 s
->skip_fiemap
= true;
1493 if (f
.fm
.fm_mapped_extents
== 0) {
1494 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1495 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1497 off_t length
= lseek(s
->fd
, 0, SEEK_END
);
1498 *hole
= f
.fm
.fm_start
;
1499 *data
= MIN(f
.fm
.fm_start
+ f
.fm
.fm_length
, length
);
1501 *data
= f
.fe
.fe_logical
;
1502 *hole
= f
.fe
.fe_logical
+ f
.fe
.fe_length
;
1503 if (f
.fe
.fe_flags
& FIEMAP_EXTENT_UNWRITTEN
) {
1504 ret
|= BDRV_BLOCK_ZERO
;
1514 static int64_t try_seek_hole(BlockDriverState
*bs
, off_t start
, off_t
*data
,
1515 off_t
*hole
, int *pnum
)
1517 #if defined SEEK_HOLE && defined SEEK_DATA
1518 BDRVRawState
*s
= bs
->opaque
;
1520 *hole
= lseek(s
->fd
, start
, SEEK_HOLE
);
1522 /* -ENXIO indicates that sector_num was past the end of the file.
1523 * There is a virtual hole there. */
1524 assert(errno
!= -ENXIO
);
1529 if (*hole
> start
) {
1532 /* On a hole. We need another syscall to find its end. */
1533 *data
= lseek(s
->fd
, start
, SEEK_DATA
);
1535 *data
= lseek(s
->fd
, 0, SEEK_END
);
1539 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1546 * Returns true iff the specified sector is present in the disk image. Drivers
1547 * not implementing the functionality are assumed to not support backing files,
1548 * hence all their sectors are reported as allocated.
1550 * If 'sector_num' is beyond the end of the disk image the return value is 0
1551 * and 'pnum' is set to 0.
1553 * 'pnum' is set to the number of sectors (including and immediately following
1554 * the specified sector) that are known to be in the same
1555 * allocated/unallocated state.
1557 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1558 * beyond the end of the disk image it will be clamped.
1560 static int64_t coroutine_fn
raw_co_get_block_status(BlockDriverState
*bs
,
1562 int nb_sectors
, int *pnum
)
1564 off_t start
, data
= 0, hole
= 0;
1572 start
= sector_num
* BDRV_SECTOR_SIZE
;
1574 ret
= try_fiemap(bs
, start
, &data
, &hole
, nb_sectors
, pnum
);
1576 ret
= try_seek_hole(bs
, start
, &data
, &hole
, pnum
);
1578 /* Assume everything is allocated. */
1580 hole
= start
+ nb_sectors
* BDRV_SECTOR_SIZE
;
1581 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1585 if (data
<= start
) {
1586 /* On a data extent, compute sectors to the end of the extent. */
1587 *pnum
= MIN(nb_sectors
, (hole
- start
) / BDRV_SECTOR_SIZE
);
1589 /* On a hole, compute sectors to the beginning of the next extent. */
1590 *pnum
= MIN(nb_sectors
, (data
- start
) / BDRV_SECTOR_SIZE
);
1591 ret
&= ~BDRV_BLOCK_DATA
;
1592 ret
|= BDRV_BLOCK_ZERO
;
1598 static coroutine_fn BlockDriverAIOCB
*raw_aio_discard(BlockDriverState
*bs
,
1599 int64_t sector_num
, int nb_sectors
,
1600 BlockDriverCompletionFunc
*cb
, void *opaque
)
1602 BDRVRawState
*s
= bs
->opaque
;
1604 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1605 cb
, opaque
, QEMU_AIO_DISCARD
);
1608 static int coroutine_fn
raw_co_write_zeroes(
1609 BlockDriverState
*bs
, int64_t sector_num
,
1610 int nb_sectors
, BdrvRequestFlags flags
)
1612 BDRVRawState
*s
= bs
->opaque
;
1614 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1615 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1616 QEMU_AIO_WRITE_ZEROES
);
1617 } else if (s
->discard_zeroes
) {
1618 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1624 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1626 BDRVRawState
*s
= bs
->opaque
;
1628 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
1629 bdi
->can_write_zeroes_with_unmap
= s
->discard_zeroes
;
1633 static QemuOptsList raw_create_opts
= {
1634 .name
= "raw-create-opts",
1635 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
1638 .name
= BLOCK_OPT_SIZE
,
1639 .type
= QEMU_OPT_SIZE
,
1640 .help
= "Virtual disk size"
1643 .name
= BLOCK_OPT_NOCOW
,
1644 .type
= QEMU_OPT_BOOL
,
1645 .help
= "Turn off copy-on-write (valid only on btrfs)"
1648 .name
= BLOCK_OPT_PREALLOC
,
1649 .type
= QEMU_OPT_STRING
,
1650 .help
= "Preallocation mode (allowed values: off, falloc, full)"
1652 { /* end of list */ }
1656 static BlockDriver bdrv_file
= {
1657 .format_name
= "file",
1658 .protocol_name
= "file",
1659 .instance_size
= sizeof(BDRVRawState
),
1660 .bdrv_needs_filename
= true,
1661 .bdrv_probe
= NULL
, /* no probe for protocols */
1662 .bdrv_parse_filename
= raw_parse_filename
,
1663 .bdrv_file_open
= raw_open
,
1664 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1665 .bdrv_reopen_commit
= raw_reopen_commit
,
1666 .bdrv_reopen_abort
= raw_reopen_abort
,
1667 .bdrv_close
= raw_close
,
1668 .bdrv_create
= raw_create
,
1669 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
1670 .bdrv_co_get_block_status
= raw_co_get_block_status
,
1671 .bdrv_co_write_zeroes
= raw_co_write_zeroes
,
1673 .bdrv_aio_readv
= raw_aio_readv
,
1674 .bdrv_aio_writev
= raw_aio_writev
,
1675 .bdrv_aio_flush
= raw_aio_flush
,
1676 .bdrv_aio_discard
= raw_aio_discard
,
1677 .bdrv_refresh_limits
= raw_refresh_limits
,
1678 .bdrv_io_plug
= raw_aio_plug
,
1679 .bdrv_io_unplug
= raw_aio_unplug
,
1680 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
1682 .bdrv_truncate
= raw_truncate
,
1683 .bdrv_getlength
= raw_getlength
,
1684 .bdrv_get_info
= raw_get_info
,
1685 .bdrv_get_allocated_file_size
1686 = raw_get_allocated_file_size
,
1688 .bdrv_detach_aio_context
= raw_detach_aio_context
,
1689 .bdrv_attach_aio_context
= raw_attach_aio_context
,
1691 .create_opts
= &raw_create_opts
,
1694 /***********************************************/
1697 #if defined(__APPLE__) && defined(__MACH__)
1698 static kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
);
1699 static kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
);
1701 kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
)
1703 kern_return_t kernResult
;
1704 mach_port_t masterPort
;
1705 CFMutableDictionaryRef classesToMatch
;
1707 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
1708 if ( KERN_SUCCESS
!= kernResult
) {
1709 printf( "IOMasterPort returned %d\n", kernResult
);
1712 classesToMatch
= IOServiceMatching( kIOCDMediaClass
);
1713 if ( classesToMatch
== NULL
) {
1714 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1716 CFDictionarySetValue( classesToMatch
, CFSTR( kIOMediaEjectableKey
), kCFBooleanTrue
);
1718 kernResult
= IOServiceGetMatchingServices( masterPort
, classesToMatch
, mediaIterator
);
1719 if ( KERN_SUCCESS
!= kernResult
)
1721 printf( "IOServiceGetMatchingServices returned %d\n", kernResult
);
1727 kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
)
1729 io_object_t nextMedia
;
1730 kern_return_t kernResult
= KERN_FAILURE
;
1732 nextMedia
= IOIteratorNext( mediaIterator
);
1735 CFTypeRef bsdPathAsCFString
;
1736 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
1737 if ( bsdPathAsCFString
) {
1738 size_t devPathLength
;
1739 strcpy( bsdPath
, _PATH_DEV
);
1740 strcat( bsdPath
, "r" );
1741 devPathLength
= strlen( bsdPath
);
1742 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
1743 kernResult
= KERN_SUCCESS
;
1745 CFRelease( bsdPathAsCFString
);
1747 IOObjectRelease( nextMedia
);
1755 static int hdev_probe_device(const char *filename
)
1759 /* allow a dedicated CD-ROM driver to match with a higher priority */
1760 if (strstart(filename
, "/dev/cdrom", NULL
))
1763 if (stat(filename
, &st
) >= 0 &&
1764 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
1771 static int check_hdev_writable(BDRVRawState
*s
)
1773 #if defined(BLKROGET)
1774 /* Linux block devices can be configured "read-only" using blockdev(8).
1775 * This is independent of device node permissions and therefore open(2)
1776 * with O_RDWR succeeds. Actual writes fail with EPERM.
1778 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1779 * check for read-only block devices so that Linux block devices behave
1785 if (fstat(s
->fd
, &st
)) {
1789 if (!S_ISBLK(st
.st_mode
)) {
1793 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
1800 #endif /* defined(BLKROGET) */
1804 static void hdev_parse_filename(const char *filename
, QDict
*options
,
1807 /* The prefix is optional, just as for "file". */
1808 strstart(filename
, "host_device:", &filename
);
1810 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
1813 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1816 BDRVRawState
*s
= bs
->opaque
;
1817 Error
*local_err
= NULL
;
1819 const char *filename
= qdict_get_str(options
, "filename");
1821 #if defined(__APPLE__) && defined(__MACH__)
1822 if (strstart(filename
, "/dev/cdrom", NULL
)) {
1823 kern_return_t kernResult
;
1824 io_iterator_t mediaIterator
;
1825 char bsdPath
[ MAXPATHLEN
];
1828 kernResult
= FindEjectableCDMedia( &mediaIterator
);
1829 kernResult
= GetBSDPath( mediaIterator
, bsdPath
, sizeof( bsdPath
) );
1831 if ( bsdPath
[ 0 ] != '\0' ) {
1832 strcat(bsdPath
,"s0");
1833 /* some CDs don't have a partition 0 */
1834 fd
= qemu_open(bsdPath
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
1836 bsdPath
[strlen(bsdPath
)-1] = '1';
1841 qdict_put(options
, "filename", qstring_from_str(filename
));
1844 if ( mediaIterator
)
1845 IOObjectRelease( mediaIterator
);
1849 s
->type
= FTYPE_FILE
;
1850 #if defined(__linux__)
1852 char resolved_path
[ MAXPATHLEN
], *temp
;
1854 temp
= realpath(filename
, resolved_path
);
1855 if (temp
&& strstart(temp
, "/dev/sg", NULL
)) {
1861 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
1864 error_propagate(errp
, local_err
);
1869 if (flags
& BDRV_O_RDWR
) {
1870 ret
= check_hdev_writable(s
);
1873 error_setg_errno(errp
, -ret
, "The device is not writable");
1881 #if defined(__linux__)
1882 /* Note: we do not have a reliable method to detect if the floppy is
1883 present. The current method is to try to open the floppy at every
1884 I/O and to keep it opened during a few hundreds of ms. */
1885 static int fd_open(BlockDriverState
*bs
)
1887 BDRVRawState
*s
= bs
->opaque
;
1888 int last_media_present
;
1890 if (s
->type
!= FTYPE_FD
)
1892 last_media_present
= (s
->fd
>= 0);
1894 (get_clock() - s
->fd_open_time
) >= FD_OPEN_TIMEOUT
) {
1898 printf("Floppy closed\n");
1902 if (s
->fd_got_error
&&
1903 (get_clock() - s
->fd_error_time
) < FD_OPEN_TIMEOUT
) {
1905 printf("No floppy (open delayed)\n");
1909 s
->fd
= qemu_open(bs
->filename
, s
->open_flags
& ~O_NONBLOCK
);
1911 s
->fd_error_time
= get_clock();
1912 s
->fd_got_error
= 1;
1913 if (last_media_present
)
1914 s
->fd_media_changed
= 1;
1916 printf("No floppy\n");
1921 printf("Floppy opened\n");
1924 if (!last_media_present
)
1925 s
->fd_media_changed
= 1;
1926 s
->fd_open_time
= get_clock();
1927 s
->fd_got_error
= 0;
1931 static int hdev_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
1933 BDRVRawState
*s
= bs
->opaque
;
1935 return ioctl(s
->fd
, req
, buf
);
1938 static BlockDriverAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
1939 unsigned long int req
, void *buf
,
1940 BlockDriverCompletionFunc
*cb
, void *opaque
)
1942 BDRVRawState
*s
= bs
->opaque
;
1943 RawPosixAIOData
*acb
;
1946 if (fd_open(bs
) < 0)
1949 acb
= g_slice_new(RawPosixAIOData
);
1951 acb
->aio_type
= QEMU_AIO_IOCTL
;
1952 acb
->aio_fildes
= s
->fd
;
1953 acb
->aio_offset
= 0;
1954 acb
->aio_ioctl_buf
= buf
;
1955 acb
->aio_ioctl_cmd
= req
;
1956 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1957 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1960 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1961 static int fd_open(BlockDriverState
*bs
)
1963 BDRVRawState
*s
= bs
->opaque
;
1965 /* this is just to ensure s->fd is sane (its called by io ops) */
1970 #else /* !linux && !FreeBSD */
1972 static int fd_open(BlockDriverState
*bs
)
1977 #endif /* !linux && !FreeBSD */
1979 static coroutine_fn BlockDriverAIOCB
*hdev_aio_discard(BlockDriverState
*bs
,
1980 int64_t sector_num
, int nb_sectors
,
1981 BlockDriverCompletionFunc
*cb
, void *opaque
)
1983 BDRVRawState
*s
= bs
->opaque
;
1985 if (fd_open(bs
) < 0) {
1988 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1989 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1992 static coroutine_fn
int hdev_co_write_zeroes(BlockDriverState
*bs
,
1993 int64_t sector_num
, int nb_sectors
, BdrvRequestFlags flags
)
1995 BDRVRawState
*s
= bs
->opaque
;
2002 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
2003 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
2004 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
2005 } else if (s
->discard_zeroes
) {
2006 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
2007 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2012 static int hdev_create(const char *filename
, QemuOpts
*opts
,
2017 struct stat stat_buf
;
2018 int64_t total_size
= 0;
2021 /* This function is used by all three protocol block drivers and therefore
2022 * any of these three prefixes may be given.
2023 * The return value has to be stored somewhere, otherwise this is an error
2024 * due to -Werror=unused-value. */
2026 strstart(filename
, "host_device:", &filename
) ||
2027 strstart(filename
, "host_cdrom:" , &filename
) ||
2028 strstart(filename
, "host_floppy:", &filename
);
2032 /* Read out options */
2033 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2036 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
2039 error_setg_errno(errp
, -ret
, "Could not open device");
2043 if (fstat(fd
, &stat_buf
) < 0) {
2045 error_setg_errno(errp
, -ret
, "Could not stat device");
2046 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
2048 "The given file is neither a block nor a character device");
2050 } else if (lseek(fd
, 0, SEEK_END
) < total_size
) {
2051 error_setg(errp
, "Device is too small");
2059 static BlockDriver bdrv_host_device
= {
2060 .format_name
= "host_device",
2061 .protocol_name
= "host_device",
2062 .instance_size
= sizeof(BDRVRawState
),
2063 .bdrv_needs_filename
= true,
2064 .bdrv_probe_device
= hdev_probe_device
,
2065 .bdrv_parse_filename
= hdev_parse_filename
,
2066 .bdrv_file_open
= hdev_open
,
2067 .bdrv_close
= raw_close
,
2068 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2069 .bdrv_reopen_commit
= raw_reopen_commit
,
2070 .bdrv_reopen_abort
= raw_reopen_abort
,
2071 .bdrv_create
= hdev_create
,
2072 .create_opts
= &raw_create_opts
,
2073 .bdrv_co_write_zeroes
= hdev_co_write_zeroes
,
2075 .bdrv_aio_readv
= raw_aio_readv
,
2076 .bdrv_aio_writev
= raw_aio_writev
,
2077 .bdrv_aio_flush
= raw_aio_flush
,
2078 .bdrv_aio_discard
= hdev_aio_discard
,
2079 .bdrv_refresh_limits
= raw_refresh_limits
,
2080 .bdrv_io_plug
= raw_aio_plug
,
2081 .bdrv_io_unplug
= raw_aio_unplug
,
2082 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2084 .bdrv_truncate
= raw_truncate
,
2085 .bdrv_getlength
= raw_getlength
,
2086 .bdrv_get_info
= raw_get_info
,
2087 .bdrv_get_allocated_file_size
2088 = raw_get_allocated_file_size
,
2090 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2091 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2093 /* generic scsi device */
2095 .bdrv_ioctl
= hdev_ioctl
,
2096 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2101 static void floppy_parse_filename(const char *filename
, QDict
*options
,
2104 /* The prefix is optional, just as for "file". */
2105 strstart(filename
, "host_floppy:", &filename
);
2107 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2110 static int floppy_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2113 BDRVRawState
*s
= bs
->opaque
;
2114 Error
*local_err
= NULL
;
2119 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2120 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2123 error_propagate(errp
, local_err
);
2128 /* close fd so that we can reopen it as needed */
2131 s
->fd_media_changed
= 1;
2136 static int floppy_probe_device(const char *filename
)
2140 struct floppy_struct fdparam
;
2143 if (strstart(filename
, "/dev/fd", NULL
) &&
2144 !strstart(filename
, "/dev/fdset/", NULL
)) {
2148 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2152 ret
= fstat(fd
, &st
);
2153 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2157 /* Attempt to detect via a floppy specific ioctl */
2158 ret
= ioctl(fd
, FDGETPRM
, &fdparam
);
2169 static int floppy_is_inserted(BlockDriverState
*bs
)
2171 return fd_open(bs
) >= 0;
2174 static int floppy_media_changed(BlockDriverState
*bs
)
2176 BDRVRawState
*s
= bs
->opaque
;
2180 * XXX: we do not have a true media changed indication.
2181 * It does not work if the floppy is changed without trying to read it.
2184 ret
= s
->fd_media_changed
;
2185 s
->fd_media_changed
= 0;
2187 printf("Floppy changed=%d\n", ret
);
2192 static void floppy_eject(BlockDriverState
*bs
, bool eject_flag
)
2194 BDRVRawState
*s
= bs
->opaque
;
2201 fd
= qemu_open(bs
->filename
, s
->open_flags
| O_NONBLOCK
);
2203 if (ioctl(fd
, FDEJECT
, 0) < 0)
2209 static BlockDriver bdrv_host_floppy
= {
2210 .format_name
= "host_floppy",
2211 .protocol_name
= "host_floppy",
2212 .instance_size
= sizeof(BDRVRawState
),
2213 .bdrv_needs_filename
= true,
2214 .bdrv_probe_device
= floppy_probe_device
,
2215 .bdrv_parse_filename
= floppy_parse_filename
,
2216 .bdrv_file_open
= floppy_open
,
2217 .bdrv_close
= raw_close
,
2218 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2219 .bdrv_reopen_commit
= raw_reopen_commit
,
2220 .bdrv_reopen_abort
= raw_reopen_abort
,
2221 .bdrv_create
= hdev_create
,
2222 .create_opts
= &raw_create_opts
,
2224 .bdrv_aio_readv
= raw_aio_readv
,
2225 .bdrv_aio_writev
= raw_aio_writev
,
2226 .bdrv_aio_flush
= raw_aio_flush
,
2227 .bdrv_refresh_limits
= raw_refresh_limits
,
2228 .bdrv_io_plug
= raw_aio_plug
,
2229 .bdrv_io_unplug
= raw_aio_unplug
,
2230 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2232 .bdrv_truncate
= raw_truncate
,
2233 .bdrv_getlength
= raw_getlength
,
2234 .has_variable_length
= true,
2235 .bdrv_get_allocated_file_size
2236 = raw_get_allocated_file_size
,
2238 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2239 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2241 /* removable device support */
2242 .bdrv_is_inserted
= floppy_is_inserted
,
2243 .bdrv_media_changed
= floppy_media_changed
,
2244 .bdrv_eject
= floppy_eject
,
2248 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2249 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2252 /* The prefix is optional, just as for "file". */
2253 strstart(filename
, "host_cdrom:", &filename
);
2255 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2260 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2263 BDRVRawState
*s
= bs
->opaque
;
2264 Error
*local_err
= NULL
;
2269 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2270 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2272 error_propagate(errp
, local_err
);
2277 static int cdrom_probe_device(const char *filename
)
2283 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2287 ret
= fstat(fd
, &st
);
2288 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2292 /* Attempt to detect via a CDROM specific ioctl */
2293 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2303 static int cdrom_is_inserted(BlockDriverState
*bs
)
2305 BDRVRawState
*s
= bs
->opaque
;
2308 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2309 if (ret
== CDS_DISC_OK
)
2314 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2316 BDRVRawState
*s
= bs
->opaque
;
2319 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2320 perror("CDROMEJECT");
2322 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2323 perror("CDROMEJECT");
2327 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2329 BDRVRawState
*s
= bs
->opaque
;
2331 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2333 * Note: an error can happen if the distribution automatically
2336 /* perror("CDROM_LOCKDOOR"); */
2340 static BlockDriver bdrv_host_cdrom
= {
2341 .format_name
= "host_cdrom",
2342 .protocol_name
= "host_cdrom",
2343 .instance_size
= sizeof(BDRVRawState
),
2344 .bdrv_needs_filename
= true,
2345 .bdrv_probe_device
= cdrom_probe_device
,
2346 .bdrv_parse_filename
= cdrom_parse_filename
,
2347 .bdrv_file_open
= cdrom_open
,
2348 .bdrv_close
= raw_close
,
2349 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2350 .bdrv_reopen_commit
= raw_reopen_commit
,
2351 .bdrv_reopen_abort
= raw_reopen_abort
,
2352 .bdrv_create
= hdev_create
,
2353 .create_opts
= &raw_create_opts
,
2355 .bdrv_aio_readv
= raw_aio_readv
,
2356 .bdrv_aio_writev
= raw_aio_writev
,
2357 .bdrv_aio_flush
= raw_aio_flush
,
2358 .bdrv_refresh_limits
= raw_refresh_limits
,
2359 .bdrv_io_plug
= raw_aio_plug
,
2360 .bdrv_io_unplug
= raw_aio_unplug
,
2361 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2363 .bdrv_truncate
= raw_truncate
,
2364 .bdrv_getlength
= raw_getlength
,
2365 .has_variable_length
= true,
2366 .bdrv_get_allocated_file_size
2367 = raw_get_allocated_file_size
,
2369 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2370 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2372 /* removable device support */
2373 .bdrv_is_inserted
= cdrom_is_inserted
,
2374 .bdrv_eject
= cdrom_eject
,
2375 .bdrv_lock_medium
= cdrom_lock_medium
,
2377 /* generic scsi device */
2378 .bdrv_ioctl
= hdev_ioctl
,
2379 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2381 #endif /* __linux__ */
2383 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2384 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2387 BDRVRawState
*s
= bs
->opaque
;
2388 Error
*local_err
= NULL
;
2393 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2396 error_propagate(errp
, local_err
);
2401 /* make sure the door isn't locked at this time */
2402 ioctl(s
->fd
, CDIOCALLOW
);
2406 static int cdrom_probe_device(const char *filename
)
2408 if (strstart(filename
, "/dev/cd", NULL
) ||
2409 strstart(filename
, "/dev/acd", NULL
))
2414 static int cdrom_reopen(BlockDriverState
*bs
)
2416 BDRVRawState
*s
= bs
->opaque
;
2420 * Force reread of possibly changed/newly loaded disc,
2421 * FreeBSD seems to not notice sometimes...
2425 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
2432 /* make sure the door isn't locked at this time */
2433 ioctl(s
->fd
, CDIOCALLOW
);
2437 static int cdrom_is_inserted(BlockDriverState
*bs
)
2439 return raw_getlength(bs
) > 0;
2442 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2444 BDRVRawState
*s
= bs
->opaque
;
2449 (void) ioctl(s
->fd
, CDIOCALLOW
);
2452 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
2453 perror("CDIOCEJECT");
2455 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
2456 perror("CDIOCCLOSE");
2462 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2464 BDRVRawState
*s
= bs
->opaque
;
2468 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
2470 * Note: an error can happen if the distribution automatically
2473 /* perror("CDROM_LOCKDOOR"); */
2477 static BlockDriver bdrv_host_cdrom
= {
2478 .format_name
= "host_cdrom",
2479 .protocol_name
= "host_cdrom",
2480 .instance_size
= sizeof(BDRVRawState
),
2481 .bdrv_needs_filename
= true,
2482 .bdrv_probe_device
= cdrom_probe_device
,
2483 .bdrv_parse_filename
= cdrom_parse_filename
,
2484 .bdrv_file_open
= cdrom_open
,
2485 .bdrv_close
= raw_close
,
2486 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2487 .bdrv_reopen_commit
= raw_reopen_commit
,
2488 .bdrv_reopen_abort
= raw_reopen_abort
,
2489 .bdrv_create
= hdev_create
,
2490 .create_opts
= &raw_create_opts
,
2492 .bdrv_aio_readv
= raw_aio_readv
,
2493 .bdrv_aio_writev
= raw_aio_writev
,
2494 .bdrv_aio_flush
= raw_aio_flush
,
2495 .bdrv_refresh_limits
= raw_refresh_limits
,
2496 .bdrv_io_plug
= raw_aio_plug
,
2497 .bdrv_io_unplug
= raw_aio_unplug
,
2498 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2500 .bdrv_truncate
= raw_truncate
,
2501 .bdrv_getlength
= raw_getlength
,
2502 .has_variable_length
= true,
2503 .bdrv_get_allocated_file_size
2504 = raw_get_allocated_file_size
,
2506 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2507 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2509 /* removable device support */
2510 .bdrv_is_inserted
= cdrom_is_inserted
,
2511 .bdrv_eject
= cdrom_eject
,
2512 .bdrv_lock_medium
= cdrom_lock_medium
,
2514 #endif /* __FreeBSD__ */
2516 static void bdrv_file_init(void)
2519 * Register all the drivers. Note that order is important, the driver
2520 * registered last will get probed first.
2522 bdrv_register(&bdrv_file
);
2523 bdrv_register(&bdrv_host_device
);
2525 bdrv_register(&bdrv_host_floppy
);
2526 bdrv_register(&bdrv_host_cdrom
);
2528 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2529 bdrv_register(&bdrv_host_cdrom
);
2533 block_init(bdrv_file_init
);