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");
1419 if (prealloc
== PREALLOC_MODE_FALLOC
) {
1420 /* posix_fallocate() doesn't set errno. */
1421 result
= -posix_fallocate(fd
, 0, total_size
);
1423 error_setg_errno(errp
, -result
,
1424 "Could not preallocate data for the new file");
1426 } else if (prealloc
== PREALLOC_MODE_FULL
) {
1427 buf
= g_malloc0(65536);
1428 int64_t num
= 0, left
= total_size
;
1431 num
= MIN(left
, 65536);
1432 result
= write(fd
, buf
, num
);
1435 error_setg_errno(errp
, -result
,
1436 "Could not write to the new file");
1443 } else if (prealloc
!= PREALLOC_MODE_OFF
) {
1445 error_setg(errp
, "Unsupported preallocation mode: %s",
1446 PreallocMode_lookup
[prealloc
]);
1450 if (qemu_close(fd
) != 0 && result
== 0) {
1452 error_setg_errno(errp
, -result
, "Could not close the new file");
1458 static int64_t try_fiemap(BlockDriverState
*bs
, off_t start
, off_t
*data
,
1459 off_t
*hole
, int nb_sectors
, int *pnum
)
1461 #ifdef CONFIG_FIEMAP
1462 BDRVRawState
*s
= bs
->opaque
;
1463 int64_t ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1466 struct fiemap_extent fe
;
1469 if (s
->skip_fiemap
) {
1473 f
.fm
.fm_start
= start
;
1474 f
.fm
.fm_length
= (int64_t)nb_sectors
* BDRV_SECTOR_SIZE
;
1476 f
.fm
.fm_extent_count
= 1;
1477 f
.fm
.fm_reserved
= 0;
1478 if (ioctl(s
->fd
, FS_IOC_FIEMAP
, &f
) == -1) {
1479 s
->skip_fiemap
= true;
1483 if (f
.fm
.fm_mapped_extents
== 0) {
1484 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1485 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1487 off_t length
= lseek(s
->fd
, 0, SEEK_END
);
1488 *hole
= f
.fm
.fm_start
;
1489 *data
= MIN(f
.fm
.fm_start
+ f
.fm
.fm_length
, length
);
1491 *data
= f
.fe
.fe_logical
;
1492 *hole
= f
.fe
.fe_logical
+ f
.fe
.fe_length
;
1493 if (f
.fe
.fe_flags
& FIEMAP_EXTENT_UNWRITTEN
) {
1494 ret
|= BDRV_BLOCK_ZERO
;
1504 static int64_t try_seek_hole(BlockDriverState
*bs
, off_t start
, off_t
*data
,
1505 off_t
*hole
, int *pnum
)
1507 #if defined SEEK_HOLE && defined SEEK_DATA
1508 BDRVRawState
*s
= bs
->opaque
;
1510 *hole
= lseek(s
->fd
, start
, SEEK_HOLE
);
1512 /* -ENXIO indicates that sector_num was past the end of the file.
1513 * There is a virtual hole there. */
1514 assert(errno
!= -ENXIO
);
1519 if (*hole
> start
) {
1522 /* On a hole. We need another syscall to find its end. */
1523 *data
= lseek(s
->fd
, start
, SEEK_DATA
);
1525 *data
= lseek(s
->fd
, 0, SEEK_END
);
1529 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1536 * Returns true iff the specified sector is present in the disk image. Drivers
1537 * not implementing the functionality are assumed to not support backing files,
1538 * hence all their sectors are reported as allocated.
1540 * If 'sector_num' is beyond the end of the disk image the return value is 0
1541 * and 'pnum' is set to 0.
1543 * 'pnum' is set to the number of sectors (including and immediately following
1544 * the specified sector) that are known to be in the same
1545 * allocated/unallocated state.
1547 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1548 * beyond the end of the disk image it will be clamped.
1550 static int64_t coroutine_fn
raw_co_get_block_status(BlockDriverState
*bs
,
1552 int nb_sectors
, int *pnum
)
1554 off_t start
, data
= 0, hole
= 0;
1562 start
= sector_num
* BDRV_SECTOR_SIZE
;
1564 ret
= try_fiemap(bs
, start
, &data
, &hole
, nb_sectors
, pnum
);
1566 ret
= try_seek_hole(bs
, start
, &data
, &hole
, pnum
);
1568 /* Assume everything is allocated. */
1570 hole
= start
+ nb_sectors
* BDRV_SECTOR_SIZE
;
1571 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1575 if (data
<= start
) {
1576 /* On a data extent, compute sectors to the end of the extent. */
1577 *pnum
= MIN(nb_sectors
, (hole
- start
) / BDRV_SECTOR_SIZE
);
1579 /* On a hole, compute sectors to the beginning of the next extent. */
1580 *pnum
= MIN(nb_sectors
, (data
- start
) / BDRV_SECTOR_SIZE
);
1581 ret
&= ~BDRV_BLOCK_DATA
;
1582 ret
|= BDRV_BLOCK_ZERO
;
1588 static coroutine_fn BlockDriverAIOCB
*raw_aio_discard(BlockDriverState
*bs
,
1589 int64_t sector_num
, int nb_sectors
,
1590 BlockDriverCompletionFunc
*cb
, void *opaque
)
1592 BDRVRawState
*s
= bs
->opaque
;
1594 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1595 cb
, opaque
, QEMU_AIO_DISCARD
);
1598 static int coroutine_fn
raw_co_write_zeroes(
1599 BlockDriverState
*bs
, int64_t sector_num
,
1600 int nb_sectors
, BdrvRequestFlags flags
)
1602 BDRVRawState
*s
= bs
->opaque
;
1604 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1605 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1606 QEMU_AIO_WRITE_ZEROES
);
1607 } else if (s
->discard_zeroes
) {
1608 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1614 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1616 BDRVRawState
*s
= bs
->opaque
;
1618 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
1619 bdi
->can_write_zeroes_with_unmap
= s
->discard_zeroes
;
1623 static QemuOptsList raw_create_opts
= {
1624 .name
= "raw-create-opts",
1625 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
1628 .name
= BLOCK_OPT_SIZE
,
1629 .type
= QEMU_OPT_SIZE
,
1630 .help
= "Virtual disk size"
1633 .name
= BLOCK_OPT_NOCOW
,
1634 .type
= QEMU_OPT_BOOL
,
1635 .help
= "Turn off copy-on-write (valid only on btrfs)"
1638 .name
= BLOCK_OPT_PREALLOC
,
1639 .type
= QEMU_OPT_STRING
,
1640 .help
= "Preallocation mode (allowed values: off, falloc, full)"
1642 { /* end of list */ }
1646 static BlockDriver bdrv_file
= {
1647 .format_name
= "file",
1648 .protocol_name
= "file",
1649 .instance_size
= sizeof(BDRVRawState
),
1650 .bdrv_needs_filename
= true,
1651 .bdrv_probe
= NULL
, /* no probe for protocols */
1652 .bdrv_parse_filename
= raw_parse_filename
,
1653 .bdrv_file_open
= raw_open
,
1654 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1655 .bdrv_reopen_commit
= raw_reopen_commit
,
1656 .bdrv_reopen_abort
= raw_reopen_abort
,
1657 .bdrv_close
= raw_close
,
1658 .bdrv_create
= raw_create
,
1659 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
1660 .bdrv_co_get_block_status
= raw_co_get_block_status
,
1661 .bdrv_co_write_zeroes
= raw_co_write_zeroes
,
1663 .bdrv_aio_readv
= raw_aio_readv
,
1664 .bdrv_aio_writev
= raw_aio_writev
,
1665 .bdrv_aio_flush
= raw_aio_flush
,
1666 .bdrv_aio_discard
= raw_aio_discard
,
1667 .bdrv_refresh_limits
= raw_refresh_limits
,
1668 .bdrv_io_plug
= raw_aio_plug
,
1669 .bdrv_io_unplug
= raw_aio_unplug
,
1670 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
1672 .bdrv_truncate
= raw_truncate
,
1673 .bdrv_getlength
= raw_getlength
,
1674 .bdrv_get_info
= raw_get_info
,
1675 .bdrv_get_allocated_file_size
1676 = raw_get_allocated_file_size
,
1678 .bdrv_detach_aio_context
= raw_detach_aio_context
,
1679 .bdrv_attach_aio_context
= raw_attach_aio_context
,
1681 .create_opts
= &raw_create_opts
,
1684 /***********************************************/
1687 #if defined(__APPLE__) && defined(__MACH__)
1688 static kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
);
1689 static kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
);
1691 kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
)
1693 kern_return_t kernResult
;
1694 mach_port_t masterPort
;
1695 CFMutableDictionaryRef classesToMatch
;
1697 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
1698 if ( KERN_SUCCESS
!= kernResult
) {
1699 printf( "IOMasterPort returned %d\n", kernResult
);
1702 classesToMatch
= IOServiceMatching( kIOCDMediaClass
);
1703 if ( classesToMatch
== NULL
) {
1704 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1706 CFDictionarySetValue( classesToMatch
, CFSTR( kIOMediaEjectableKey
), kCFBooleanTrue
);
1708 kernResult
= IOServiceGetMatchingServices( masterPort
, classesToMatch
, mediaIterator
);
1709 if ( KERN_SUCCESS
!= kernResult
)
1711 printf( "IOServiceGetMatchingServices returned %d\n", kernResult
);
1717 kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
)
1719 io_object_t nextMedia
;
1720 kern_return_t kernResult
= KERN_FAILURE
;
1722 nextMedia
= IOIteratorNext( mediaIterator
);
1725 CFTypeRef bsdPathAsCFString
;
1726 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
1727 if ( bsdPathAsCFString
) {
1728 size_t devPathLength
;
1729 strcpy( bsdPath
, _PATH_DEV
);
1730 strcat( bsdPath
, "r" );
1731 devPathLength
= strlen( bsdPath
);
1732 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
1733 kernResult
= KERN_SUCCESS
;
1735 CFRelease( bsdPathAsCFString
);
1737 IOObjectRelease( nextMedia
);
1745 static int hdev_probe_device(const char *filename
)
1749 /* allow a dedicated CD-ROM driver to match with a higher priority */
1750 if (strstart(filename
, "/dev/cdrom", NULL
))
1753 if (stat(filename
, &st
) >= 0 &&
1754 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
1761 static int check_hdev_writable(BDRVRawState
*s
)
1763 #if defined(BLKROGET)
1764 /* Linux block devices can be configured "read-only" using blockdev(8).
1765 * This is independent of device node permissions and therefore open(2)
1766 * with O_RDWR succeeds. Actual writes fail with EPERM.
1768 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1769 * check for read-only block devices so that Linux block devices behave
1775 if (fstat(s
->fd
, &st
)) {
1779 if (!S_ISBLK(st
.st_mode
)) {
1783 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
1790 #endif /* defined(BLKROGET) */
1794 static void hdev_parse_filename(const char *filename
, QDict
*options
,
1797 /* The prefix is optional, just as for "file". */
1798 strstart(filename
, "host_device:", &filename
);
1800 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
1803 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1806 BDRVRawState
*s
= bs
->opaque
;
1807 Error
*local_err
= NULL
;
1809 const char *filename
= qdict_get_str(options
, "filename");
1811 #if defined(__APPLE__) && defined(__MACH__)
1812 if (strstart(filename
, "/dev/cdrom", NULL
)) {
1813 kern_return_t kernResult
;
1814 io_iterator_t mediaIterator
;
1815 char bsdPath
[ MAXPATHLEN
];
1818 kernResult
= FindEjectableCDMedia( &mediaIterator
);
1819 kernResult
= GetBSDPath( mediaIterator
, bsdPath
, sizeof( bsdPath
) );
1821 if ( bsdPath
[ 0 ] != '\0' ) {
1822 strcat(bsdPath
,"s0");
1823 /* some CDs don't have a partition 0 */
1824 fd
= qemu_open(bsdPath
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
1826 bsdPath
[strlen(bsdPath
)-1] = '1';
1831 qdict_put(options
, "filename", qstring_from_str(filename
));
1834 if ( mediaIterator
)
1835 IOObjectRelease( mediaIterator
);
1839 s
->type
= FTYPE_FILE
;
1840 #if defined(__linux__)
1842 char resolved_path
[ MAXPATHLEN
], *temp
;
1844 temp
= realpath(filename
, resolved_path
);
1845 if (temp
&& strstart(temp
, "/dev/sg", NULL
)) {
1851 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
1854 error_propagate(errp
, local_err
);
1859 if (flags
& BDRV_O_RDWR
) {
1860 ret
= check_hdev_writable(s
);
1863 error_setg_errno(errp
, -ret
, "The device is not writable");
1871 #if defined(__linux__)
1872 /* Note: we do not have a reliable method to detect if the floppy is
1873 present. The current method is to try to open the floppy at every
1874 I/O and to keep it opened during a few hundreds of ms. */
1875 static int fd_open(BlockDriverState
*bs
)
1877 BDRVRawState
*s
= bs
->opaque
;
1878 int last_media_present
;
1880 if (s
->type
!= FTYPE_FD
)
1882 last_media_present
= (s
->fd
>= 0);
1884 (get_clock() - s
->fd_open_time
) >= FD_OPEN_TIMEOUT
) {
1888 printf("Floppy closed\n");
1892 if (s
->fd_got_error
&&
1893 (get_clock() - s
->fd_error_time
) < FD_OPEN_TIMEOUT
) {
1895 printf("No floppy (open delayed)\n");
1899 s
->fd
= qemu_open(bs
->filename
, s
->open_flags
& ~O_NONBLOCK
);
1901 s
->fd_error_time
= get_clock();
1902 s
->fd_got_error
= 1;
1903 if (last_media_present
)
1904 s
->fd_media_changed
= 1;
1906 printf("No floppy\n");
1911 printf("Floppy opened\n");
1914 if (!last_media_present
)
1915 s
->fd_media_changed
= 1;
1916 s
->fd_open_time
= get_clock();
1917 s
->fd_got_error
= 0;
1921 static int hdev_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
1923 BDRVRawState
*s
= bs
->opaque
;
1925 return ioctl(s
->fd
, req
, buf
);
1928 static BlockDriverAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
1929 unsigned long int req
, void *buf
,
1930 BlockDriverCompletionFunc
*cb
, void *opaque
)
1932 BDRVRawState
*s
= bs
->opaque
;
1933 RawPosixAIOData
*acb
;
1936 if (fd_open(bs
) < 0)
1939 acb
= g_slice_new(RawPosixAIOData
);
1941 acb
->aio_type
= QEMU_AIO_IOCTL
;
1942 acb
->aio_fildes
= s
->fd
;
1943 acb
->aio_offset
= 0;
1944 acb
->aio_ioctl_buf
= buf
;
1945 acb
->aio_ioctl_cmd
= req
;
1946 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1947 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1950 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1951 static int fd_open(BlockDriverState
*bs
)
1953 BDRVRawState
*s
= bs
->opaque
;
1955 /* this is just to ensure s->fd is sane (its called by io ops) */
1960 #else /* !linux && !FreeBSD */
1962 static int fd_open(BlockDriverState
*bs
)
1967 #endif /* !linux && !FreeBSD */
1969 static coroutine_fn BlockDriverAIOCB
*hdev_aio_discard(BlockDriverState
*bs
,
1970 int64_t sector_num
, int nb_sectors
,
1971 BlockDriverCompletionFunc
*cb
, void *opaque
)
1973 BDRVRawState
*s
= bs
->opaque
;
1975 if (fd_open(bs
) < 0) {
1978 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1979 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1982 static coroutine_fn
int hdev_co_write_zeroes(BlockDriverState
*bs
,
1983 int64_t sector_num
, int nb_sectors
, BdrvRequestFlags flags
)
1985 BDRVRawState
*s
= bs
->opaque
;
1992 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1993 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1994 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
1995 } else if (s
->discard_zeroes
) {
1996 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1997 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2002 static int hdev_create(const char *filename
, QemuOpts
*opts
,
2007 struct stat stat_buf
;
2008 int64_t total_size
= 0;
2011 /* This function is used by all three protocol block drivers and therefore
2012 * any of these three prefixes may be given.
2013 * The return value has to be stored somewhere, otherwise this is an error
2014 * due to -Werror=unused-value. */
2016 strstart(filename
, "host_device:", &filename
) ||
2017 strstart(filename
, "host_cdrom:" , &filename
) ||
2018 strstart(filename
, "host_floppy:", &filename
);
2022 /* Read out options */
2023 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2026 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
2029 error_setg_errno(errp
, -ret
, "Could not open device");
2033 if (fstat(fd
, &stat_buf
) < 0) {
2035 error_setg_errno(errp
, -ret
, "Could not stat device");
2036 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
2038 "The given file is neither a block nor a character device");
2040 } else if (lseek(fd
, 0, SEEK_END
) < total_size
) {
2041 error_setg(errp
, "Device is too small");
2049 static BlockDriver bdrv_host_device
= {
2050 .format_name
= "host_device",
2051 .protocol_name
= "host_device",
2052 .instance_size
= sizeof(BDRVRawState
),
2053 .bdrv_needs_filename
= true,
2054 .bdrv_probe_device
= hdev_probe_device
,
2055 .bdrv_parse_filename
= hdev_parse_filename
,
2056 .bdrv_file_open
= hdev_open
,
2057 .bdrv_close
= raw_close
,
2058 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2059 .bdrv_reopen_commit
= raw_reopen_commit
,
2060 .bdrv_reopen_abort
= raw_reopen_abort
,
2061 .bdrv_create
= hdev_create
,
2062 .create_opts
= &raw_create_opts
,
2063 .bdrv_co_write_zeroes
= hdev_co_write_zeroes
,
2065 .bdrv_aio_readv
= raw_aio_readv
,
2066 .bdrv_aio_writev
= raw_aio_writev
,
2067 .bdrv_aio_flush
= raw_aio_flush
,
2068 .bdrv_aio_discard
= hdev_aio_discard
,
2069 .bdrv_refresh_limits
= raw_refresh_limits
,
2070 .bdrv_io_plug
= raw_aio_plug
,
2071 .bdrv_io_unplug
= raw_aio_unplug
,
2072 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2074 .bdrv_truncate
= raw_truncate
,
2075 .bdrv_getlength
= raw_getlength
,
2076 .bdrv_get_info
= raw_get_info
,
2077 .bdrv_get_allocated_file_size
2078 = raw_get_allocated_file_size
,
2080 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2081 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2083 /* generic scsi device */
2085 .bdrv_ioctl
= hdev_ioctl
,
2086 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2091 static void floppy_parse_filename(const char *filename
, QDict
*options
,
2094 /* The prefix is optional, just as for "file". */
2095 strstart(filename
, "host_floppy:", &filename
);
2097 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2100 static int floppy_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2103 BDRVRawState
*s
= bs
->opaque
;
2104 Error
*local_err
= NULL
;
2109 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2110 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2113 error_propagate(errp
, local_err
);
2118 /* close fd so that we can reopen it as needed */
2121 s
->fd_media_changed
= 1;
2126 static int floppy_probe_device(const char *filename
)
2130 struct floppy_struct fdparam
;
2133 if (strstart(filename
, "/dev/fd", NULL
) &&
2134 !strstart(filename
, "/dev/fdset/", NULL
)) {
2138 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2142 ret
= fstat(fd
, &st
);
2143 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2147 /* Attempt to detect via a floppy specific ioctl */
2148 ret
= ioctl(fd
, FDGETPRM
, &fdparam
);
2159 static int floppy_is_inserted(BlockDriverState
*bs
)
2161 return fd_open(bs
) >= 0;
2164 static int floppy_media_changed(BlockDriverState
*bs
)
2166 BDRVRawState
*s
= bs
->opaque
;
2170 * XXX: we do not have a true media changed indication.
2171 * It does not work if the floppy is changed without trying to read it.
2174 ret
= s
->fd_media_changed
;
2175 s
->fd_media_changed
= 0;
2177 printf("Floppy changed=%d\n", ret
);
2182 static void floppy_eject(BlockDriverState
*bs
, bool eject_flag
)
2184 BDRVRawState
*s
= bs
->opaque
;
2191 fd
= qemu_open(bs
->filename
, s
->open_flags
| O_NONBLOCK
);
2193 if (ioctl(fd
, FDEJECT
, 0) < 0)
2199 static BlockDriver bdrv_host_floppy
= {
2200 .format_name
= "host_floppy",
2201 .protocol_name
= "host_floppy",
2202 .instance_size
= sizeof(BDRVRawState
),
2203 .bdrv_needs_filename
= true,
2204 .bdrv_probe_device
= floppy_probe_device
,
2205 .bdrv_parse_filename
= floppy_parse_filename
,
2206 .bdrv_file_open
= floppy_open
,
2207 .bdrv_close
= raw_close
,
2208 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2209 .bdrv_reopen_commit
= raw_reopen_commit
,
2210 .bdrv_reopen_abort
= raw_reopen_abort
,
2211 .bdrv_create
= hdev_create
,
2212 .create_opts
= &raw_create_opts
,
2214 .bdrv_aio_readv
= raw_aio_readv
,
2215 .bdrv_aio_writev
= raw_aio_writev
,
2216 .bdrv_aio_flush
= raw_aio_flush
,
2217 .bdrv_refresh_limits
= raw_refresh_limits
,
2218 .bdrv_io_plug
= raw_aio_plug
,
2219 .bdrv_io_unplug
= raw_aio_unplug
,
2220 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2222 .bdrv_truncate
= raw_truncate
,
2223 .bdrv_getlength
= raw_getlength
,
2224 .has_variable_length
= true,
2225 .bdrv_get_allocated_file_size
2226 = raw_get_allocated_file_size
,
2228 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2229 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2231 /* removable device support */
2232 .bdrv_is_inserted
= floppy_is_inserted
,
2233 .bdrv_media_changed
= floppy_media_changed
,
2234 .bdrv_eject
= floppy_eject
,
2238 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2239 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2242 /* The prefix is optional, just as for "file". */
2243 strstart(filename
, "host_cdrom:", &filename
);
2245 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2250 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2253 BDRVRawState
*s
= bs
->opaque
;
2254 Error
*local_err
= NULL
;
2259 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2260 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2262 error_propagate(errp
, local_err
);
2267 static int cdrom_probe_device(const char *filename
)
2273 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2277 ret
= fstat(fd
, &st
);
2278 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2282 /* Attempt to detect via a CDROM specific ioctl */
2283 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2293 static int cdrom_is_inserted(BlockDriverState
*bs
)
2295 BDRVRawState
*s
= bs
->opaque
;
2298 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2299 if (ret
== CDS_DISC_OK
)
2304 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2306 BDRVRawState
*s
= bs
->opaque
;
2309 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2310 perror("CDROMEJECT");
2312 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2313 perror("CDROMEJECT");
2317 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2319 BDRVRawState
*s
= bs
->opaque
;
2321 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2323 * Note: an error can happen if the distribution automatically
2326 /* perror("CDROM_LOCKDOOR"); */
2330 static BlockDriver bdrv_host_cdrom
= {
2331 .format_name
= "host_cdrom",
2332 .protocol_name
= "host_cdrom",
2333 .instance_size
= sizeof(BDRVRawState
),
2334 .bdrv_needs_filename
= true,
2335 .bdrv_probe_device
= cdrom_probe_device
,
2336 .bdrv_parse_filename
= cdrom_parse_filename
,
2337 .bdrv_file_open
= cdrom_open
,
2338 .bdrv_close
= raw_close
,
2339 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2340 .bdrv_reopen_commit
= raw_reopen_commit
,
2341 .bdrv_reopen_abort
= raw_reopen_abort
,
2342 .bdrv_create
= hdev_create
,
2343 .create_opts
= &raw_create_opts
,
2345 .bdrv_aio_readv
= raw_aio_readv
,
2346 .bdrv_aio_writev
= raw_aio_writev
,
2347 .bdrv_aio_flush
= raw_aio_flush
,
2348 .bdrv_refresh_limits
= raw_refresh_limits
,
2349 .bdrv_io_plug
= raw_aio_plug
,
2350 .bdrv_io_unplug
= raw_aio_unplug
,
2351 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2353 .bdrv_truncate
= raw_truncate
,
2354 .bdrv_getlength
= raw_getlength
,
2355 .has_variable_length
= true,
2356 .bdrv_get_allocated_file_size
2357 = raw_get_allocated_file_size
,
2359 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2360 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2362 /* removable device support */
2363 .bdrv_is_inserted
= cdrom_is_inserted
,
2364 .bdrv_eject
= cdrom_eject
,
2365 .bdrv_lock_medium
= cdrom_lock_medium
,
2367 /* generic scsi device */
2368 .bdrv_ioctl
= hdev_ioctl
,
2369 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2371 #endif /* __linux__ */
2373 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2374 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2377 BDRVRawState
*s
= bs
->opaque
;
2378 Error
*local_err
= NULL
;
2383 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2386 error_propagate(errp
, local_err
);
2391 /* make sure the door isn't locked at this time */
2392 ioctl(s
->fd
, CDIOCALLOW
);
2396 static int cdrom_probe_device(const char *filename
)
2398 if (strstart(filename
, "/dev/cd", NULL
) ||
2399 strstart(filename
, "/dev/acd", NULL
))
2404 static int cdrom_reopen(BlockDriverState
*bs
)
2406 BDRVRawState
*s
= bs
->opaque
;
2410 * Force reread of possibly changed/newly loaded disc,
2411 * FreeBSD seems to not notice sometimes...
2415 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
2422 /* make sure the door isn't locked at this time */
2423 ioctl(s
->fd
, CDIOCALLOW
);
2427 static int cdrom_is_inserted(BlockDriverState
*bs
)
2429 return raw_getlength(bs
) > 0;
2432 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2434 BDRVRawState
*s
= bs
->opaque
;
2439 (void) ioctl(s
->fd
, CDIOCALLOW
);
2442 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
2443 perror("CDIOCEJECT");
2445 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
2446 perror("CDIOCCLOSE");
2452 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2454 BDRVRawState
*s
= bs
->opaque
;
2458 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
2460 * Note: an error can happen if the distribution automatically
2463 /* perror("CDROM_LOCKDOOR"); */
2467 static BlockDriver bdrv_host_cdrom
= {
2468 .format_name
= "host_cdrom",
2469 .protocol_name
= "host_cdrom",
2470 .instance_size
= sizeof(BDRVRawState
),
2471 .bdrv_needs_filename
= true,
2472 .bdrv_probe_device
= cdrom_probe_device
,
2473 .bdrv_parse_filename
= cdrom_parse_filename
,
2474 .bdrv_file_open
= cdrom_open
,
2475 .bdrv_close
= raw_close
,
2476 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2477 .bdrv_reopen_commit
= raw_reopen_commit
,
2478 .bdrv_reopen_abort
= raw_reopen_abort
,
2479 .bdrv_create
= hdev_create
,
2480 .create_opts
= &raw_create_opts
,
2482 .bdrv_aio_readv
= raw_aio_readv
,
2483 .bdrv_aio_writev
= raw_aio_writev
,
2484 .bdrv_aio_flush
= raw_aio_flush
,
2485 .bdrv_refresh_limits
= raw_refresh_limits
,
2486 .bdrv_io_plug
= raw_aio_plug
,
2487 .bdrv_io_unplug
= raw_aio_unplug
,
2488 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2490 .bdrv_truncate
= raw_truncate
,
2491 .bdrv_getlength
= raw_getlength
,
2492 .has_variable_length
= true,
2493 .bdrv_get_allocated_file_size
2494 = raw_get_allocated_file_size
,
2496 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2497 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2499 /* removable device support */
2500 .bdrv_is_inserted
= cdrom_is_inserted
,
2501 .bdrv_eject
= cdrom_eject
,
2502 .bdrv_lock_medium
= cdrom_lock_medium
,
2504 #endif /* __FreeBSD__ */
2506 static void bdrv_file_init(void)
2509 * Register all the drivers. Note that order is important, the driver
2510 * registered last will get probed first.
2512 bdrv_register(&bdrv_file
);
2513 bdrv_register(&bdrv_host_device
);
2515 bdrv_register(&bdrv_host_floppy
);
2516 bdrv_register(&bdrv_host_cdrom
);
2518 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2519 bdrv_register(&bdrv_host_cdrom
);
2523 block_init(bdrv_file_init
);