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>
60 #include <linux/fiemap.h>
62 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
63 #include <linux/falloc.h>
65 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
71 #include <sys/ioctl.h>
72 #include <sys/disklabel.h>
77 #include <sys/ioctl.h>
78 #include <sys/disklabel.h>
84 #include <sys/ioctl.h>
85 #include <sys/diskslice.h>
92 //#define DEBUG_FLOPPY
95 #if defined(DEBUG_BLOCK)
96 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
97 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
99 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
102 /* OS X does not have O_DSYNC */
105 #define O_DSYNC O_SYNC
106 #elif defined(O_FSYNC)
107 #define O_DSYNC O_FSYNC
111 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
113 #define O_DIRECT O_DSYNC
120 /* if the FD is not accessed during that time (in ns), we try to
121 reopen it to see if the disk has been changed */
122 #define FD_OPEN_TIMEOUT (1000000000)
124 #define MAX_BLOCKSIZE 4096
126 typedef struct BDRVRawState
{
132 #if defined(__linux__)
133 /* linux floppy specific */
134 int64_t fd_open_time
;
135 int64_t fd_error_time
;
137 int fd_media_changed
;
139 #ifdef CONFIG_LINUX_AIO
147 bool has_write_zeroes
:1;
148 bool discard_zeroes
:1;
154 typedef struct BDRVRawReopenState
{
157 #ifdef CONFIG_LINUX_AIO
160 } BDRVRawReopenState
;
162 static int fd_open(BlockDriverState
*bs
);
163 static int64_t raw_getlength(BlockDriverState
*bs
);
165 typedef struct RawPosixAIOData
{
166 BlockDriverState
*bs
;
169 struct iovec
*aio_iov
;
174 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
179 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
180 static int cdrom_reopen(BlockDriverState
*bs
);
183 #if defined(__NetBSD__)
184 static int raw_normalize_devicepath(const char **filename
)
186 static char namebuf
[PATH_MAX
];
187 const char *dp
, *fname
;
191 dp
= strrchr(fname
, '/');
192 if (lstat(fname
, &sb
) < 0) {
193 fprintf(stderr
, "%s: stat failed: %s\n",
194 fname
, strerror(errno
));
198 if (!S_ISBLK(sb
.st_mode
)) {
203 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
205 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
206 (int)(dp
- fname
), fname
, dp
+ 1);
208 fprintf(stderr
, "%s is a block device", fname
);
210 fprintf(stderr
, ", using %s\n", *filename
);
215 static int raw_normalize_devicepath(const char **filename
)
221 static void raw_probe_alignment(BlockDriverState
*bs
)
223 BDRVRawState
*s
= bs
->opaque
;
225 unsigned int sector_size
;
227 /* For /dev/sg devices the alignment is not really used.
228 With buffered I/O, we don't have any restrictions. */
229 if (bs
->sg
|| !(s
->open_flags
& O_DIRECT
)) {
230 bs
->request_alignment
= 1;
235 /* Try a few ioctls to get the right size */
236 bs
->request_alignment
= 0;
240 if (ioctl(s
->fd
, BLKSSZGET
, §or_size
) >= 0) {
241 bs
->request_alignment
= sector_size
;
244 #ifdef DKIOCGETBLOCKSIZE
245 if (ioctl(s
->fd
, DKIOCGETBLOCKSIZE
, §or_size
) >= 0) {
246 bs
->request_alignment
= sector_size
;
249 #ifdef DIOCGSECTORSIZE
250 if (ioctl(s
->fd
, DIOCGSECTORSIZE
, §or_size
) >= 0) {
251 bs
->request_alignment
= sector_size
;
257 if (xfsctl(NULL
, s
->fd
, XFS_IOC_DIOINFO
, &da
) >= 0) {
258 bs
->request_alignment
= da
.d_miniosz
;
259 /* The kernel returns wrong information for d_mem */
260 /* s->buf_align = da.d_mem; */
265 /* If we could not get the sizes so far, we can only guess them */
268 buf
= qemu_memalign(MAX_BLOCKSIZE
, 2 * MAX_BLOCKSIZE
);
269 for (align
= 512; align
<= MAX_BLOCKSIZE
; align
<<= 1) {
270 if (pread(s
->fd
, buf
+ align
, MAX_BLOCKSIZE
, 0) >= 0) {
271 s
->buf_align
= align
;
278 if (!bs
->request_alignment
) {
280 buf
= qemu_memalign(s
->buf_align
, MAX_BLOCKSIZE
);
281 for (align
= 512; align
<= MAX_BLOCKSIZE
; align
<<= 1) {
282 if (pread(s
->fd
, buf
, align
, 0) >= 0) {
283 bs
->request_alignment
= align
;
291 static void raw_parse_flags(int bdrv_flags
, int *open_flags
)
293 assert(open_flags
!= NULL
);
295 *open_flags
|= O_BINARY
;
296 *open_flags
&= ~O_ACCMODE
;
297 if (bdrv_flags
& BDRV_O_RDWR
) {
298 *open_flags
|= O_RDWR
;
300 *open_flags
|= O_RDONLY
;
303 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
304 * and O_DIRECT for no caching. */
305 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
306 *open_flags
|= O_DIRECT
;
310 #ifdef CONFIG_LINUX_AIO
311 static int raw_set_aio(void **aio_ctx
, int *use_aio
, int bdrv_flags
)
314 assert(aio_ctx
!= NULL
);
315 assert(use_aio
!= NULL
);
317 * Currently Linux do AIO only for files opened with O_DIRECT
318 * specified so check NOCACHE flag too
320 if ((bdrv_flags
& (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) ==
321 (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) {
323 /* if non-NULL, laio_init() has already been run */
324 if (*aio_ctx
== NULL
) {
325 *aio_ctx
= laio_init();
342 static void raw_parse_filename(const char *filename
, QDict
*options
,
345 /* The filename does not have to be prefixed by the protocol name, since
346 * "file" is the default protocol; therefore, the return value of this
347 * function call can be ignored. */
348 strstart(filename
, "file:", &filename
);
350 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
353 static QemuOptsList raw_runtime_opts
= {
355 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
359 .type
= QEMU_OPT_STRING
,
360 .help
= "File name of the image",
362 { /* end of list */ }
366 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
367 int bdrv_flags
, int open_flags
, Error
**errp
)
369 BDRVRawState
*s
= bs
->opaque
;
371 Error
*local_err
= NULL
;
372 const char *filename
= NULL
;
376 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
377 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
379 error_propagate(errp
, local_err
);
384 filename
= qemu_opt_get(opts
, "filename");
386 ret
= raw_normalize_devicepath(&filename
);
388 error_setg_errno(errp
, -ret
, "Could not normalize device path");
392 s
->open_flags
= open_flags
;
393 raw_parse_flags(bdrv_flags
, &s
->open_flags
);
396 fd
= qemu_open(filename
, s
->open_flags
, 0644);
406 #ifdef CONFIG_LINUX_AIO
407 if (raw_set_aio(&s
->aio_ctx
, &s
->use_aio
, bdrv_flags
)) {
410 error_setg_errno(errp
, -ret
, "Could not set AIO state");
415 s
->has_discard
= true;
416 s
->has_write_zeroes
= true;
418 if (fstat(s
->fd
, &st
) < 0) {
419 error_setg_errno(errp
, errno
, "Could not stat file");
422 if (S_ISREG(st
.st_mode
)) {
423 s
->discard_zeroes
= true;
425 if (S_ISBLK(st
.st_mode
)) {
426 #ifdef BLKDISCARDZEROES
428 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
429 s
->discard_zeroes
= true;
433 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
434 * not rely on the contents of discarded blocks unless using O_DIRECT.
435 * Same for BLKZEROOUT.
437 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
438 s
->discard_zeroes
= false;
439 s
->has_write_zeroes
= false;
445 if (platform_test_xfs_fd(s
->fd
)) {
452 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
459 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
462 BDRVRawState
*s
= bs
->opaque
;
463 Error
*local_err
= NULL
;
466 s
->type
= FTYPE_FILE
;
467 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
469 error_propagate(errp
, local_err
);
474 static int raw_reopen_prepare(BDRVReopenState
*state
,
475 BlockReopenQueue
*queue
, Error
**errp
)
478 BDRVRawReopenState
*raw_s
;
481 assert(state
!= NULL
);
482 assert(state
->bs
!= NULL
);
484 s
= state
->bs
->opaque
;
486 state
->opaque
= g_malloc0(sizeof(BDRVRawReopenState
));
487 raw_s
= state
->opaque
;
489 #ifdef CONFIG_LINUX_AIO
490 raw_s
->use_aio
= s
->use_aio
;
492 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
493 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
494 * won't override aio_ctx if aio_ctx is non-NULL */
495 if (raw_set_aio(&s
->aio_ctx
, &raw_s
->use_aio
, state
->flags
)) {
496 error_setg(errp
, "Could not set AIO state");
501 if (s
->type
== FTYPE_FD
|| s
->type
== FTYPE_CD
) {
502 raw_s
->open_flags
|= O_NONBLOCK
;
505 raw_parse_flags(state
->flags
, &raw_s
->open_flags
);
509 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
511 fcntl_flags
|= O_NOATIME
;
515 /* Not all operating systems have O_ASYNC, and those that don't
516 * will not let us track the state into raw_s->open_flags (typically
517 * you achieve the same effect with an ioctl, for example I_SETSIG
518 * on Solaris). But we do not use O_ASYNC, so that's fine.
520 assert((s
->open_flags
& O_ASYNC
) == 0);
523 if ((raw_s
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
524 /* dup the original fd */
525 /* TODO: use qemu fcntl wrapper */
526 #ifdef F_DUPFD_CLOEXEC
527 raw_s
->fd
= fcntl(s
->fd
, F_DUPFD_CLOEXEC
, 0);
529 raw_s
->fd
= dup(s
->fd
);
530 if (raw_s
->fd
!= -1) {
531 qemu_set_cloexec(raw_s
->fd
);
534 if (raw_s
->fd
>= 0) {
535 ret
= fcntl_setfl(raw_s
->fd
, raw_s
->open_flags
);
537 qemu_close(raw_s
->fd
);
543 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
544 if (raw_s
->fd
== -1) {
545 assert(!(raw_s
->open_flags
& O_CREAT
));
546 raw_s
->fd
= qemu_open(state
->bs
->filename
, raw_s
->open_flags
);
547 if (raw_s
->fd
== -1) {
548 error_setg_errno(errp
, errno
, "Could not reopen file");
555 static void raw_reopen_commit(BDRVReopenState
*state
)
557 BDRVRawReopenState
*raw_s
= state
->opaque
;
558 BDRVRawState
*s
= state
->bs
->opaque
;
560 s
->open_flags
= raw_s
->open_flags
;
564 #ifdef CONFIG_LINUX_AIO
565 s
->use_aio
= raw_s
->use_aio
;
568 g_free(state
->opaque
);
569 state
->opaque
= NULL
;
573 static void raw_reopen_abort(BDRVReopenState
*state
)
575 BDRVRawReopenState
*raw_s
= state
->opaque
;
577 /* nothing to do if NULL, we didn't get far enough */
582 if (raw_s
->fd
>= 0) {
583 qemu_close(raw_s
->fd
);
586 g_free(state
->opaque
);
587 state
->opaque
= NULL
;
590 static int raw_refresh_limits(BlockDriverState
*bs
)
592 BDRVRawState
*s
= bs
->opaque
;
594 raw_probe_alignment(bs
);
595 bs
->bl
.opt_mem_alignment
= s
->buf_align
;
600 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
604 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
612 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
616 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
625 static bool preadv_present
= true;
628 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
630 return preadv(fd
, iov
, nr_iov
, offset
);
634 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
636 return pwritev(fd
, iov
, nr_iov
, offset
);
641 static bool preadv_present
= false;
644 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
650 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
657 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
662 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
663 len
= qemu_pwritev(aiocb
->aio_fildes
,
668 len
= qemu_preadv(aiocb
->aio_fildes
,
672 } while (len
== -1 && errno
== EINTR
);
681 * Read/writes the data to/from a given linear buffer.
683 * Returns the number of bytes handles or -errno in case of an error. Short
684 * reads are only returned if the end of the file is reached.
686 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
691 while (offset
< aiocb
->aio_nbytes
) {
692 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
693 len
= pwrite(aiocb
->aio_fildes
,
694 (const char *)buf
+ offset
,
695 aiocb
->aio_nbytes
- offset
,
696 aiocb
->aio_offset
+ offset
);
698 len
= pread(aiocb
->aio_fildes
,
700 aiocb
->aio_nbytes
- offset
,
701 aiocb
->aio_offset
+ offset
);
703 if (len
== -1 && errno
== EINTR
) {
705 } else if (len
== -1) {
708 } else if (len
== 0) {
717 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
722 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
724 * If there is just a single buffer, and it is properly aligned
725 * we can just use plain pread/pwrite without any problems.
727 if (aiocb
->aio_niov
== 1) {
728 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
731 * We have more than one iovec, and all are properly aligned.
733 * Try preadv/pwritev first and fall back to linearizing the
734 * buffer if it's not supported.
736 if (preadv_present
) {
737 nbytes
= handle_aiocb_rw_vector(aiocb
);
738 if (nbytes
== aiocb
->aio_nbytes
||
739 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
742 preadv_present
= false;
746 * XXX(hch): short read/write. no easy way to handle the reminder
747 * using these interfaces. For now retry using plain
753 * Ok, we have to do it the hard way, copy all segments into
754 * a single aligned buffer.
756 buf
= qemu_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
757 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
761 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
762 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
763 p
+= aiocb
->aio_iov
[i
].iov_len
;
767 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
768 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
770 size_t count
= aiocb
->aio_nbytes
, copy
;
773 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
775 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
776 copy
= aiocb
->aio_iov
[i
].iov_len
;
778 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
789 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
791 struct xfs_flock64 fl
;
793 memset(&fl
, 0, sizeof(fl
));
794 fl
.l_whence
= SEEK_SET
;
798 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
799 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno
));
806 static int xfs_discard(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
808 struct xfs_flock64 fl
;
810 memset(&fl
, 0, sizeof(fl
));
811 fl
.l_whence
= SEEK_SET
;
815 if (xfsctl(NULL
, s
->fd
, XFS_IOC_UNRESVSP64
, &fl
) < 0) {
816 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno
));
824 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
826 int ret
= -EOPNOTSUPP
;
827 BDRVRawState
*s
= aiocb
->bs
->opaque
;
829 if (s
->has_write_zeroes
== 0) {
833 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
836 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
837 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
840 } while (errno
== EINTR
);
847 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
852 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
854 s
->has_write_zeroes
= false;
860 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
862 int ret
= -EOPNOTSUPP
;
863 BDRVRawState
*s
= aiocb
->bs
->opaque
;
865 if (!s
->has_discard
) {
869 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
872 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
873 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
876 } while (errno
== EINTR
);
883 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
887 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
889 if (fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
890 aiocb
->aio_offset
, aiocb
->aio_nbytes
) == 0) {
893 } while (errno
== EINTR
);
899 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
901 s
->has_discard
= false;
907 static int aio_worker(void *arg
)
909 RawPosixAIOData
*aiocb
= arg
;
912 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
914 ret
= handle_aiocb_rw(aiocb
);
915 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
&& aiocb
->bs
->growable
) {
916 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
917 0, aiocb
->aio_nbytes
- ret
);
919 ret
= aiocb
->aio_nbytes
;
921 if (ret
== aiocb
->aio_nbytes
) {
923 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
928 ret
= handle_aiocb_rw(aiocb
);
929 if (ret
== aiocb
->aio_nbytes
) {
931 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
936 ret
= handle_aiocb_flush(aiocb
);
939 ret
= handle_aiocb_ioctl(aiocb
);
941 case QEMU_AIO_DISCARD
:
942 ret
= handle_aiocb_discard(aiocb
);
944 case QEMU_AIO_WRITE_ZEROES
:
945 ret
= handle_aiocb_write_zeroes(aiocb
);
948 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
953 g_slice_free(RawPosixAIOData
, aiocb
);
957 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
958 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
961 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
965 acb
->aio_type
= type
;
966 acb
->aio_fildes
= fd
;
969 acb
->aio_iov
= qiov
->iov
;
970 acb
->aio_niov
= qiov
->niov
;
972 acb
->aio_nbytes
= nb_sectors
* 512;
973 acb
->aio_offset
= sector_num
* 512;
975 trace_paio_submit_co(sector_num
, nb_sectors
, type
);
976 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
977 return thread_pool_submit_co(pool
, aio_worker
, acb
);
980 static BlockDriverAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
981 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
982 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
984 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
988 acb
->aio_type
= type
;
989 acb
->aio_fildes
= fd
;
992 acb
->aio_iov
= qiov
->iov
;
993 acb
->aio_niov
= qiov
->niov
;
995 acb
->aio_nbytes
= nb_sectors
* 512;
996 acb
->aio_offset
= sector_num
* 512;
998 trace_paio_submit(acb
, opaque
, sector_num
, nb_sectors
, type
);
999 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1000 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1003 static BlockDriverAIOCB
*raw_aio_submit(BlockDriverState
*bs
,
1004 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1005 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
1007 BDRVRawState
*s
= bs
->opaque
;
1009 if (fd_open(bs
) < 0)
1013 * If O_DIRECT is used the buffer needs to be aligned on a sector
1014 * boundary. Check if this is the case or tell the low-level
1015 * driver that it needs to copy the buffer.
1017 if ((bs
->open_flags
& BDRV_O_NOCACHE
)) {
1018 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1019 type
|= QEMU_AIO_MISALIGNED
;
1020 #ifdef CONFIG_LINUX_AIO
1021 } else if (s
->use_aio
) {
1022 return laio_submit(bs
, s
->aio_ctx
, s
->fd
, sector_num
, qiov
,
1023 nb_sectors
, cb
, opaque
, type
);
1028 return paio_submit(bs
, s
->fd
, sector_num
, qiov
, nb_sectors
,
1032 static BlockDriverAIOCB
*raw_aio_readv(BlockDriverState
*bs
,
1033 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1034 BlockDriverCompletionFunc
*cb
, void *opaque
)
1036 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1037 cb
, opaque
, QEMU_AIO_READ
);
1040 static BlockDriverAIOCB
*raw_aio_writev(BlockDriverState
*bs
,
1041 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1042 BlockDriverCompletionFunc
*cb
, void *opaque
)
1044 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1045 cb
, opaque
, QEMU_AIO_WRITE
);
1048 static BlockDriverAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1049 BlockDriverCompletionFunc
*cb
, void *opaque
)
1051 BDRVRawState
*s
= bs
->opaque
;
1053 if (fd_open(bs
) < 0)
1056 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1059 static void raw_close(BlockDriverState
*bs
)
1061 BDRVRawState
*s
= bs
->opaque
;
1068 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
1070 BDRVRawState
*s
= bs
->opaque
;
1073 if (fstat(s
->fd
, &st
)) {
1077 if (S_ISREG(st
.st_mode
)) {
1078 if (ftruncate(s
->fd
, offset
) < 0) {
1081 } else if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1082 if (offset
> raw_getlength(bs
)) {
1093 static int64_t raw_getlength(BlockDriverState
*bs
)
1095 BDRVRawState
*s
= bs
->opaque
;
1101 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1102 struct disklabel dl
;
1104 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1106 return (uint64_t)dl
.d_secsize
*
1107 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1111 #elif defined(__NetBSD__)
1112 static int64_t raw_getlength(BlockDriverState
*bs
)
1114 BDRVRawState
*s
= bs
->opaque
;
1120 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1121 struct dkwedge_info dkw
;
1123 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1124 return dkw
.dkw_size
* 512;
1126 struct disklabel dl
;
1128 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1130 return (uint64_t)dl
.d_secsize
*
1131 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1136 #elif defined(__sun__)
1137 static int64_t raw_getlength(BlockDriverState
*bs
)
1139 BDRVRawState
*s
= bs
->opaque
;
1140 struct dk_minfo minfo
;
1149 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1151 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1153 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1157 * There are reports that lseek on some devices fails, but
1158 * irc discussion said that contingency on contingency was overkill.
1160 return lseek(s
->fd
, 0, SEEK_END
);
1162 #elif defined(CONFIG_BSD)
1163 static int64_t raw_getlength(BlockDriverState
*bs
)
1165 BDRVRawState
*s
= bs
->opaque
;
1169 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1178 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1181 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1182 #ifdef DIOCGMEDIASIZE
1183 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1184 #elif defined(DIOCGPART)
1187 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1188 size
= pi
.media_size
;
1194 #if defined(__APPLE__) && defined(__MACH__)
1195 size
= LONG_LONG_MAX
;
1197 size
= lseek(fd
, 0LL, SEEK_END
);
1199 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1202 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1203 if (size
== 2048LL * (unsigned)-1)
1205 /* XXX no disc? maybe we need to reopen... */
1206 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1213 size
= lseek(fd
, 0, SEEK_END
);
1218 static int64_t raw_getlength(BlockDriverState
*bs
)
1220 BDRVRawState
*s
= bs
->opaque
;
1228 return lseek(s
->fd
, 0, SEEK_END
);
1232 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
1235 BDRVRawState
*s
= bs
->opaque
;
1237 if (fstat(s
->fd
, &st
) < 0) {
1240 return (int64_t)st
.st_blocks
* 512;
1243 static int raw_create(const char *filename
, QEMUOptionParameter
*options
,
1248 int64_t total_size
= 0;
1250 strstart(filename
, "file:", &filename
);
1252 /* Read out options */
1253 while (options
&& options
->name
) {
1254 if (!strcmp(options
->name
, BLOCK_OPT_SIZE
)) {
1255 total_size
= options
->value
.n
/ BDRV_SECTOR_SIZE
;
1260 fd
= qemu_open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
1264 error_setg_errno(errp
, -result
, "Could not create file");
1266 if (ftruncate(fd
, total_size
* BDRV_SECTOR_SIZE
) != 0) {
1268 error_setg_errno(errp
, -result
, "Could not resize file");
1270 if (qemu_close(fd
) != 0) {
1272 error_setg_errno(errp
, -result
, "Could not close the new file");
1278 static int64_t try_fiemap(BlockDriverState
*bs
, off_t start
, off_t
*data
,
1279 off_t
*hole
, int nb_sectors
, int *pnum
)
1281 #ifdef CONFIG_FIEMAP
1282 BDRVRawState
*s
= bs
->opaque
;
1283 int64_t ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1286 struct fiemap_extent fe
;
1289 if (s
->skip_fiemap
) {
1293 f
.fm
.fm_start
= start
;
1294 f
.fm
.fm_length
= (int64_t)nb_sectors
* BDRV_SECTOR_SIZE
;
1296 f
.fm
.fm_extent_count
= 1;
1297 f
.fm
.fm_reserved
= 0;
1298 if (ioctl(s
->fd
, FS_IOC_FIEMAP
, &f
) == -1) {
1299 s
->skip_fiemap
= true;
1303 if (f
.fm
.fm_mapped_extents
== 0) {
1304 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1305 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1307 off_t length
= lseek(s
->fd
, 0, SEEK_END
);
1308 *hole
= f
.fm
.fm_start
;
1309 *data
= MIN(f
.fm
.fm_start
+ f
.fm
.fm_length
, length
);
1311 *data
= f
.fe
.fe_logical
;
1312 *hole
= f
.fe
.fe_logical
+ f
.fe
.fe_length
;
1313 if (f
.fe
.fe_flags
& FIEMAP_EXTENT_UNWRITTEN
) {
1314 ret
|= BDRV_BLOCK_ZERO
;
1324 static int64_t try_seek_hole(BlockDriverState
*bs
, off_t start
, off_t
*data
,
1325 off_t
*hole
, int *pnum
)
1327 #if defined SEEK_HOLE && defined SEEK_DATA
1328 BDRVRawState
*s
= bs
->opaque
;
1330 *hole
= lseek(s
->fd
, start
, SEEK_HOLE
);
1332 /* -ENXIO indicates that sector_num was past the end of the file.
1333 * There is a virtual hole there. */
1334 assert(errno
!= -ENXIO
);
1339 if (*hole
> start
) {
1342 /* On a hole. We need another syscall to find its end. */
1343 *data
= lseek(s
->fd
, start
, SEEK_DATA
);
1345 *data
= lseek(s
->fd
, 0, SEEK_END
);
1349 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1356 * Returns true iff the specified sector is present in the disk image. Drivers
1357 * not implementing the functionality are assumed to not support backing files,
1358 * hence all their sectors are reported as allocated.
1360 * If 'sector_num' is beyond the end of the disk image the return value is 0
1361 * and 'pnum' is set to 0.
1363 * 'pnum' is set to the number of sectors (including and immediately following
1364 * the specified sector) that are known to be in the same
1365 * allocated/unallocated state.
1367 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1368 * beyond the end of the disk image it will be clamped.
1370 static int64_t coroutine_fn
raw_co_get_block_status(BlockDriverState
*bs
,
1372 int nb_sectors
, int *pnum
)
1374 off_t start
, data
= 0, hole
= 0;
1382 start
= sector_num
* BDRV_SECTOR_SIZE
;
1384 ret
= try_fiemap(bs
, start
, &data
, &hole
, nb_sectors
, pnum
);
1386 ret
= try_seek_hole(bs
, start
, &data
, &hole
, pnum
);
1388 /* Assume everything is allocated. */
1390 hole
= start
+ nb_sectors
* BDRV_SECTOR_SIZE
;
1391 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1395 if (data
<= start
) {
1396 /* On a data extent, compute sectors to the end of the extent. */
1397 *pnum
= MIN(nb_sectors
, (hole
- start
) / BDRV_SECTOR_SIZE
);
1399 /* On a hole, compute sectors to the beginning of the next extent. */
1400 *pnum
= MIN(nb_sectors
, (data
- start
) / BDRV_SECTOR_SIZE
);
1401 ret
&= ~BDRV_BLOCK_DATA
;
1402 ret
|= BDRV_BLOCK_ZERO
;
1408 static coroutine_fn BlockDriverAIOCB
*raw_aio_discard(BlockDriverState
*bs
,
1409 int64_t sector_num
, int nb_sectors
,
1410 BlockDriverCompletionFunc
*cb
, void *opaque
)
1412 BDRVRawState
*s
= bs
->opaque
;
1414 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1415 cb
, opaque
, QEMU_AIO_DISCARD
);
1418 static int coroutine_fn
raw_co_write_zeroes(
1419 BlockDriverState
*bs
, int64_t sector_num
,
1420 int nb_sectors
, BdrvRequestFlags flags
)
1422 BDRVRawState
*s
= bs
->opaque
;
1424 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1425 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1426 QEMU_AIO_WRITE_ZEROES
);
1427 } else if (s
->discard_zeroes
) {
1428 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1434 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1436 BDRVRawState
*s
= bs
->opaque
;
1438 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
1439 bdi
->can_write_zeroes_with_unmap
= s
->discard_zeroes
;
1443 static QEMUOptionParameter raw_create_options
[] = {
1445 .name
= BLOCK_OPT_SIZE
,
1447 .help
= "Virtual disk size"
1452 static BlockDriver bdrv_file
= {
1453 .format_name
= "file",
1454 .protocol_name
= "file",
1455 .instance_size
= sizeof(BDRVRawState
),
1456 .bdrv_needs_filename
= true,
1457 .bdrv_probe
= NULL
, /* no probe for protocols */
1458 .bdrv_parse_filename
= raw_parse_filename
,
1459 .bdrv_file_open
= raw_open
,
1460 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1461 .bdrv_reopen_commit
= raw_reopen_commit
,
1462 .bdrv_reopen_abort
= raw_reopen_abort
,
1463 .bdrv_close
= raw_close
,
1464 .bdrv_create
= raw_create
,
1465 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
1466 .bdrv_co_get_block_status
= raw_co_get_block_status
,
1467 .bdrv_co_write_zeroes
= raw_co_write_zeroes
,
1469 .bdrv_aio_readv
= raw_aio_readv
,
1470 .bdrv_aio_writev
= raw_aio_writev
,
1471 .bdrv_aio_flush
= raw_aio_flush
,
1472 .bdrv_aio_discard
= raw_aio_discard
,
1473 .bdrv_refresh_limits
= raw_refresh_limits
,
1475 .bdrv_truncate
= raw_truncate
,
1476 .bdrv_getlength
= raw_getlength
,
1477 .bdrv_get_info
= raw_get_info
,
1478 .bdrv_get_allocated_file_size
1479 = raw_get_allocated_file_size
,
1481 .create_options
= raw_create_options
,
1484 /***********************************************/
1487 #if defined(__APPLE__) && defined(__MACH__)
1488 static kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
);
1489 static kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
);
1491 kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
)
1493 kern_return_t kernResult
;
1494 mach_port_t masterPort
;
1495 CFMutableDictionaryRef classesToMatch
;
1497 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
1498 if ( KERN_SUCCESS
!= kernResult
) {
1499 printf( "IOMasterPort returned %d\n", kernResult
);
1502 classesToMatch
= IOServiceMatching( kIOCDMediaClass
);
1503 if ( classesToMatch
== NULL
) {
1504 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1506 CFDictionarySetValue( classesToMatch
, CFSTR( kIOMediaEjectableKey
), kCFBooleanTrue
);
1508 kernResult
= IOServiceGetMatchingServices( masterPort
, classesToMatch
, mediaIterator
);
1509 if ( KERN_SUCCESS
!= kernResult
)
1511 printf( "IOServiceGetMatchingServices returned %d\n", kernResult
);
1517 kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
)
1519 io_object_t nextMedia
;
1520 kern_return_t kernResult
= KERN_FAILURE
;
1522 nextMedia
= IOIteratorNext( mediaIterator
);
1525 CFTypeRef bsdPathAsCFString
;
1526 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
1527 if ( bsdPathAsCFString
) {
1528 size_t devPathLength
;
1529 strcpy( bsdPath
, _PATH_DEV
);
1530 strcat( bsdPath
, "r" );
1531 devPathLength
= strlen( bsdPath
);
1532 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
1533 kernResult
= KERN_SUCCESS
;
1535 CFRelease( bsdPathAsCFString
);
1537 IOObjectRelease( nextMedia
);
1545 static int hdev_probe_device(const char *filename
)
1549 /* allow a dedicated CD-ROM driver to match with a higher priority */
1550 if (strstart(filename
, "/dev/cdrom", NULL
))
1553 if (stat(filename
, &st
) >= 0 &&
1554 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
1561 static int check_hdev_writable(BDRVRawState
*s
)
1563 #if defined(BLKROGET)
1564 /* Linux block devices can be configured "read-only" using blockdev(8).
1565 * This is independent of device node permissions and therefore open(2)
1566 * with O_RDWR succeeds. Actual writes fail with EPERM.
1568 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1569 * check for read-only block devices so that Linux block devices behave
1575 if (fstat(s
->fd
, &st
)) {
1579 if (!S_ISBLK(st
.st_mode
)) {
1583 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
1590 #endif /* defined(BLKROGET) */
1594 static void hdev_parse_filename(const char *filename
, QDict
*options
,
1597 /* The prefix is optional, just as for "file". */
1598 strstart(filename
, "host_device:", &filename
);
1600 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
1603 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1606 BDRVRawState
*s
= bs
->opaque
;
1607 Error
*local_err
= NULL
;
1609 const char *filename
= qdict_get_str(options
, "filename");
1611 #if defined(__APPLE__) && defined(__MACH__)
1612 if (strstart(filename
, "/dev/cdrom", NULL
)) {
1613 kern_return_t kernResult
;
1614 io_iterator_t mediaIterator
;
1615 char bsdPath
[ MAXPATHLEN
];
1618 kernResult
= FindEjectableCDMedia( &mediaIterator
);
1619 kernResult
= GetBSDPath( mediaIterator
, bsdPath
, sizeof( bsdPath
) );
1621 if ( bsdPath
[ 0 ] != '\0' ) {
1622 strcat(bsdPath
,"s0");
1623 /* some CDs don't have a partition 0 */
1624 fd
= qemu_open(bsdPath
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
1626 bsdPath
[strlen(bsdPath
)-1] = '1';
1631 qdict_put(options
, "filename", qstring_from_str(filename
));
1634 if ( mediaIterator
)
1635 IOObjectRelease( mediaIterator
);
1639 s
->type
= FTYPE_FILE
;
1640 #if defined(__linux__)
1642 char resolved_path
[ MAXPATHLEN
], *temp
;
1644 temp
= realpath(filename
, resolved_path
);
1645 if (temp
&& strstart(temp
, "/dev/sg", NULL
)) {
1651 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
1654 error_propagate(errp
, local_err
);
1659 if (flags
& BDRV_O_RDWR
) {
1660 ret
= check_hdev_writable(s
);
1663 error_setg_errno(errp
, -ret
, "The device is not writable");
1671 #if defined(__linux__)
1672 /* Note: we do not have a reliable method to detect if the floppy is
1673 present. The current method is to try to open the floppy at every
1674 I/O and to keep it opened during a few hundreds of ms. */
1675 static int fd_open(BlockDriverState
*bs
)
1677 BDRVRawState
*s
= bs
->opaque
;
1678 int last_media_present
;
1680 if (s
->type
!= FTYPE_FD
)
1682 last_media_present
= (s
->fd
>= 0);
1684 (get_clock() - s
->fd_open_time
) >= FD_OPEN_TIMEOUT
) {
1688 printf("Floppy closed\n");
1692 if (s
->fd_got_error
&&
1693 (get_clock() - s
->fd_error_time
) < FD_OPEN_TIMEOUT
) {
1695 printf("No floppy (open delayed)\n");
1699 s
->fd
= qemu_open(bs
->filename
, s
->open_flags
& ~O_NONBLOCK
);
1701 s
->fd_error_time
= get_clock();
1702 s
->fd_got_error
= 1;
1703 if (last_media_present
)
1704 s
->fd_media_changed
= 1;
1706 printf("No floppy\n");
1711 printf("Floppy opened\n");
1714 if (!last_media_present
)
1715 s
->fd_media_changed
= 1;
1716 s
->fd_open_time
= get_clock();
1717 s
->fd_got_error
= 0;
1721 static int hdev_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
1723 BDRVRawState
*s
= bs
->opaque
;
1725 return ioctl(s
->fd
, req
, buf
);
1728 static BlockDriverAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
1729 unsigned long int req
, void *buf
,
1730 BlockDriverCompletionFunc
*cb
, void *opaque
)
1732 BDRVRawState
*s
= bs
->opaque
;
1733 RawPosixAIOData
*acb
;
1736 if (fd_open(bs
) < 0)
1739 acb
= g_slice_new(RawPosixAIOData
);
1741 acb
->aio_type
= QEMU_AIO_IOCTL
;
1742 acb
->aio_fildes
= s
->fd
;
1743 acb
->aio_offset
= 0;
1744 acb
->aio_ioctl_buf
= buf
;
1745 acb
->aio_ioctl_cmd
= req
;
1746 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1747 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1750 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1751 static int fd_open(BlockDriverState
*bs
)
1753 BDRVRawState
*s
= bs
->opaque
;
1755 /* this is just to ensure s->fd is sane (its called by io ops) */
1760 #else /* !linux && !FreeBSD */
1762 static int fd_open(BlockDriverState
*bs
)
1767 #endif /* !linux && !FreeBSD */
1769 static coroutine_fn BlockDriverAIOCB
*hdev_aio_discard(BlockDriverState
*bs
,
1770 int64_t sector_num
, int nb_sectors
,
1771 BlockDriverCompletionFunc
*cb
, void *opaque
)
1773 BDRVRawState
*s
= bs
->opaque
;
1775 if (fd_open(bs
) < 0) {
1778 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1779 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1782 static coroutine_fn
int hdev_co_write_zeroes(BlockDriverState
*bs
,
1783 int64_t sector_num
, int nb_sectors
, BdrvRequestFlags flags
)
1785 BDRVRawState
*s
= bs
->opaque
;
1792 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1793 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1794 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
1795 } else if (s
->discard_zeroes
) {
1796 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1797 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1802 static int hdev_create(const char *filename
, QEMUOptionParameter
*options
,
1807 struct stat stat_buf
;
1808 int64_t total_size
= 0;
1811 /* This function is used by all three protocol block drivers and therefore
1812 * any of these three prefixes may be given.
1813 * The return value has to be stored somewhere, otherwise this is an error
1814 * due to -Werror=unused-value. */
1816 strstart(filename
, "host_device:", &filename
) ||
1817 strstart(filename
, "host_cdrom:" , &filename
) ||
1818 strstart(filename
, "host_floppy:", &filename
);
1822 /* Read out options */
1823 while (options
&& options
->name
) {
1824 if (!strcmp(options
->name
, "size")) {
1825 total_size
= options
->value
.n
/ BDRV_SECTOR_SIZE
;
1830 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
1833 error_setg_errno(errp
, -ret
, "Could not open device");
1837 if (fstat(fd
, &stat_buf
) < 0) {
1839 error_setg_errno(errp
, -ret
, "Could not stat device");
1840 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
1842 "The given file is neither a block nor a character device");
1844 } else if (lseek(fd
, 0, SEEK_END
) < total_size
* BDRV_SECTOR_SIZE
) {
1845 error_setg(errp
, "Device is too small");
1853 static BlockDriver bdrv_host_device
= {
1854 .format_name
= "host_device",
1855 .protocol_name
= "host_device",
1856 .instance_size
= sizeof(BDRVRawState
),
1857 .bdrv_needs_filename
= true,
1858 .bdrv_probe_device
= hdev_probe_device
,
1859 .bdrv_parse_filename
= hdev_parse_filename
,
1860 .bdrv_file_open
= hdev_open
,
1861 .bdrv_close
= raw_close
,
1862 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1863 .bdrv_reopen_commit
= raw_reopen_commit
,
1864 .bdrv_reopen_abort
= raw_reopen_abort
,
1865 .bdrv_create
= hdev_create
,
1866 .create_options
= raw_create_options
,
1867 .bdrv_co_write_zeroes
= hdev_co_write_zeroes
,
1869 .bdrv_aio_readv
= raw_aio_readv
,
1870 .bdrv_aio_writev
= raw_aio_writev
,
1871 .bdrv_aio_flush
= raw_aio_flush
,
1872 .bdrv_aio_discard
= hdev_aio_discard
,
1873 .bdrv_refresh_limits
= raw_refresh_limits
,
1875 .bdrv_truncate
= raw_truncate
,
1876 .bdrv_getlength
= raw_getlength
,
1877 .bdrv_get_info
= raw_get_info
,
1878 .bdrv_get_allocated_file_size
1879 = raw_get_allocated_file_size
,
1881 /* generic scsi device */
1883 .bdrv_ioctl
= hdev_ioctl
,
1884 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
1889 static void floppy_parse_filename(const char *filename
, QDict
*options
,
1892 /* The prefix is optional, just as for "file". */
1893 strstart(filename
, "host_floppy:", &filename
);
1895 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
1898 static int floppy_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1901 BDRVRawState
*s
= bs
->opaque
;
1902 Error
*local_err
= NULL
;
1907 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1908 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
1911 error_propagate(errp
, local_err
);
1916 /* close fd so that we can reopen it as needed */
1919 s
->fd_media_changed
= 1;
1924 static int floppy_probe_device(const char *filename
)
1928 struct floppy_struct fdparam
;
1931 if (strstart(filename
, "/dev/fd", NULL
) &&
1932 !strstart(filename
, "/dev/fdset/", NULL
)) {
1936 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
1940 ret
= fstat(fd
, &st
);
1941 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
1945 /* Attempt to detect via a floppy specific ioctl */
1946 ret
= ioctl(fd
, FDGETPRM
, &fdparam
);
1957 static int floppy_is_inserted(BlockDriverState
*bs
)
1959 return fd_open(bs
) >= 0;
1962 static int floppy_media_changed(BlockDriverState
*bs
)
1964 BDRVRawState
*s
= bs
->opaque
;
1968 * XXX: we do not have a true media changed indication.
1969 * It does not work if the floppy is changed without trying to read it.
1972 ret
= s
->fd_media_changed
;
1973 s
->fd_media_changed
= 0;
1975 printf("Floppy changed=%d\n", ret
);
1980 static void floppy_eject(BlockDriverState
*bs
, bool eject_flag
)
1982 BDRVRawState
*s
= bs
->opaque
;
1989 fd
= qemu_open(bs
->filename
, s
->open_flags
| O_NONBLOCK
);
1991 if (ioctl(fd
, FDEJECT
, 0) < 0)
1997 static BlockDriver bdrv_host_floppy
= {
1998 .format_name
= "host_floppy",
1999 .protocol_name
= "host_floppy",
2000 .instance_size
= sizeof(BDRVRawState
),
2001 .bdrv_needs_filename
= true,
2002 .bdrv_probe_device
= floppy_probe_device
,
2003 .bdrv_parse_filename
= floppy_parse_filename
,
2004 .bdrv_file_open
= floppy_open
,
2005 .bdrv_close
= raw_close
,
2006 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2007 .bdrv_reopen_commit
= raw_reopen_commit
,
2008 .bdrv_reopen_abort
= raw_reopen_abort
,
2009 .bdrv_create
= hdev_create
,
2010 .create_options
= raw_create_options
,
2012 .bdrv_aio_readv
= raw_aio_readv
,
2013 .bdrv_aio_writev
= raw_aio_writev
,
2014 .bdrv_aio_flush
= raw_aio_flush
,
2015 .bdrv_refresh_limits
= raw_refresh_limits
,
2017 .bdrv_truncate
= raw_truncate
,
2018 .bdrv_getlength
= raw_getlength
,
2019 .has_variable_length
= true,
2020 .bdrv_get_allocated_file_size
2021 = raw_get_allocated_file_size
,
2023 /* removable device support */
2024 .bdrv_is_inserted
= floppy_is_inserted
,
2025 .bdrv_media_changed
= floppy_media_changed
,
2026 .bdrv_eject
= floppy_eject
,
2030 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2031 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2034 /* The prefix is optional, just as for "file". */
2035 strstart(filename
, "host_cdrom:", &filename
);
2037 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2042 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2045 BDRVRawState
*s
= bs
->opaque
;
2046 Error
*local_err
= NULL
;
2051 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2052 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2054 error_propagate(errp
, local_err
);
2059 static int cdrom_probe_device(const char *filename
)
2065 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2069 ret
= fstat(fd
, &st
);
2070 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2074 /* Attempt to detect via a CDROM specific ioctl */
2075 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2085 static int cdrom_is_inserted(BlockDriverState
*bs
)
2087 BDRVRawState
*s
= bs
->opaque
;
2090 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2091 if (ret
== CDS_DISC_OK
)
2096 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2098 BDRVRawState
*s
= bs
->opaque
;
2101 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2102 perror("CDROMEJECT");
2104 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2105 perror("CDROMEJECT");
2109 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2111 BDRVRawState
*s
= bs
->opaque
;
2113 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2115 * Note: an error can happen if the distribution automatically
2118 /* perror("CDROM_LOCKDOOR"); */
2122 static BlockDriver bdrv_host_cdrom
= {
2123 .format_name
= "host_cdrom",
2124 .protocol_name
= "host_cdrom",
2125 .instance_size
= sizeof(BDRVRawState
),
2126 .bdrv_needs_filename
= true,
2127 .bdrv_probe_device
= cdrom_probe_device
,
2128 .bdrv_parse_filename
= cdrom_parse_filename
,
2129 .bdrv_file_open
= cdrom_open
,
2130 .bdrv_close
= raw_close
,
2131 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2132 .bdrv_reopen_commit
= raw_reopen_commit
,
2133 .bdrv_reopen_abort
= raw_reopen_abort
,
2134 .bdrv_create
= hdev_create
,
2135 .create_options
= raw_create_options
,
2137 .bdrv_aio_readv
= raw_aio_readv
,
2138 .bdrv_aio_writev
= raw_aio_writev
,
2139 .bdrv_aio_flush
= raw_aio_flush
,
2140 .bdrv_refresh_limits
= raw_refresh_limits
,
2142 .bdrv_truncate
= raw_truncate
,
2143 .bdrv_getlength
= raw_getlength
,
2144 .has_variable_length
= true,
2145 .bdrv_get_allocated_file_size
2146 = raw_get_allocated_file_size
,
2148 /* removable device support */
2149 .bdrv_is_inserted
= cdrom_is_inserted
,
2150 .bdrv_eject
= cdrom_eject
,
2151 .bdrv_lock_medium
= cdrom_lock_medium
,
2153 /* generic scsi device */
2154 .bdrv_ioctl
= hdev_ioctl
,
2155 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2157 #endif /* __linux__ */
2159 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2160 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2163 BDRVRawState
*s
= bs
->opaque
;
2164 Error
*local_err
= NULL
;
2169 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2172 error_propagate(errp
, local_err
);
2177 /* make sure the door isn't locked at this time */
2178 ioctl(s
->fd
, CDIOCALLOW
);
2182 static int cdrom_probe_device(const char *filename
)
2184 if (strstart(filename
, "/dev/cd", NULL
) ||
2185 strstart(filename
, "/dev/acd", NULL
))
2190 static int cdrom_reopen(BlockDriverState
*bs
)
2192 BDRVRawState
*s
= bs
->opaque
;
2196 * Force reread of possibly changed/newly loaded disc,
2197 * FreeBSD seems to not notice sometimes...
2201 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
2208 /* make sure the door isn't locked at this time */
2209 ioctl(s
->fd
, CDIOCALLOW
);
2213 static int cdrom_is_inserted(BlockDriverState
*bs
)
2215 return raw_getlength(bs
) > 0;
2218 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2220 BDRVRawState
*s
= bs
->opaque
;
2225 (void) ioctl(s
->fd
, CDIOCALLOW
);
2228 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
2229 perror("CDIOCEJECT");
2231 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
2232 perror("CDIOCCLOSE");
2238 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2240 BDRVRawState
*s
= bs
->opaque
;
2244 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
2246 * Note: an error can happen if the distribution automatically
2249 /* perror("CDROM_LOCKDOOR"); */
2253 static BlockDriver bdrv_host_cdrom
= {
2254 .format_name
= "host_cdrom",
2255 .protocol_name
= "host_cdrom",
2256 .instance_size
= sizeof(BDRVRawState
),
2257 .bdrv_needs_filename
= true,
2258 .bdrv_probe_device
= cdrom_probe_device
,
2259 .bdrv_parse_filename
= cdrom_parse_filename
,
2260 .bdrv_file_open
= cdrom_open
,
2261 .bdrv_close
= raw_close
,
2262 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2263 .bdrv_reopen_commit
= raw_reopen_commit
,
2264 .bdrv_reopen_abort
= raw_reopen_abort
,
2265 .bdrv_create
= hdev_create
,
2266 .create_options
= raw_create_options
,
2268 .bdrv_aio_readv
= raw_aio_readv
,
2269 .bdrv_aio_writev
= raw_aio_writev
,
2270 .bdrv_aio_flush
= raw_aio_flush
,
2271 .bdrv_refresh_limits
= raw_refresh_limits
,
2273 .bdrv_truncate
= raw_truncate
,
2274 .bdrv_getlength
= raw_getlength
,
2275 .has_variable_length
= true,
2276 .bdrv_get_allocated_file_size
2277 = raw_get_allocated_file_size
,
2279 /* removable device support */
2280 .bdrv_is_inserted
= cdrom_is_inserted
,
2281 .bdrv_eject
= cdrom_eject
,
2282 .bdrv_lock_medium
= cdrom_lock_medium
,
2284 #endif /* __FreeBSD__ */
2286 #ifdef CONFIG_LINUX_AIO
2288 * Return the file descriptor for Linux AIO
2290 * This function is a layering violation and should be removed when it becomes
2291 * possible to call the block layer outside the global mutex. It allows the
2292 * caller to hijack the file descriptor so I/O can be performed outside the
2295 int raw_get_aio_fd(BlockDriverState
*bs
)
2303 if (bs
->drv
== bdrv_find_format("raw")) {
2307 /* raw-posix has several protocols so just check for raw_aio_readv */
2308 if (bs
->drv
->bdrv_aio_readv
!= raw_aio_readv
) {
2318 #endif /* CONFIG_LINUX_AIO */
2320 static void bdrv_file_init(void)
2323 * Register all the drivers. Note that order is important, the driver
2324 * registered last will get probed first.
2326 bdrv_register(&bdrv_file
);
2327 bdrv_register(&bdrv_host_device
);
2329 bdrv_register(&bdrv_host_floppy
);
2330 bdrv_register(&bdrv_host_cdrom
);
2332 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2333 bdrv_register(&bdrv_host_cdrom
);
2337 block_init(bdrv_file_init
);