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"
34 #if defined(__APPLE__) && (__MACH__)
36 #include <sys/param.h>
37 #include <IOKit/IOKitLib.h>
38 #include <IOKit/IOBSD.h>
39 #include <IOKit/storage/IOMediaBSDClient.h>
40 #include <IOKit/storage/IOMedia.h>
41 #include <IOKit/storage/IOCDMedia.h>
42 //#include <IOKit/storage/IOCDTypes.h>
43 #include <CoreFoundation/CoreFoundation.h>
47 #define _POSIX_PTHREAD_SEMANTICS 1
51 #include <sys/types.h>
53 #include <sys/ioctl.h>
54 #include <sys/param.h>
55 #include <linux/cdrom.h>
59 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
63 #include <linux/fiemap.h>
65 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
66 #include <linux/falloc.h>
68 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
74 #include <sys/ioctl.h>
75 #include <sys/disklabel.h>
80 #include <sys/ioctl.h>
81 #include <sys/disklabel.h>
87 #include <sys/ioctl.h>
88 #include <sys/diskslice.h>
95 //#define DEBUG_FLOPPY
98 #if defined(DEBUG_BLOCK)
99 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
100 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
102 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
105 /* OS X does not have O_DSYNC */
108 #define O_DSYNC O_SYNC
109 #elif defined(O_FSYNC)
110 #define O_DSYNC O_FSYNC
114 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
116 #define O_DIRECT O_DSYNC
123 /* if the FD is not accessed during that time (in ns), we try to
124 reopen it to see if the disk has been changed */
125 #define FD_OPEN_TIMEOUT (1000000000)
127 #define MAX_BLOCKSIZE 4096
129 typedef struct BDRVRawState
{
135 #if defined(__linux__)
136 /* linux floppy specific */
137 int64_t fd_open_time
;
138 int64_t fd_error_time
;
140 int fd_media_changed
;
142 #ifdef CONFIG_LINUX_AIO
150 bool has_write_zeroes
:1;
151 bool discard_zeroes
:1;
157 typedef struct BDRVRawReopenState
{
160 #ifdef CONFIG_LINUX_AIO
163 } BDRVRawReopenState
;
165 static int fd_open(BlockDriverState
*bs
);
166 static int64_t raw_getlength(BlockDriverState
*bs
);
168 typedef struct RawPosixAIOData
{
169 BlockDriverState
*bs
;
172 struct iovec
*aio_iov
;
177 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
182 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
183 static int cdrom_reopen(BlockDriverState
*bs
);
186 #if defined(__NetBSD__)
187 static int raw_normalize_devicepath(const char **filename
)
189 static char namebuf
[PATH_MAX
];
190 const char *dp
, *fname
;
194 dp
= strrchr(fname
, '/');
195 if (lstat(fname
, &sb
) < 0) {
196 fprintf(stderr
, "%s: stat failed: %s\n",
197 fname
, strerror(errno
));
201 if (!S_ISBLK(sb
.st_mode
)) {
206 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
208 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
209 (int)(dp
- fname
), fname
, dp
+ 1);
211 fprintf(stderr
, "%s is a block device", fname
);
213 fprintf(stderr
, ", using %s\n", *filename
);
218 static int raw_normalize_devicepath(const char **filename
)
224 static void raw_probe_alignment(BlockDriverState
*bs
)
226 BDRVRawState
*s
= bs
->opaque
;
228 unsigned int sector_size
;
230 /* For /dev/sg devices the alignment is not really used.
231 With buffered I/O, we don't have any restrictions. */
232 if (bs
->sg
|| !(s
->open_flags
& O_DIRECT
)) {
233 bs
->request_alignment
= 1;
238 /* Try a few ioctls to get the right size */
239 bs
->request_alignment
= 0;
243 if (ioctl(s
->fd
, BLKSSZGET
, §or_size
) >= 0) {
244 bs
->request_alignment
= sector_size
;
247 #ifdef DKIOCGETBLOCKSIZE
248 if (ioctl(s
->fd
, DKIOCGETBLOCKSIZE
, §or_size
) >= 0) {
249 bs
->request_alignment
= sector_size
;
252 #ifdef DIOCGSECTORSIZE
253 if (ioctl(s
->fd
, DIOCGSECTORSIZE
, §or_size
) >= 0) {
254 bs
->request_alignment
= sector_size
;
260 if (xfsctl(NULL
, s
->fd
, XFS_IOC_DIOINFO
, &da
) >= 0) {
261 bs
->request_alignment
= da
.d_miniosz
;
262 /* The kernel returns wrong information for d_mem */
263 /* s->buf_align = da.d_mem; */
268 /* If we could not get the sizes so far, we can only guess them */
271 buf
= qemu_memalign(MAX_BLOCKSIZE
, 2 * MAX_BLOCKSIZE
);
272 for (align
= 512; align
<= MAX_BLOCKSIZE
; align
<<= 1) {
273 if (pread(s
->fd
, buf
+ align
, MAX_BLOCKSIZE
, 0) >= 0) {
274 s
->buf_align
= align
;
281 if (!bs
->request_alignment
) {
283 buf
= qemu_memalign(s
->buf_align
, MAX_BLOCKSIZE
);
284 for (align
= 512; align
<= MAX_BLOCKSIZE
; align
<<= 1) {
285 if (pread(s
->fd
, buf
, align
, 0) >= 0) {
286 bs
->request_alignment
= align
;
294 static void raw_parse_flags(int bdrv_flags
, int *open_flags
)
296 assert(open_flags
!= NULL
);
298 *open_flags
|= O_BINARY
;
299 *open_flags
&= ~O_ACCMODE
;
300 if (bdrv_flags
& BDRV_O_RDWR
) {
301 *open_flags
|= O_RDWR
;
303 *open_flags
|= O_RDONLY
;
306 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
307 * and O_DIRECT for no caching. */
308 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
309 *open_flags
|= O_DIRECT
;
313 static void raw_detach_aio_context(BlockDriverState
*bs
)
315 #ifdef CONFIG_LINUX_AIO
316 BDRVRawState
*s
= bs
->opaque
;
319 laio_detach_aio_context(s
->aio_ctx
, bdrv_get_aio_context(bs
));
324 static void raw_attach_aio_context(BlockDriverState
*bs
,
325 AioContext
*new_context
)
327 #ifdef CONFIG_LINUX_AIO
328 BDRVRawState
*s
= bs
->opaque
;
331 laio_attach_aio_context(s
->aio_ctx
, new_context
);
336 #ifdef CONFIG_LINUX_AIO
337 static int raw_set_aio(void **aio_ctx
, int *use_aio
, int bdrv_flags
)
340 assert(aio_ctx
!= NULL
);
341 assert(use_aio
!= NULL
);
343 * Currently Linux do AIO only for files opened with O_DIRECT
344 * specified so check NOCACHE flag too
346 if ((bdrv_flags
& (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) ==
347 (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) {
349 /* if non-NULL, laio_init() has already been run */
350 if (*aio_ctx
== NULL
) {
351 *aio_ctx
= laio_init();
368 static void raw_parse_filename(const char *filename
, QDict
*options
,
371 /* The filename does not have to be prefixed by the protocol name, since
372 * "file" is the default protocol; therefore, the return value of this
373 * function call can be ignored. */
374 strstart(filename
, "file:", &filename
);
376 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
379 static QemuOptsList raw_runtime_opts
= {
381 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
385 .type
= QEMU_OPT_STRING
,
386 .help
= "File name of the image",
388 { /* end of list */ }
392 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
393 int bdrv_flags
, int open_flags
, Error
**errp
)
395 BDRVRawState
*s
= bs
->opaque
;
397 Error
*local_err
= NULL
;
398 const char *filename
= NULL
;
402 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
403 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
405 error_propagate(errp
, local_err
);
410 filename
= qemu_opt_get(opts
, "filename");
412 ret
= raw_normalize_devicepath(&filename
);
414 error_setg_errno(errp
, -ret
, "Could not normalize device path");
418 s
->open_flags
= open_flags
;
419 raw_parse_flags(bdrv_flags
, &s
->open_flags
);
422 fd
= qemu_open(filename
, s
->open_flags
, 0644);
432 #ifdef CONFIG_LINUX_AIO
433 if (raw_set_aio(&s
->aio_ctx
, &s
->use_aio
, bdrv_flags
)) {
436 error_setg_errno(errp
, -ret
, "Could not set AIO state");
441 s
->has_discard
= true;
442 s
->has_write_zeroes
= true;
444 if (fstat(s
->fd
, &st
) < 0) {
445 error_setg_errno(errp
, errno
, "Could not stat file");
448 if (S_ISREG(st
.st_mode
)) {
449 s
->discard_zeroes
= true;
451 if (S_ISBLK(st
.st_mode
)) {
452 #ifdef BLKDISCARDZEROES
454 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
455 s
->discard_zeroes
= true;
459 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
460 * not rely on the contents of discarded blocks unless using O_DIRECT.
461 * Same for BLKZEROOUT.
463 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
464 s
->discard_zeroes
= false;
465 s
->has_write_zeroes
= false;
471 if (platform_test_xfs_fd(s
->fd
)) {
476 raw_attach_aio_context(bs
, bdrv_get_aio_context(bs
));
480 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
487 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
490 BDRVRawState
*s
= bs
->opaque
;
491 Error
*local_err
= NULL
;
494 s
->type
= FTYPE_FILE
;
495 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
497 error_propagate(errp
, local_err
);
502 static int raw_reopen_prepare(BDRVReopenState
*state
,
503 BlockReopenQueue
*queue
, Error
**errp
)
506 BDRVRawReopenState
*raw_s
;
509 assert(state
!= NULL
);
510 assert(state
->bs
!= NULL
);
512 s
= state
->bs
->opaque
;
514 state
->opaque
= g_malloc0(sizeof(BDRVRawReopenState
));
515 raw_s
= state
->opaque
;
517 #ifdef CONFIG_LINUX_AIO
518 raw_s
->use_aio
= s
->use_aio
;
520 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
521 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
522 * won't override aio_ctx if aio_ctx is non-NULL */
523 if (raw_set_aio(&s
->aio_ctx
, &raw_s
->use_aio
, state
->flags
)) {
524 error_setg(errp
, "Could not set AIO state");
529 if (s
->type
== FTYPE_FD
|| s
->type
== FTYPE_CD
) {
530 raw_s
->open_flags
|= O_NONBLOCK
;
533 raw_parse_flags(state
->flags
, &raw_s
->open_flags
);
537 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
539 fcntl_flags
|= O_NOATIME
;
543 /* Not all operating systems have O_ASYNC, and those that don't
544 * will not let us track the state into raw_s->open_flags (typically
545 * you achieve the same effect with an ioctl, for example I_SETSIG
546 * on Solaris). But we do not use O_ASYNC, so that's fine.
548 assert((s
->open_flags
& O_ASYNC
) == 0);
551 if ((raw_s
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
552 /* dup the original fd */
553 /* TODO: use qemu fcntl wrapper */
554 #ifdef F_DUPFD_CLOEXEC
555 raw_s
->fd
= fcntl(s
->fd
, F_DUPFD_CLOEXEC
, 0);
557 raw_s
->fd
= dup(s
->fd
);
558 if (raw_s
->fd
!= -1) {
559 qemu_set_cloexec(raw_s
->fd
);
562 if (raw_s
->fd
>= 0) {
563 ret
= fcntl_setfl(raw_s
->fd
, raw_s
->open_flags
);
565 qemu_close(raw_s
->fd
);
571 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
572 if (raw_s
->fd
== -1) {
573 assert(!(raw_s
->open_flags
& O_CREAT
));
574 raw_s
->fd
= qemu_open(state
->bs
->filename
, raw_s
->open_flags
);
575 if (raw_s
->fd
== -1) {
576 error_setg_errno(errp
, errno
, "Could not reopen file");
583 static void raw_reopen_commit(BDRVReopenState
*state
)
585 BDRVRawReopenState
*raw_s
= state
->opaque
;
586 BDRVRawState
*s
= state
->bs
->opaque
;
588 s
->open_flags
= raw_s
->open_flags
;
592 #ifdef CONFIG_LINUX_AIO
593 s
->use_aio
= raw_s
->use_aio
;
596 g_free(state
->opaque
);
597 state
->opaque
= NULL
;
601 static void raw_reopen_abort(BDRVReopenState
*state
)
603 BDRVRawReopenState
*raw_s
= state
->opaque
;
605 /* nothing to do if NULL, we didn't get far enough */
610 if (raw_s
->fd
>= 0) {
611 qemu_close(raw_s
->fd
);
614 g_free(state
->opaque
);
615 state
->opaque
= NULL
;
618 static int raw_refresh_limits(BlockDriverState
*bs
)
620 BDRVRawState
*s
= bs
->opaque
;
622 raw_probe_alignment(bs
);
623 bs
->bl
.opt_mem_alignment
= s
->buf_align
;
628 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
632 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
640 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
644 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
653 static bool preadv_present
= true;
656 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
658 return preadv(fd
, iov
, nr_iov
, offset
);
662 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
664 return pwritev(fd
, iov
, nr_iov
, offset
);
669 static bool preadv_present
= false;
672 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
678 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
685 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
690 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
691 len
= qemu_pwritev(aiocb
->aio_fildes
,
696 len
= qemu_preadv(aiocb
->aio_fildes
,
700 } while (len
== -1 && errno
== EINTR
);
709 * Read/writes the data to/from a given linear buffer.
711 * Returns the number of bytes handles or -errno in case of an error. Short
712 * reads are only returned if the end of the file is reached.
714 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
719 while (offset
< aiocb
->aio_nbytes
) {
720 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
721 len
= pwrite(aiocb
->aio_fildes
,
722 (const char *)buf
+ offset
,
723 aiocb
->aio_nbytes
- offset
,
724 aiocb
->aio_offset
+ offset
);
726 len
= pread(aiocb
->aio_fildes
,
728 aiocb
->aio_nbytes
- offset
,
729 aiocb
->aio_offset
+ offset
);
731 if (len
== -1 && errno
== EINTR
) {
733 } else if (len
== -1) {
736 } else if (len
== 0) {
745 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
750 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
752 * If there is just a single buffer, and it is properly aligned
753 * we can just use plain pread/pwrite without any problems.
755 if (aiocb
->aio_niov
== 1) {
756 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
759 * We have more than one iovec, and all are properly aligned.
761 * Try preadv/pwritev first and fall back to linearizing the
762 * buffer if it's not supported.
764 if (preadv_present
) {
765 nbytes
= handle_aiocb_rw_vector(aiocb
);
766 if (nbytes
== aiocb
->aio_nbytes
||
767 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
770 preadv_present
= false;
774 * XXX(hch): short read/write. no easy way to handle the reminder
775 * using these interfaces. For now retry using plain
781 * Ok, we have to do it the hard way, copy all segments into
782 * a single aligned buffer.
784 buf
= qemu_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
785 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
789 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
790 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
791 p
+= aiocb
->aio_iov
[i
].iov_len
;
793 assert(p
- buf
== aiocb
->aio_nbytes
);
796 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
797 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
799 size_t count
= aiocb
->aio_nbytes
, copy
;
802 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
804 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
805 copy
= aiocb
->aio_iov
[i
].iov_len
;
807 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
808 assert(count
>= copy
);
820 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
822 struct xfs_flock64 fl
;
824 memset(&fl
, 0, sizeof(fl
));
825 fl
.l_whence
= SEEK_SET
;
829 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
830 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno
));
837 static int xfs_discard(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
839 struct xfs_flock64 fl
;
841 memset(&fl
, 0, sizeof(fl
));
842 fl
.l_whence
= SEEK_SET
;
846 if (xfsctl(NULL
, s
->fd
, XFS_IOC_UNRESVSP64
, &fl
) < 0) {
847 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno
));
855 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
857 int ret
= -EOPNOTSUPP
;
858 BDRVRawState
*s
= aiocb
->bs
->opaque
;
860 if (s
->has_write_zeroes
== 0) {
864 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
867 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
868 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
871 } while (errno
== EINTR
);
878 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
883 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
885 s
->has_write_zeroes
= false;
891 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
893 int ret
= -EOPNOTSUPP
;
894 BDRVRawState
*s
= aiocb
->bs
->opaque
;
896 if (!s
->has_discard
) {
900 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
903 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
904 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
907 } while (errno
== EINTR
);
914 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
918 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
920 if (fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
921 aiocb
->aio_offset
, aiocb
->aio_nbytes
) == 0) {
924 } while (errno
== EINTR
);
930 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
932 s
->has_discard
= false;
938 static int aio_worker(void *arg
)
940 RawPosixAIOData
*aiocb
= arg
;
943 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
945 ret
= handle_aiocb_rw(aiocb
);
946 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
&& aiocb
->bs
->growable
) {
947 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
948 0, aiocb
->aio_nbytes
- ret
);
950 ret
= aiocb
->aio_nbytes
;
952 if (ret
== aiocb
->aio_nbytes
) {
954 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
959 ret
= handle_aiocb_rw(aiocb
);
960 if (ret
== aiocb
->aio_nbytes
) {
962 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
967 ret
= handle_aiocb_flush(aiocb
);
970 ret
= handle_aiocb_ioctl(aiocb
);
972 case QEMU_AIO_DISCARD
:
973 ret
= handle_aiocb_discard(aiocb
);
975 case QEMU_AIO_WRITE_ZEROES
:
976 ret
= handle_aiocb_write_zeroes(aiocb
);
979 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
984 g_slice_free(RawPosixAIOData
, aiocb
);
988 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
989 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
992 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
996 acb
->aio_type
= type
;
997 acb
->aio_fildes
= fd
;
999 acb
->aio_nbytes
= nb_sectors
* BDRV_SECTOR_SIZE
;
1000 acb
->aio_offset
= sector_num
* BDRV_SECTOR_SIZE
;
1003 acb
->aio_iov
= qiov
->iov
;
1004 acb
->aio_niov
= qiov
->niov
;
1005 assert(qiov
->size
== acb
->aio_nbytes
);
1008 trace_paio_submit_co(sector_num
, nb_sectors
, type
);
1009 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1010 return thread_pool_submit_co(pool
, aio_worker
, acb
);
1013 static BlockDriverAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
1014 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1015 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
1017 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
1021 acb
->aio_type
= type
;
1022 acb
->aio_fildes
= fd
;
1024 acb
->aio_nbytes
= nb_sectors
* BDRV_SECTOR_SIZE
;
1025 acb
->aio_offset
= sector_num
* BDRV_SECTOR_SIZE
;
1028 acb
->aio_iov
= qiov
->iov
;
1029 acb
->aio_niov
= qiov
->niov
;
1030 assert(qiov
->size
== acb
->aio_nbytes
);
1033 trace_paio_submit(acb
, opaque
, sector_num
, nb_sectors
, type
);
1034 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1035 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1038 static BlockDriverAIOCB
*raw_aio_submit(BlockDriverState
*bs
,
1039 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1040 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
1042 BDRVRawState
*s
= bs
->opaque
;
1044 if (fd_open(bs
) < 0)
1048 * If O_DIRECT is used the buffer needs to be aligned on a sector
1049 * boundary. Check if this is the case or tell the low-level
1050 * driver that it needs to copy the buffer.
1052 if ((bs
->open_flags
& BDRV_O_NOCACHE
)) {
1053 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1054 type
|= QEMU_AIO_MISALIGNED
;
1055 #ifdef CONFIG_LINUX_AIO
1056 } else if (s
->use_aio
) {
1057 return laio_submit(bs
, s
->aio_ctx
, s
->fd
, sector_num
, qiov
,
1058 nb_sectors
, cb
, opaque
, type
);
1063 return paio_submit(bs
, s
->fd
, sector_num
, qiov
, nb_sectors
,
1067 static void raw_aio_plug(BlockDriverState
*bs
)
1069 #ifdef CONFIG_LINUX_AIO
1070 BDRVRawState
*s
= bs
->opaque
;
1072 laio_io_plug(bs
, s
->aio_ctx
);
1077 static void raw_aio_unplug(BlockDriverState
*bs
)
1079 #ifdef CONFIG_LINUX_AIO
1080 BDRVRawState
*s
= bs
->opaque
;
1082 laio_io_unplug(bs
, s
->aio_ctx
, true);
1087 static void raw_aio_flush_io_queue(BlockDriverState
*bs
)
1089 #ifdef CONFIG_LINUX_AIO
1090 BDRVRawState
*s
= bs
->opaque
;
1092 laio_io_unplug(bs
, s
->aio_ctx
, false);
1097 static BlockDriverAIOCB
*raw_aio_readv(BlockDriverState
*bs
,
1098 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1099 BlockDriverCompletionFunc
*cb
, void *opaque
)
1101 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1102 cb
, opaque
, QEMU_AIO_READ
);
1105 static BlockDriverAIOCB
*raw_aio_writev(BlockDriverState
*bs
,
1106 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1107 BlockDriverCompletionFunc
*cb
, void *opaque
)
1109 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1110 cb
, opaque
, QEMU_AIO_WRITE
);
1113 static BlockDriverAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1114 BlockDriverCompletionFunc
*cb
, void *opaque
)
1116 BDRVRawState
*s
= bs
->opaque
;
1118 if (fd_open(bs
) < 0)
1121 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1124 static void raw_close(BlockDriverState
*bs
)
1126 BDRVRawState
*s
= bs
->opaque
;
1128 raw_detach_aio_context(bs
);
1130 #ifdef CONFIG_LINUX_AIO
1132 laio_cleanup(s
->aio_ctx
);
1141 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
1143 BDRVRawState
*s
= bs
->opaque
;
1146 if (fstat(s
->fd
, &st
)) {
1150 if (S_ISREG(st
.st_mode
)) {
1151 if (ftruncate(s
->fd
, offset
) < 0) {
1154 } else if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1155 if (offset
> raw_getlength(bs
)) {
1166 static int64_t raw_getlength(BlockDriverState
*bs
)
1168 BDRVRawState
*s
= bs
->opaque
;
1174 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1175 struct disklabel dl
;
1177 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1179 return (uint64_t)dl
.d_secsize
*
1180 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1184 #elif defined(__NetBSD__)
1185 static int64_t raw_getlength(BlockDriverState
*bs
)
1187 BDRVRawState
*s
= bs
->opaque
;
1193 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1194 struct dkwedge_info dkw
;
1196 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1197 return dkw
.dkw_size
* 512;
1199 struct disklabel dl
;
1201 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1203 return (uint64_t)dl
.d_secsize
*
1204 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1209 #elif defined(__sun__)
1210 static int64_t raw_getlength(BlockDriverState
*bs
)
1212 BDRVRawState
*s
= bs
->opaque
;
1213 struct dk_minfo minfo
;
1223 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1225 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1227 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1231 * There are reports that lseek on some devices fails, but
1232 * irc discussion said that contingency on contingency was overkill.
1234 size
= lseek(s
->fd
, 0, SEEK_END
);
1240 #elif defined(CONFIG_BSD)
1241 static int64_t raw_getlength(BlockDriverState
*bs
)
1243 BDRVRawState
*s
= bs
->opaque
;
1247 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1256 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1259 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1260 #ifdef DIOCGMEDIASIZE
1261 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1262 #elif defined(DIOCGPART)
1265 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1266 size
= pi
.media_size
;
1272 #if defined(__APPLE__) && defined(__MACH__)
1275 size
= lseek(fd
, 0LL, SEEK_END
);
1280 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1283 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1284 if (size
== 2048LL * (unsigned)-1)
1286 /* XXX no disc? maybe we need to reopen... */
1287 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1294 size
= lseek(fd
, 0, SEEK_END
);
1302 static int64_t raw_getlength(BlockDriverState
*bs
)
1304 BDRVRawState
*s
= bs
->opaque
;
1313 size
= lseek(s
->fd
, 0, SEEK_END
);
1321 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
1324 BDRVRawState
*s
= bs
->opaque
;
1326 if (fstat(s
->fd
, &st
) < 0) {
1329 return (int64_t)st
.st_blocks
* 512;
1332 static int raw_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1336 int64_t total_size
= 0;
1339 strstart(filename
, "file:", &filename
);
1341 /* Read out options */
1343 qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0) / BDRV_SECTOR_SIZE
;
1344 nocow
= qemu_opt_get_bool(opts
, BLOCK_OPT_NOCOW
, false);
1346 fd
= qemu_open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
1350 error_setg_errno(errp
, -result
, "Could not create file");
1354 /* Set NOCOW flag to solve performance issue on fs like btrfs.
1355 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
1356 * will be ignored since any failure of this operation should not
1357 * block the left work.
1360 if (ioctl(fd
, FS_IOC_GETFLAGS
, &attr
) == 0) {
1361 attr
|= FS_NOCOW_FL
;
1362 ioctl(fd
, FS_IOC_SETFLAGS
, &attr
);
1367 if (ftruncate(fd
, total_size
* BDRV_SECTOR_SIZE
) != 0) {
1369 error_setg_errno(errp
, -result
, "Could not resize file");
1371 if (qemu_close(fd
) != 0) {
1373 error_setg_errno(errp
, -result
, "Could not close the new file");
1379 static int64_t try_fiemap(BlockDriverState
*bs
, off_t start
, off_t
*data
,
1380 off_t
*hole
, int nb_sectors
, int *pnum
)
1382 #ifdef CONFIG_FIEMAP
1383 BDRVRawState
*s
= bs
->opaque
;
1384 int64_t ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1387 struct fiemap_extent fe
;
1390 if (s
->skip_fiemap
) {
1394 f
.fm
.fm_start
= start
;
1395 f
.fm
.fm_length
= (int64_t)nb_sectors
* BDRV_SECTOR_SIZE
;
1397 f
.fm
.fm_extent_count
= 1;
1398 f
.fm
.fm_reserved
= 0;
1399 if (ioctl(s
->fd
, FS_IOC_FIEMAP
, &f
) == -1) {
1400 s
->skip_fiemap
= true;
1404 if (f
.fm
.fm_mapped_extents
== 0) {
1405 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1406 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1408 off_t length
= lseek(s
->fd
, 0, SEEK_END
);
1409 *hole
= f
.fm
.fm_start
;
1410 *data
= MIN(f
.fm
.fm_start
+ f
.fm
.fm_length
, length
);
1412 *data
= f
.fe
.fe_logical
;
1413 *hole
= f
.fe
.fe_logical
+ f
.fe
.fe_length
;
1414 if (f
.fe
.fe_flags
& FIEMAP_EXTENT_UNWRITTEN
) {
1415 ret
|= BDRV_BLOCK_ZERO
;
1425 static int64_t try_seek_hole(BlockDriverState
*bs
, off_t start
, off_t
*data
,
1426 off_t
*hole
, int *pnum
)
1428 #if defined SEEK_HOLE && defined SEEK_DATA
1429 BDRVRawState
*s
= bs
->opaque
;
1431 *hole
= lseek(s
->fd
, start
, SEEK_HOLE
);
1433 /* -ENXIO indicates that sector_num was past the end of the file.
1434 * There is a virtual hole there. */
1435 assert(errno
!= -ENXIO
);
1440 if (*hole
> start
) {
1443 /* On a hole. We need another syscall to find its end. */
1444 *data
= lseek(s
->fd
, start
, SEEK_DATA
);
1446 *data
= lseek(s
->fd
, 0, SEEK_END
);
1450 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1457 * Returns true iff the specified sector is present in the disk image. Drivers
1458 * not implementing the functionality are assumed to not support backing files,
1459 * hence all their sectors are reported as allocated.
1461 * If 'sector_num' is beyond the end of the disk image the return value is 0
1462 * and 'pnum' is set to 0.
1464 * 'pnum' is set to the number of sectors (including and immediately following
1465 * the specified sector) that are known to be in the same
1466 * allocated/unallocated state.
1468 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1469 * beyond the end of the disk image it will be clamped.
1471 static int64_t coroutine_fn
raw_co_get_block_status(BlockDriverState
*bs
,
1473 int nb_sectors
, int *pnum
)
1475 off_t start
, data
= 0, hole
= 0;
1483 start
= sector_num
* BDRV_SECTOR_SIZE
;
1485 ret
= try_fiemap(bs
, start
, &data
, &hole
, nb_sectors
, pnum
);
1487 ret
= try_seek_hole(bs
, start
, &data
, &hole
, pnum
);
1489 /* Assume everything is allocated. */
1491 hole
= start
+ nb_sectors
* BDRV_SECTOR_SIZE
;
1492 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1496 if (data
<= start
) {
1497 /* On a data extent, compute sectors to the end of the extent. */
1498 *pnum
= MIN(nb_sectors
, (hole
- start
) / BDRV_SECTOR_SIZE
);
1500 /* On a hole, compute sectors to the beginning of the next extent. */
1501 *pnum
= MIN(nb_sectors
, (data
- start
) / BDRV_SECTOR_SIZE
);
1502 ret
&= ~BDRV_BLOCK_DATA
;
1503 ret
|= BDRV_BLOCK_ZERO
;
1509 static coroutine_fn BlockDriverAIOCB
*raw_aio_discard(BlockDriverState
*bs
,
1510 int64_t sector_num
, int nb_sectors
,
1511 BlockDriverCompletionFunc
*cb
, void *opaque
)
1513 BDRVRawState
*s
= bs
->opaque
;
1515 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1516 cb
, opaque
, QEMU_AIO_DISCARD
);
1519 static int coroutine_fn
raw_co_write_zeroes(
1520 BlockDriverState
*bs
, int64_t sector_num
,
1521 int nb_sectors
, BdrvRequestFlags flags
)
1523 BDRVRawState
*s
= bs
->opaque
;
1525 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1526 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1527 QEMU_AIO_WRITE_ZEROES
);
1528 } else if (s
->discard_zeroes
) {
1529 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1535 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1537 BDRVRawState
*s
= bs
->opaque
;
1539 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
1540 bdi
->can_write_zeroes_with_unmap
= s
->discard_zeroes
;
1544 static QemuOptsList raw_create_opts
= {
1545 .name
= "raw-create-opts",
1546 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
1549 .name
= BLOCK_OPT_SIZE
,
1550 .type
= QEMU_OPT_SIZE
,
1551 .help
= "Virtual disk size"
1554 .name
= BLOCK_OPT_NOCOW
,
1555 .type
= QEMU_OPT_BOOL
,
1556 .help
= "Turn off copy-on-write (valid only on btrfs)"
1558 { /* end of list */ }
1562 static BlockDriver bdrv_file
= {
1563 .format_name
= "file",
1564 .protocol_name
= "file",
1565 .instance_size
= sizeof(BDRVRawState
),
1566 .bdrv_needs_filename
= true,
1567 .bdrv_probe
= NULL
, /* no probe for protocols */
1568 .bdrv_parse_filename
= raw_parse_filename
,
1569 .bdrv_file_open
= raw_open
,
1570 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1571 .bdrv_reopen_commit
= raw_reopen_commit
,
1572 .bdrv_reopen_abort
= raw_reopen_abort
,
1573 .bdrv_close
= raw_close
,
1574 .bdrv_create
= raw_create
,
1575 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
1576 .bdrv_co_get_block_status
= raw_co_get_block_status
,
1577 .bdrv_co_write_zeroes
= raw_co_write_zeroes
,
1579 .bdrv_aio_readv
= raw_aio_readv
,
1580 .bdrv_aio_writev
= raw_aio_writev
,
1581 .bdrv_aio_flush
= raw_aio_flush
,
1582 .bdrv_aio_discard
= raw_aio_discard
,
1583 .bdrv_refresh_limits
= raw_refresh_limits
,
1584 .bdrv_io_plug
= raw_aio_plug
,
1585 .bdrv_io_unplug
= raw_aio_unplug
,
1586 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
1588 .bdrv_truncate
= raw_truncate
,
1589 .bdrv_getlength
= raw_getlength
,
1590 .bdrv_get_info
= raw_get_info
,
1591 .bdrv_get_allocated_file_size
1592 = raw_get_allocated_file_size
,
1594 .bdrv_detach_aio_context
= raw_detach_aio_context
,
1595 .bdrv_attach_aio_context
= raw_attach_aio_context
,
1597 .create_opts
= &raw_create_opts
,
1600 /***********************************************/
1603 #if defined(__APPLE__) && defined(__MACH__)
1604 static kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
);
1605 static kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
);
1607 kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
)
1609 kern_return_t kernResult
;
1610 mach_port_t masterPort
;
1611 CFMutableDictionaryRef classesToMatch
;
1613 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
1614 if ( KERN_SUCCESS
!= kernResult
) {
1615 printf( "IOMasterPort returned %d\n", kernResult
);
1618 classesToMatch
= IOServiceMatching( kIOCDMediaClass
);
1619 if ( classesToMatch
== NULL
) {
1620 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1622 CFDictionarySetValue( classesToMatch
, CFSTR( kIOMediaEjectableKey
), kCFBooleanTrue
);
1624 kernResult
= IOServiceGetMatchingServices( masterPort
, classesToMatch
, mediaIterator
);
1625 if ( KERN_SUCCESS
!= kernResult
)
1627 printf( "IOServiceGetMatchingServices returned %d\n", kernResult
);
1633 kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
)
1635 io_object_t nextMedia
;
1636 kern_return_t kernResult
= KERN_FAILURE
;
1638 nextMedia
= IOIteratorNext( mediaIterator
);
1641 CFTypeRef bsdPathAsCFString
;
1642 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
1643 if ( bsdPathAsCFString
) {
1644 size_t devPathLength
;
1645 strcpy( bsdPath
, _PATH_DEV
);
1646 strcat( bsdPath
, "r" );
1647 devPathLength
= strlen( bsdPath
);
1648 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
1649 kernResult
= KERN_SUCCESS
;
1651 CFRelease( bsdPathAsCFString
);
1653 IOObjectRelease( nextMedia
);
1661 static int hdev_probe_device(const char *filename
)
1665 /* allow a dedicated CD-ROM driver to match with a higher priority */
1666 if (strstart(filename
, "/dev/cdrom", NULL
))
1669 if (stat(filename
, &st
) >= 0 &&
1670 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
1677 static int check_hdev_writable(BDRVRawState
*s
)
1679 #if defined(BLKROGET)
1680 /* Linux block devices can be configured "read-only" using blockdev(8).
1681 * This is independent of device node permissions and therefore open(2)
1682 * with O_RDWR succeeds. Actual writes fail with EPERM.
1684 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1685 * check for read-only block devices so that Linux block devices behave
1691 if (fstat(s
->fd
, &st
)) {
1695 if (!S_ISBLK(st
.st_mode
)) {
1699 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
1706 #endif /* defined(BLKROGET) */
1710 static void hdev_parse_filename(const char *filename
, QDict
*options
,
1713 /* The prefix is optional, just as for "file". */
1714 strstart(filename
, "host_device:", &filename
);
1716 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
1719 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1722 BDRVRawState
*s
= bs
->opaque
;
1723 Error
*local_err
= NULL
;
1725 const char *filename
= qdict_get_str(options
, "filename");
1727 #if defined(__APPLE__) && defined(__MACH__)
1728 if (strstart(filename
, "/dev/cdrom", NULL
)) {
1729 kern_return_t kernResult
;
1730 io_iterator_t mediaIterator
;
1731 char bsdPath
[ MAXPATHLEN
];
1734 kernResult
= FindEjectableCDMedia( &mediaIterator
);
1735 kernResult
= GetBSDPath( mediaIterator
, bsdPath
, sizeof( bsdPath
) );
1737 if ( bsdPath
[ 0 ] != '\0' ) {
1738 strcat(bsdPath
,"s0");
1739 /* some CDs don't have a partition 0 */
1740 fd
= qemu_open(bsdPath
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
1742 bsdPath
[strlen(bsdPath
)-1] = '1';
1747 qdict_put(options
, "filename", qstring_from_str(filename
));
1750 if ( mediaIterator
)
1751 IOObjectRelease( mediaIterator
);
1755 s
->type
= FTYPE_FILE
;
1756 #if defined(__linux__)
1758 char resolved_path
[ MAXPATHLEN
], *temp
;
1760 temp
= realpath(filename
, resolved_path
);
1761 if (temp
&& strstart(temp
, "/dev/sg", NULL
)) {
1767 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
1770 error_propagate(errp
, local_err
);
1775 if (flags
& BDRV_O_RDWR
) {
1776 ret
= check_hdev_writable(s
);
1779 error_setg_errno(errp
, -ret
, "The device is not writable");
1787 #if defined(__linux__)
1788 /* Note: we do not have a reliable method to detect if the floppy is
1789 present. The current method is to try to open the floppy at every
1790 I/O and to keep it opened during a few hundreds of ms. */
1791 static int fd_open(BlockDriverState
*bs
)
1793 BDRVRawState
*s
= bs
->opaque
;
1794 int last_media_present
;
1796 if (s
->type
!= FTYPE_FD
)
1798 last_media_present
= (s
->fd
>= 0);
1800 (get_clock() - s
->fd_open_time
) >= FD_OPEN_TIMEOUT
) {
1804 printf("Floppy closed\n");
1808 if (s
->fd_got_error
&&
1809 (get_clock() - s
->fd_error_time
) < FD_OPEN_TIMEOUT
) {
1811 printf("No floppy (open delayed)\n");
1815 s
->fd
= qemu_open(bs
->filename
, s
->open_flags
& ~O_NONBLOCK
);
1817 s
->fd_error_time
= get_clock();
1818 s
->fd_got_error
= 1;
1819 if (last_media_present
)
1820 s
->fd_media_changed
= 1;
1822 printf("No floppy\n");
1827 printf("Floppy opened\n");
1830 if (!last_media_present
)
1831 s
->fd_media_changed
= 1;
1832 s
->fd_open_time
= get_clock();
1833 s
->fd_got_error
= 0;
1837 static int hdev_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
1839 BDRVRawState
*s
= bs
->opaque
;
1841 return ioctl(s
->fd
, req
, buf
);
1844 static BlockDriverAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
1845 unsigned long int req
, void *buf
,
1846 BlockDriverCompletionFunc
*cb
, void *opaque
)
1848 BDRVRawState
*s
= bs
->opaque
;
1849 RawPosixAIOData
*acb
;
1852 if (fd_open(bs
) < 0)
1855 acb
= g_slice_new(RawPosixAIOData
);
1857 acb
->aio_type
= QEMU_AIO_IOCTL
;
1858 acb
->aio_fildes
= s
->fd
;
1859 acb
->aio_offset
= 0;
1860 acb
->aio_ioctl_buf
= buf
;
1861 acb
->aio_ioctl_cmd
= req
;
1862 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1863 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1866 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1867 static int fd_open(BlockDriverState
*bs
)
1869 BDRVRawState
*s
= bs
->opaque
;
1871 /* this is just to ensure s->fd is sane (its called by io ops) */
1876 #else /* !linux && !FreeBSD */
1878 static int fd_open(BlockDriverState
*bs
)
1883 #endif /* !linux && !FreeBSD */
1885 static coroutine_fn BlockDriverAIOCB
*hdev_aio_discard(BlockDriverState
*bs
,
1886 int64_t sector_num
, int nb_sectors
,
1887 BlockDriverCompletionFunc
*cb
, void *opaque
)
1889 BDRVRawState
*s
= bs
->opaque
;
1891 if (fd_open(bs
) < 0) {
1894 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1895 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1898 static coroutine_fn
int hdev_co_write_zeroes(BlockDriverState
*bs
,
1899 int64_t sector_num
, int nb_sectors
, BdrvRequestFlags flags
)
1901 BDRVRawState
*s
= bs
->opaque
;
1908 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1909 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1910 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
1911 } else if (s
->discard_zeroes
) {
1912 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1913 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1918 static int hdev_create(const char *filename
, QemuOpts
*opts
,
1923 struct stat stat_buf
;
1924 int64_t total_size
= 0;
1927 /* This function is used by all three protocol block drivers and therefore
1928 * any of these three prefixes may be given.
1929 * The return value has to be stored somewhere, otherwise this is an error
1930 * due to -Werror=unused-value. */
1932 strstart(filename
, "host_device:", &filename
) ||
1933 strstart(filename
, "host_cdrom:" , &filename
) ||
1934 strstart(filename
, "host_floppy:", &filename
);
1938 /* Read out options */
1940 qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0) / BDRV_SECTOR_SIZE
;
1942 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
1945 error_setg_errno(errp
, -ret
, "Could not open device");
1949 if (fstat(fd
, &stat_buf
) < 0) {
1951 error_setg_errno(errp
, -ret
, "Could not stat device");
1952 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
1954 "The given file is neither a block nor a character device");
1956 } else if (lseek(fd
, 0, SEEK_END
) < total_size
* BDRV_SECTOR_SIZE
) {
1957 error_setg(errp
, "Device is too small");
1965 static BlockDriver bdrv_host_device
= {
1966 .format_name
= "host_device",
1967 .protocol_name
= "host_device",
1968 .instance_size
= sizeof(BDRVRawState
),
1969 .bdrv_needs_filename
= true,
1970 .bdrv_probe_device
= hdev_probe_device
,
1971 .bdrv_parse_filename
= hdev_parse_filename
,
1972 .bdrv_file_open
= hdev_open
,
1973 .bdrv_close
= raw_close
,
1974 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1975 .bdrv_reopen_commit
= raw_reopen_commit
,
1976 .bdrv_reopen_abort
= raw_reopen_abort
,
1977 .bdrv_create
= hdev_create
,
1978 .create_opts
= &raw_create_opts
,
1979 .bdrv_co_write_zeroes
= hdev_co_write_zeroes
,
1981 .bdrv_aio_readv
= raw_aio_readv
,
1982 .bdrv_aio_writev
= raw_aio_writev
,
1983 .bdrv_aio_flush
= raw_aio_flush
,
1984 .bdrv_aio_discard
= hdev_aio_discard
,
1985 .bdrv_refresh_limits
= raw_refresh_limits
,
1986 .bdrv_io_plug
= raw_aio_plug
,
1987 .bdrv_io_unplug
= raw_aio_unplug
,
1988 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
1990 .bdrv_truncate
= raw_truncate
,
1991 .bdrv_getlength
= raw_getlength
,
1992 .bdrv_get_info
= raw_get_info
,
1993 .bdrv_get_allocated_file_size
1994 = raw_get_allocated_file_size
,
1996 .bdrv_detach_aio_context
= raw_detach_aio_context
,
1997 .bdrv_attach_aio_context
= raw_attach_aio_context
,
1999 /* generic scsi device */
2001 .bdrv_ioctl
= hdev_ioctl
,
2002 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2007 static void floppy_parse_filename(const char *filename
, QDict
*options
,
2010 /* The prefix is optional, just as for "file". */
2011 strstart(filename
, "host_floppy:", &filename
);
2013 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2016 static int floppy_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2019 BDRVRawState
*s
= bs
->opaque
;
2020 Error
*local_err
= NULL
;
2025 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
2026 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2029 error_propagate(errp
, local_err
);
2034 /* close fd so that we can reopen it as needed */
2037 s
->fd_media_changed
= 1;
2042 static int floppy_probe_device(const char *filename
)
2046 struct floppy_struct fdparam
;
2049 if (strstart(filename
, "/dev/fd", NULL
) &&
2050 !strstart(filename
, "/dev/fdset/", NULL
)) {
2054 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2058 ret
= fstat(fd
, &st
);
2059 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2063 /* Attempt to detect via a floppy specific ioctl */
2064 ret
= ioctl(fd
, FDGETPRM
, &fdparam
);
2075 static int floppy_is_inserted(BlockDriverState
*bs
)
2077 return fd_open(bs
) >= 0;
2080 static int floppy_media_changed(BlockDriverState
*bs
)
2082 BDRVRawState
*s
= bs
->opaque
;
2086 * XXX: we do not have a true media changed indication.
2087 * It does not work if the floppy is changed without trying to read it.
2090 ret
= s
->fd_media_changed
;
2091 s
->fd_media_changed
= 0;
2093 printf("Floppy changed=%d\n", ret
);
2098 static void floppy_eject(BlockDriverState
*bs
, bool eject_flag
)
2100 BDRVRawState
*s
= bs
->opaque
;
2107 fd
= qemu_open(bs
->filename
, s
->open_flags
| O_NONBLOCK
);
2109 if (ioctl(fd
, FDEJECT
, 0) < 0)
2115 static BlockDriver bdrv_host_floppy
= {
2116 .format_name
= "host_floppy",
2117 .protocol_name
= "host_floppy",
2118 .instance_size
= sizeof(BDRVRawState
),
2119 .bdrv_needs_filename
= true,
2120 .bdrv_probe_device
= floppy_probe_device
,
2121 .bdrv_parse_filename
= floppy_parse_filename
,
2122 .bdrv_file_open
= floppy_open
,
2123 .bdrv_close
= raw_close
,
2124 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2125 .bdrv_reopen_commit
= raw_reopen_commit
,
2126 .bdrv_reopen_abort
= raw_reopen_abort
,
2127 .bdrv_create
= hdev_create
,
2128 .create_opts
= &raw_create_opts
,
2130 .bdrv_aio_readv
= raw_aio_readv
,
2131 .bdrv_aio_writev
= raw_aio_writev
,
2132 .bdrv_aio_flush
= raw_aio_flush
,
2133 .bdrv_refresh_limits
= raw_refresh_limits
,
2134 .bdrv_io_plug
= raw_aio_plug
,
2135 .bdrv_io_unplug
= raw_aio_unplug
,
2136 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2138 .bdrv_truncate
= raw_truncate
,
2139 .bdrv_getlength
= raw_getlength
,
2140 .has_variable_length
= true,
2141 .bdrv_get_allocated_file_size
2142 = raw_get_allocated_file_size
,
2144 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2145 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2147 /* removable device support */
2148 .bdrv_is_inserted
= floppy_is_inserted
,
2149 .bdrv_media_changed
= floppy_media_changed
,
2150 .bdrv_eject
= floppy_eject
,
2154 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2155 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2158 /* The prefix is optional, just as for "file". */
2159 strstart(filename
, "host_cdrom:", &filename
);
2161 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2166 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2169 BDRVRawState
*s
= bs
->opaque
;
2170 Error
*local_err
= NULL
;
2175 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2176 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2178 error_propagate(errp
, local_err
);
2183 static int cdrom_probe_device(const char *filename
)
2189 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2193 ret
= fstat(fd
, &st
);
2194 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2198 /* Attempt to detect via a CDROM specific ioctl */
2199 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2209 static int cdrom_is_inserted(BlockDriverState
*bs
)
2211 BDRVRawState
*s
= bs
->opaque
;
2214 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2215 if (ret
== CDS_DISC_OK
)
2220 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2222 BDRVRawState
*s
= bs
->opaque
;
2225 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2226 perror("CDROMEJECT");
2228 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2229 perror("CDROMEJECT");
2233 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2235 BDRVRawState
*s
= bs
->opaque
;
2237 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2239 * Note: an error can happen if the distribution automatically
2242 /* perror("CDROM_LOCKDOOR"); */
2246 static BlockDriver bdrv_host_cdrom
= {
2247 .format_name
= "host_cdrom",
2248 .protocol_name
= "host_cdrom",
2249 .instance_size
= sizeof(BDRVRawState
),
2250 .bdrv_needs_filename
= true,
2251 .bdrv_probe_device
= cdrom_probe_device
,
2252 .bdrv_parse_filename
= cdrom_parse_filename
,
2253 .bdrv_file_open
= cdrom_open
,
2254 .bdrv_close
= raw_close
,
2255 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2256 .bdrv_reopen_commit
= raw_reopen_commit
,
2257 .bdrv_reopen_abort
= raw_reopen_abort
,
2258 .bdrv_create
= hdev_create
,
2259 .create_opts
= &raw_create_opts
,
2261 .bdrv_aio_readv
= raw_aio_readv
,
2262 .bdrv_aio_writev
= raw_aio_writev
,
2263 .bdrv_aio_flush
= raw_aio_flush
,
2264 .bdrv_refresh_limits
= raw_refresh_limits
,
2265 .bdrv_io_plug
= raw_aio_plug
,
2266 .bdrv_io_unplug
= raw_aio_unplug
,
2267 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2269 .bdrv_truncate
= raw_truncate
,
2270 .bdrv_getlength
= raw_getlength
,
2271 .has_variable_length
= true,
2272 .bdrv_get_allocated_file_size
2273 = raw_get_allocated_file_size
,
2275 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2276 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2278 /* removable device support */
2279 .bdrv_is_inserted
= cdrom_is_inserted
,
2280 .bdrv_eject
= cdrom_eject
,
2281 .bdrv_lock_medium
= cdrom_lock_medium
,
2283 /* generic scsi device */
2284 .bdrv_ioctl
= hdev_ioctl
,
2285 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2287 #endif /* __linux__ */
2289 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2290 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2293 BDRVRawState
*s
= bs
->opaque
;
2294 Error
*local_err
= NULL
;
2299 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2302 error_propagate(errp
, local_err
);
2307 /* make sure the door isn't locked at this time */
2308 ioctl(s
->fd
, CDIOCALLOW
);
2312 static int cdrom_probe_device(const char *filename
)
2314 if (strstart(filename
, "/dev/cd", NULL
) ||
2315 strstart(filename
, "/dev/acd", NULL
))
2320 static int cdrom_reopen(BlockDriverState
*bs
)
2322 BDRVRawState
*s
= bs
->opaque
;
2326 * Force reread of possibly changed/newly loaded disc,
2327 * FreeBSD seems to not notice sometimes...
2331 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
2338 /* make sure the door isn't locked at this time */
2339 ioctl(s
->fd
, CDIOCALLOW
);
2343 static int cdrom_is_inserted(BlockDriverState
*bs
)
2345 return raw_getlength(bs
) > 0;
2348 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2350 BDRVRawState
*s
= bs
->opaque
;
2355 (void) ioctl(s
->fd
, CDIOCALLOW
);
2358 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
2359 perror("CDIOCEJECT");
2361 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
2362 perror("CDIOCCLOSE");
2368 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2370 BDRVRawState
*s
= bs
->opaque
;
2374 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
2376 * Note: an error can happen if the distribution automatically
2379 /* perror("CDROM_LOCKDOOR"); */
2383 static BlockDriver bdrv_host_cdrom
= {
2384 .format_name
= "host_cdrom",
2385 .protocol_name
= "host_cdrom",
2386 .instance_size
= sizeof(BDRVRawState
),
2387 .bdrv_needs_filename
= true,
2388 .bdrv_probe_device
= cdrom_probe_device
,
2389 .bdrv_parse_filename
= cdrom_parse_filename
,
2390 .bdrv_file_open
= cdrom_open
,
2391 .bdrv_close
= raw_close
,
2392 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2393 .bdrv_reopen_commit
= raw_reopen_commit
,
2394 .bdrv_reopen_abort
= raw_reopen_abort
,
2395 .bdrv_create
= hdev_create
,
2396 .create_opts
= &raw_create_opts
,
2398 .bdrv_aio_readv
= raw_aio_readv
,
2399 .bdrv_aio_writev
= raw_aio_writev
,
2400 .bdrv_aio_flush
= raw_aio_flush
,
2401 .bdrv_refresh_limits
= raw_refresh_limits
,
2402 .bdrv_io_plug
= raw_aio_plug
,
2403 .bdrv_io_unplug
= raw_aio_unplug
,
2404 .bdrv_flush_io_queue
= raw_aio_flush_io_queue
,
2406 .bdrv_truncate
= raw_truncate
,
2407 .bdrv_getlength
= raw_getlength
,
2408 .has_variable_length
= true,
2409 .bdrv_get_allocated_file_size
2410 = raw_get_allocated_file_size
,
2412 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2413 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2415 /* removable device support */
2416 .bdrv_is_inserted
= cdrom_is_inserted
,
2417 .bdrv_eject
= cdrom_eject
,
2418 .bdrv_lock_medium
= cdrom_lock_medium
,
2420 #endif /* __FreeBSD__ */
2422 static void bdrv_file_init(void)
2425 * Register all the drivers. Note that order is important, the driver
2426 * registered last will get probed first.
2428 bdrv_register(&bdrv_file
);
2429 bdrv_register(&bdrv_host_device
);
2431 bdrv_register(&bdrv_host_floppy
);
2432 bdrv_register(&bdrv_host_cdrom
);
2434 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2435 bdrv_register(&bdrv_host_cdrom
);
2439 block_init(bdrv_file_init
);