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;
151 typedef struct BDRVRawReopenState
{
154 #ifdef CONFIG_LINUX_AIO
157 } BDRVRawReopenState
;
159 static int fd_open(BlockDriverState
*bs
);
160 static int64_t raw_getlength(BlockDriverState
*bs
);
162 typedef struct RawPosixAIOData
{
163 BlockDriverState
*bs
;
166 struct iovec
*aio_iov
;
171 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
176 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
177 static int cdrom_reopen(BlockDriverState
*bs
);
180 #if defined(__NetBSD__)
181 static int raw_normalize_devicepath(const char **filename
)
183 static char namebuf
[PATH_MAX
];
184 const char *dp
, *fname
;
188 dp
= strrchr(fname
, '/');
189 if (lstat(fname
, &sb
) < 0) {
190 fprintf(stderr
, "%s: stat failed: %s\n",
191 fname
, strerror(errno
));
195 if (!S_ISBLK(sb
.st_mode
)) {
200 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
202 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
203 (int)(dp
- fname
), fname
, dp
+ 1);
205 fprintf(stderr
, "%s is a block device", fname
);
207 fprintf(stderr
, ", using %s\n", *filename
);
212 static int raw_normalize_devicepath(const char **filename
)
218 static void raw_probe_alignment(BlockDriverState
*bs
)
220 BDRVRawState
*s
= bs
->opaque
;
222 unsigned int sector_size
;
224 /* For /dev/sg devices the alignment is not really used.
225 With buffered I/O, we don't have any restrictions. */
226 if (bs
->sg
|| !(s
->open_flags
& O_DIRECT
)) {
227 bs
->request_alignment
= 1;
232 /* Try a few ioctls to get the right size */
233 bs
->request_alignment
= 0;
237 if (ioctl(s
->fd
, BLKSSZGET
, §or_size
) >= 0) {
238 bs
->request_alignment
= sector_size
;
241 #ifdef DKIOCGETBLOCKSIZE
242 if (ioctl(s
->fd
, DKIOCGETBLOCKSIZE
, §or_size
) >= 0) {
243 bs
->request_alignment
= sector_size
;
246 #ifdef DIOCGSECTORSIZE
247 if (ioctl(s
->fd
, DIOCGSECTORSIZE
, §or_size
) >= 0) {
248 bs
->request_alignment
= sector_size
;
254 if (xfsctl(NULL
, s
->fd
, XFS_IOC_DIOINFO
, &da
) >= 0) {
255 bs
->request_alignment
= da
.d_miniosz
;
256 /* The kernel returns wrong information for d_mem */
257 /* s->buf_align = da.d_mem; */
262 /* If we could not get the sizes so far, we can only guess them */
265 buf
= qemu_memalign(MAX_BLOCKSIZE
, 2 * MAX_BLOCKSIZE
);
266 for (align
= 512; align
<= MAX_BLOCKSIZE
; align
<<= 1) {
267 if (pread(s
->fd
, buf
+ align
, MAX_BLOCKSIZE
, 0) >= 0) {
268 s
->buf_align
= align
;
275 if (!bs
->request_alignment
) {
277 buf
= qemu_memalign(s
->buf_align
, MAX_BLOCKSIZE
);
278 for (align
= 512; align
<= MAX_BLOCKSIZE
; align
<<= 1) {
279 if (pread(s
->fd
, buf
, align
, 0) >= 0) {
280 bs
->request_alignment
= align
;
288 static void raw_parse_flags(int bdrv_flags
, int *open_flags
)
290 assert(open_flags
!= NULL
);
292 *open_flags
|= O_BINARY
;
293 *open_flags
&= ~O_ACCMODE
;
294 if (bdrv_flags
& BDRV_O_RDWR
) {
295 *open_flags
|= O_RDWR
;
297 *open_flags
|= O_RDONLY
;
300 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
301 * and O_DIRECT for no caching. */
302 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
303 *open_flags
|= O_DIRECT
;
307 #ifdef CONFIG_LINUX_AIO
308 static int raw_set_aio(void **aio_ctx
, int *use_aio
, int bdrv_flags
)
311 assert(aio_ctx
!= NULL
);
312 assert(use_aio
!= NULL
);
314 * Currently Linux do AIO only for files opened with O_DIRECT
315 * specified so check NOCACHE flag too
317 if ((bdrv_flags
& (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) ==
318 (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) {
320 /* if non-NULL, laio_init() has already been run */
321 if (*aio_ctx
== NULL
) {
322 *aio_ctx
= laio_init();
339 static QemuOptsList raw_runtime_opts
= {
341 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
345 .type
= QEMU_OPT_STRING
,
346 .help
= "File name of the image",
348 { /* end of list */ }
352 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
353 int bdrv_flags
, int open_flags
, Error
**errp
)
355 BDRVRawState
*s
= bs
->opaque
;
357 Error
*local_err
= NULL
;
358 const char *filename
;
362 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
363 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
364 if (error_is_set(&local_err
)) {
365 error_propagate(errp
, local_err
);
370 filename
= qemu_opt_get(opts
, "filename");
372 ret
= raw_normalize_devicepath(&filename
);
374 error_setg_errno(errp
, -ret
, "Could not normalize device path");
378 s
->open_flags
= open_flags
;
379 raw_parse_flags(bdrv_flags
, &s
->open_flags
);
382 fd
= qemu_open(filename
, s
->open_flags
, 0644);
392 #ifdef CONFIG_LINUX_AIO
393 if (raw_set_aio(&s
->aio_ctx
, &s
->use_aio
, bdrv_flags
)) {
396 error_setg_errno(errp
, -ret
, "Could not set AIO state");
401 s
->has_discard
= true;
402 s
->has_write_zeroes
= true;
404 if (fstat(s
->fd
, &st
) < 0) {
405 error_setg_errno(errp
, errno
, "Could not stat file");
408 if (S_ISREG(st
.st_mode
)) {
409 s
->discard_zeroes
= true;
411 if (S_ISBLK(st
.st_mode
)) {
412 #ifdef BLKDISCARDZEROES
414 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
415 s
->discard_zeroes
= true;
419 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
420 * not rely on the contents of discarded blocks unless using O_DIRECT.
421 * Same for BLKZEROOUT.
423 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
424 s
->discard_zeroes
= false;
425 s
->has_write_zeroes
= false;
431 if (platform_test_xfs_fd(s
->fd
)) {
442 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
445 BDRVRawState
*s
= bs
->opaque
;
446 Error
*local_err
= NULL
;
449 s
->type
= FTYPE_FILE
;
450 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
451 if (error_is_set(&local_err
)) {
452 error_propagate(errp
, local_err
);
457 static int raw_reopen_prepare(BDRVReopenState
*state
,
458 BlockReopenQueue
*queue
, Error
**errp
)
461 BDRVRawReopenState
*raw_s
;
464 assert(state
!= NULL
);
465 assert(state
->bs
!= NULL
);
467 s
= state
->bs
->opaque
;
469 state
->opaque
= g_malloc0(sizeof(BDRVRawReopenState
));
470 raw_s
= state
->opaque
;
472 #ifdef CONFIG_LINUX_AIO
473 raw_s
->use_aio
= s
->use_aio
;
475 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
476 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
477 * won't override aio_ctx if aio_ctx is non-NULL */
478 if (raw_set_aio(&s
->aio_ctx
, &raw_s
->use_aio
, state
->flags
)) {
479 error_setg(errp
, "Could not set AIO state");
484 if (s
->type
== FTYPE_FD
|| s
->type
== FTYPE_CD
) {
485 raw_s
->open_flags
|= O_NONBLOCK
;
488 raw_parse_flags(state
->flags
, &raw_s
->open_flags
);
492 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
494 fcntl_flags
|= O_NOATIME
;
498 /* Not all operating systems have O_ASYNC, and those that don't
499 * will not let us track the state into raw_s->open_flags (typically
500 * you achieve the same effect with an ioctl, for example I_SETSIG
501 * on Solaris). But we do not use O_ASYNC, so that's fine.
503 assert((s
->open_flags
& O_ASYNC
) == 0);
506 if ((raw_s
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
507 /* dup the original fd */
508 /* TODO: use qemu fcntl wrapper */
509 #ifdef F_DUPFD_CLOEXEC
510 raw_s
->fd
= fcntl(s
->fd
, F_DUPFD_CLOEXEC
, 0);
512 raw_s
->fd
= dup(s
->fd
);
513 if (raw_s
->fd
!= -1) {
514 qemu_set_cloexec(raw_s
->fd
);
517 if (raw_s
->fd
>= 0) {
518 ret
= fcntl_setfl(raw_s
->fd
, raw_s
->open_flags
);
520 qemu_close(raw_s
->fd
);
526 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
527 if (raw_s
->fd
== -1) {
528 assert(!(raw_s
->open_flags
& O_CREAT
));
529 raw_s
->fd
= qemu_open(state
->bs
->filename
, raw_s
->open_flags
);
530 if (raw_s
->fd
== -1) {
531 error_setg_errno(errp
, errno
, "Could not reopen file");
538 static void raw_reopen_commit(BDRVReopenState
*state
)
540 BDRVRawReopenState
*raw_s
= state
->opaque
;
541 BDRVRawState
*s
= state
->bs
->opaque
;
543 s
->open_flags
= raw_s
->open_flags
;
547 #ifdef CONFIG_LINUX_AIO
548 s
->use_aio
= raw_s
->use_aio
;
551 g_free(state
->opaque
);
552 state
->opaque
= NULL
;
556 static void raw_reopen_abort(BDRVReopenState
*state
)
558 BDRVRawReopenState
*raw_s
= state
->opaque
;
560 /* nothing to do if NULL, we didn't get far enough */
565 if (raw_s
->fd
>= 0) {
566 qemu_close(raw_s
->fd
);
569 g_free(state
->opaque
);
570 state
->opaque
= NULL
;
573 static int raw_refresh_limits(BlockDriverState
*bs
)
575 BDRVRawState
*s
= bs
->opaque
;
577 raw_probe_alignment(bs
);
578 bs
->bl
.opt_mem_alignment
= s
->buf_align
;
583 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
587 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
595 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
599 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
608 static bool preadv_present
= true;
611 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
613 return preadv(fd
, iov
, nr_iov
, offset
);
617 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
619 return pwritev(fd
, iov
, nr_iov
, offset
);
624 static bool preadv_present
= false;
627 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
633 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
640 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
645 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
646 len
= qemu_pwritev(aiocb
->aio_fildes
,
651 len
= qemu_preadv(aiocb
->aio_fildes
,
655 } while (len
== -1 && errno
== EINTR
);
664 * Read/writes the data to/from a given linear buffer.
666 * Returns the number of bytes handles or -errno in case of an error. Short
667 * reads are only returned if the end of the file is reached.
669 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
674 while (offset
< aiocb
->aio_nbytes
) {
675 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
676 len
= pwrite(aiocb
->aio_fildes
,
677 (const char *)buf
+ offset
,
678 aiocb
->aio_nbytes
- offset
,
679 aiocb
->aio_offset
+ offset
);
681 len
= pread(aiocb
->aio_fildes
,
683 aiocb
->aio_nbytes
- offset
,
684 aiocb
->aio_offset
+ offset
);
686 if (len
== -1 && errno
== EINTR
) {
688 } else if (len
== -1) {
691 } else if (len
== 0) {
700 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
705 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
707 * If there is just a single buffer, and it is properly aligned
708 * we can just use plain pread/pwrite without any problems.
710 if (aiocb
->aio_niov
== 1) {
711 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
714 * We have more than one iovec, and all are properly aligned.
716 * Try preadv/pwritev first and fall back to linearizing the
717 * buffer if it's not supported.
719 if (preadv_present
) {
720 nbytes
= handle_aiocb_rw_vector(aiocb
);
721 if (nbytes
== aiocb
->aio_nbytes
||
722 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
725 preadv_present
= false;
729 * XXX(hch): short read/write. no easy way to handle the reminder
730 * using these interfaces. For now retry using plain
736 * Ok, we have to do it the hard way, copy all segments into
737 * a single aligned buffer.
739 buf
= qemu_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
740 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
744 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
745 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
746 p
+= aiocb
->aio_iov
[i
].iov_len
;
750 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
751 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
753 size_t count
= aiocb
->aio_nbytes
, copy
;
756 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
758 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
759 copy
= aiocb
->aio_iov
[i
].iov_len
;
761 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
772 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
774 struct xfs_flock64 fl
;
776 memset(&fl
, 0, sizeof(fl
));
777 fl
.l_whence
= SEEK_SET
;
781 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
782 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno
));
789 static int xfs_discard(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_UNRESVSP64
, &fl
) < 0) {
799 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno
));
807 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
809 int ret
= -EOPNOTSUPP
;
810 BDRVRawState
*s
= aiocb
->bs
->opaque
;
812 if (s
->has_write_zeroes
== 0) {
816 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
819 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
820 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
823 } while (errno
== EINTR
);
830 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
835 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
837 s
->has_write_zeroes
= false;
843 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
845 int ret
= -EOPNOTSUPP
;
846 BDRVRawState
*s
= aiocb
->bs
->opaque
;
848 if (!s
->has_discard
) {
852 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
855 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
856 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
859 } while (errno
== EINTR
);
866 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
870 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
872 if (fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
873 aiocb
->aio_offset
, aiocb
->aio_nbytes
) == 0) {
876 } while (errno
== EINTR
);
882 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
884 s
->has_discard
= false;
890 static int aio_worker(void *arg
)
892 RawPosixAIOData
*aiocb
= arg
;
895 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
897 ret
= handle_aiocb_rw(aiocb
);
898 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
&& aiocb
->bs
->growable
) {
899 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
900 0, aiocb
->aio_nbytes
- ret
);
902 ret
= aiocb
->aio_nbytes
;
904 if (ret
== aiocb
->aio_nbytes
) {
906 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
911 ret
= handle_aiocb_rw(aiocb
);
912 if (ret
== aiocb
->aio_nbytes
) {
914 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
919 ret
= handle_aiocb_flush(aiocb
);
922 ret
= handle_aiocb_ioctl(aiocb
);
924 case QEMU_AIO_DISCARD
:
925 ret
= handle_aiocb_discard(aiocb
);
927 case QEMU_AIO_WRITE_ZEROES
:
928 ret
= handle_aiocb_write_zeroes(aiocb
);
931 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
936 g_slice_free(RawPosixAIOData
, aiocb
);
940 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
941 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
944 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
948 acb
->aio_type
= type
;
949 acb
->aio_fildes
= fd
;
952 acb
->aio_iov
= qiov
->iov
;
953 acb
->aio_niov
= qiov
->niov
;
955 acb
->aio_nbytes
= nb_sectors
* 512;
956 acb
->aio_offset
= sector_num
* 512;
958 trace_paio_submit_co(sector_num
, nb_sectors
, type
);
959 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
960 return thread_pool_submit_co(pool
, aio_worker
, acb
);
963 static BlockDriverAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
964 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
965 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
967 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
971 acb
->aio_type
= type
;
972 acb
->aio_fildes
= fd
;
975 acb
->aio_iov
= qiov
->iov
;
976 acb
->aio_niov
= qiov
->niov
;
978 acb
->aio_nbytes
= nb_sectors
* 512;
979 acb
->aio_offset
= sector_num
* 512;
981 trace_paio_submit(acb
, opaque
, sector_num
, nb_sectors
, type
);
982 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
983 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
986 static BlockDriverAIOCB
*raw_aio_submit(BlockDriverState
*bs
,
987 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
988 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
990 BDRVRawState
*s
= bs
->opaque
;
996 * If O_DIRECT is used the buffer needs to be aligned on a sector
997 * boundary. Check if this is the case or tell the low-level
998 * driver that it needs to copy the buffer.
1000 if ((bs
->open_flags
& BDRV_O_NOCACHE
)) {
1001 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1002 type
|= QEMU_AIO_MISALIGNED
;
1003 #ifdef CONFIG_LINUX_AIO
1004 } else if (s
->use_aio
) {
1005 return laio_submit(bs
, s
->aio_ctx
, s
->fd
, sector_num
, qiov
,
1006 nb_sectors
, cb
, opaque
, type
);
1011 return paio_submit(bs
, s
->fd
, sector_num
, qiov
, nb_sectors
,
1015 static BlockDriverAIOCB
*raw_aio_readv(BlockDriverState
*bs
,
1016 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1017 BlockDriverCompletionFunc
*cb
, void *opaque
)
1019 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1020 cb
, opaque
, QEMU_AIO_READ
);
1023 static BlockDriverAIOCB
*raw_aio_writev(BlockDriverState
*bs
,
1024 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1025 BlockDriverCompletionFunc
*cb
, void *opaque
)
1027 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1028 cb
, opaque
, QEMU_AIO_WRITE
);
1031 static BlockDriverAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1032 BlockDriverCompletionFunc
*cb
, void *opaque
)
1034 BDRVRawState
*s
= bs
->opaque
;
1036 if (fd_open(bs
) < 0)
1039 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1042 static void raw_close(BlockDriverState
*bs
)
1044 BDRVRawState
*s
= bs
->opaque
;
1051 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
1053 BDRVRawState
*s
= bs
->opaque
;
1056 if (fstat(s
->fd
, &st
)) {
1060 if (S_ISREG(st
.st_mode
)) {
1061 if (ftruncate(s
->fd
, offset
) < 0) {
1064 } else if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1065 if (offset
> raw_getlength(bs
)) {
1076 static int64_t raw_getlength(BlockDriverState
*bs
)
1078 BDRVRawState
*s
= bs
->opaque
;
1084 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1085 struct disklabel dl
;
1087 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1089 return (uint64_t)dl
.d_secsize
*
1090 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1094 #elif defined(__NetBSD__)
1095 static int64_t raw_getlength(BlockDriverState
*bs
)
1097 BDRVRawState
*s
= bs
->opaque
;
1103 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1104 struct dkwedge_info dkw
;
1106 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1107 return dkw
.dkw_size
* 512;
1109 struct disklabel dl
;
1111 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1113 return (uint64_t)dl
.d_secsize
*
1114 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1119 #elif defined(__sun__)
1120 static int64_t raw_getlength(BlockDriverState
*bs
)
1122 BDRVRawState
*s
= bs
->opaque
;
1123 struct dk_minfo minfo
;
1132 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1134 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1136 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1140 * There are reports that lseek on some devices fails, but
1141 * irc discussion said that contingency on contingency was overkill.
1143 return lseek(s
->fd
, 0, SEEK_END
);
1145 #elif defined(CONFIG_BSD)
1146 static int64_t raw_getlength(BlockDriverState
*bs
)
1148 BDRVRawState
*s
= bs
->opaque
;
1152 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1161 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1164 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1165 #ifdef DIOCGMEDIASIZE
1166 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1167 #elif defined(DIOCGPART)
1170 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1171 size
= pi
.media_size
;
1177 #if defined(__APPLE__) && defined(__MACH__)
1178 size
= LONG_LONG_MAX
;
1180 size
= lseek(fd
, 0LL, SEEK_END
);
1182 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1185 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1186 if (size
== 2048LL * (unsigned)-1)
1188 /* XXX no disc? maybe we need to reopen... */
1189 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1196 size
= lseek(fd
, 0, SEEK_END
);
1201 static int64_t raw_getlength(BlockDriverState
*bs
)
1203 BDRVRawState
*s
= bs
->opaque
;
1211 return lseek(s
->fd
, 0, SEEK_END
);
1215 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
1218 BDRVRawState
*s
= bs
->opaque
;
1220 if (fstat(s
->fd
, &st
) < 0) {
1223 return (int64_t)st
.st_blocks
* 512;
1226 static int raw_create(const char *filename
, QEMUOptionParameter
*options
,
1231 int64_t total_size
= 0;
1233 /* Read out options */
1234 while (options
&& options
->name
) {
1235 if (!strcmp(options
->name
, BLOCK_OPT_SIZE
)) {
1236 total_size
= options
->value
.n
/ BDRV_SECTOR_SIZE
;
1241 fd
= qemu_open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
1245 error_setg_errno(errp
, -result
, "Could not create file");
1247 if (ftruncate(fd
, total_size
* BDRV_SECTOR_SIZE
) != 0) {
1249 error_setg_errno(errp
, -result
, "Could not resize file");
1251 if (qemu_close(fd
) != 0) {
1253 error_setg_errno(errp
, -result
, "Could not close the new file");
1260 * Returns true iff the specified sector is present in the disk image. Drivers
1261 * not implementing the functionality are assumed to not support backing files,
1262 * hence all their sectors are reported as allocated.
1264 * If 'sector_num' is beyond the end of the disk image the return value is 0
1265 * and 'pnum' is set to 0.
1267 * 'pnum' is set to the number of sectors (including and immediately following
1268 * the specified sector) that are known to be in the same
1269 * allocated/unallocated state.
1271 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1272 * beyond the end of the disk image it will be clamped.
1274 static int64_t coroutine_fn
raw_co_get_block_status(BlockDriverState
*bs
,
1276 int nb_sectors
, int *pnum
)
1278 off_t start
, data
, hole
;
1286 start
= sector_num
* BDRV_SECTOR_SIZE
;
1287 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1289 #ifdef CONFIG_FIEMAP
1291 BDRVRawState
*s
= bs
->opaque
;
1294 struct fiemap_extent fe
;
1297 f
.fm
.fm_start
= start
;
1298 f
.fm
.fm_length
= (int64_t)nb_sectors
* BDRV_SECTOR_SIZE
;
1300 f
.fm
.fm_extent_count
= 1;
1301 f
.fm
.fm_reserved
= 0;
1302 if (ioctl(s
->fd
, FS_IOC_FIEMAP
, &f
) == -1) {
1303 /* Assume everything is allocated. */
1308 if (f
.fm
.fm_mapped_extents
== 0) {
1309 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1310 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1312 off_t length
= lseek(s
->fd
, 0, SEEK_END
);
1313 hole
= f
.fm
.fm_start
;
1314 data
= MIN(f
.fm
.fm_start
+ f
.fm
.fm_length
, length
);
1316 data
= f
.fe
.fe_logical
;
1317 hole
= f
.fe
.fe_logical
+ f
.fe
.fe_length
;
1318 if (f
.fe
.fe_flags
& FIEMAP_EXTENT_UNWRITTEN
) {
1319 ret
|= BDRV_BLOCK_ZERO
;
1323 #elif defined SEEK_HOLE && defined SEEK_DATA
1325 BDRVRawState
*s
= bs
->opaque
;
1327 hole
= lseek(s
->fd
, start
, SEEK_HOLE
);
1329 /* -ENXIO indicates that sector_num was past the end of the file.
1330 * There is a virtual hole there. */
1331 assert(errno
!= -ENXIO
);
1333 /* Most likely EINVAL. Assume everything is allocated. */
1341 /* On a hole. We need another syscall to find its end. */
1342 data
= lseek(s
->fd
, start
, SEEK_DATA
);
1344 data
= lseek(s
->fd
, 0, SEEK_END
);
1349 hole
= start
+ nb_sectors
* BDRV_SECTOR_SIZE
;
1352 if (data
<= start
) {
1353 /* On a data extent, compute sectors to the end of the extent. */
1354 *pnum
= MIN(nb_sectors
, (hole
- start
) / BDRV_SECTOR_SIZE
);
1356 /* On a hole, compute sectors to the beginning of the next extent. */
1357 *pnum
= MIN(nb_sectors
, (data
- start
) / BDRV_SECTOR_SIZE
);
1358 ret
&= ~BDRV_BLOCK_DATA
;
1359 ret
|= BDRV_BLOCK_ZERO
;
1365 static coroutine_fn BlockDriverAIOCB
*raw_aio_discard(BlockDriverState
*bs
,
1366 int64_t sector_num
, int nb_sectors
,
1367 BlockDriverCompletionFunc
*cb
, void *opaque
)
1369 BDRVRawState
*s
= bs
->opaque
;
1371 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1372 cb
, opaque
, QEMU_AIO_DISCARD
);
1375 static int coroutine_fn
raw_co_write_zeroes(
1376 BlockDriverState
*bs
, int64_t sector_num
,
1377 int nb_sectors
, BdrvRequestFlags flags
)
1379 BDRVRawState
*s
= bs
->opaque
;
1381 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1382 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1383 QEMU_AIO_WRITE_ZEROES
);
1384 } else if (s
->discard_zeroes
) {
1385 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1391 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1393 BDRVRawState
*s
= bs
->opaque
;
1395 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
1396 bdi
->can_write_zeroes_with_unmap
= s
->discard_zeroes
;
1400 static QEMUOptionParameter raw_create_options
[] = {
1402 .name
= BLOCK_OPT_SIZE
,
1404 .help
= "Virtual disk size"
1409 static BlockDriver bdrv_file
= {
1410 .format_name
= "file",
1411 .protocol_name
= "file",
1412 .instance_size
= sizeof(BDRVRawState
),
1413 .bdrv_needs_filename
= true,
1414 .bdrv_probe
= NULL
, /* no probe for protocols */
1415 .bdrv_file_open
= raw_open
,
1416 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1417 .bdrv_reopen_commit
= raw_reopen_commit
,
1418 .bdrv_reopen_abort
= raw_reopen_abort
,
1419 .bdrv_close
= raw_close
,
1420 .bdrv_create
= raw_create
,
1421 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
1422 .bdrv_co_get_block_status
= raw_co_get_block_status
,
1423 .bdrv_co_write_zeroes
= raw_co_write_zeroes
,
1425 .bdrv_aio_readv
= raw_aio_readv
,
1426 .bdrv_aio_writev
= raw_aio_writev
,
1427 .bdrv_aio_flush
= raw_aio_flush
,
1428 .bdrv_aio_discard
= raw_aio_discard
,
1429 .bdrv_refresh_limits
= raw_refresh_limits
,
1431 .bdrv_truncate
= raw_truncate
,
1432 .bdrv_getlength
= raw_getlength
,
1433 .bdrv_get_info
= raw_get_info
,
1434 .bdrv_get_allocated_file_size
1435 = raw_get_allocated_file_size
,
1437 .create_options
= raw_create_options
,
1440 /***********************************************/
1443 #if defined(__APPLE__) && defined(__MACH__)
1444 static kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
);
1445 static kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
);
1447 kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
)
1449 kern_return_t kernResult
;
1450 mach_port_t masterPort
;
1451 CFMutableDictionaryRef classesToMatch
;
1453 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
1454 if ( KERN_SUCCESS
!= kernResult
) {
1455 printf( "IOMasterPort returned %d\n", kernResult
);
1458 classesToMatch
= IOServiceMatching( kIOCDMediaClass
);
1459 if ( classesToMatch
== NULL
) {
1460 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1462 CFDictionarySetValue( classesToMatch
, CFSTR( kIOMediaEjectableKey
), kCFBooleanTrue
);
1464 kernResult
= IOServiceGetMatchingServices( masterPort
, classesToMatch
, mediaIterator
);
1465 if ( KERN_SUCCESS
!= kernResult
)
1467 printf( "IOServiceGetMatchingServices returned %d\n", kernResult
);
1473 kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
)
1475 io_object_t nextMedia
;
1476 kern_return_t kernResult
= KERN_FAILURE
;
1478 nextMedia
= IOIteratorNext( mediaIterator
);
1481 CFTypeRef bsdPathAsCFString
;
1482 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
1483 if ( bsdPathAsCFString
) {
1484 size_t devPathLength
;
1485 strcpy( bsdPath
, _PATH_DEV
);
1486 strcat( bsdPath
, "r" );
1487 devPathLength
= strlen( bsdPath
);
1488 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
1489 kernResult
= KERN_SUCCESS
;
1491 CFRelease( bsdPathAsCFString
);
1493 IOObjectRelease( nextMedia
);
1501 static int hdev_probe_device(const char *filename
)
1505 /* allow a dedicated CD-ROM driver to match with a higher priority */
1506 if (strstart(filename
, "/dev/cdrom", NULL
))
1509 if (stat(filename
, &st
) >= 0 &&
1510 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
1517 static int check_hdev_writable(BDRVRawState
*s
)
1519 #if defined(BLKROGET)
1520 /* Linux block devices can be configured "read-only" using blockdev(8).
1521 * This is independent of device node permissions and therefore open(2)
1522 * with O_RDWR succeeds. Actual writes fail with EPERM.
1524 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1525 * check for read-only block devices so that Linux block devices behave
1531 if (fstat(s
->fd
, &st
)) {
1535 if (!S_ISBLK(st
.st_mode
)) {
1539 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
1546 #endif /* defined(BLKROGET) */
1550 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1553 BDRVRawState
*s
= bs
->opaque
;
1554 Error
*local_err
= NULL
;
1556 const char *filename
= qdict_get_str(options
, "filename");
1558 #if defined(__APPLE__) && defined(__MACH__)
1559 if (strstart(filename
, "/dev/cdrom", NULL
)) {
1560 kern_return_t kernResult
;
1561 io_iterator_t mediaIterator
;
1562 char bsdPath
[ MAXPATHLEN
];
1565 kernResult
= FindEjectableCDMedia( &mediaIterator
);
1566 kernResult
= GetBSDPath( mediaIterator
, bsdPath
, sizeof( bsdPath
) );
1568 if ( bsdPath
[ 0 ] != '\0' ) {
1569 strcat(bsdPath
,"s0");
1570 /* some CDs don't have a partition 0 */
1571 fd
= qemu_open(bsdPath
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
1573 bsdPath
[strlen(bsdPath
)-1] = '1';
1578 qdict_put(options
, "filename", qstring_from_str(filename
));
1581 if ( mediaIterator
)
1582 IOObjectRelease( mediaIterator
);
1586 s
->type
= FTYPE_FILE
;
1587 #if defined(__linux__)
1589 char resolved_path
[ MAXPATHLEN
], *temp
;
1591 temp
= realpath(filename
, resolved_path
);
1592 if (temp
&& strstart(temp
, "/dev/sg", NULL
)) {
1598 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
1600 if (error_is_set(&local_err
)) {
1601 error_propagate(errp
, local_err
);
1606 if (flags
& BDRV_O_RDWR
) {
1607 ret
= check_hdev_writable(s
);
1610 error_setg_errno(errp
, -ret
, "The device is not writable");
1618 #if defined(__linux__)
1619 /* Note: we do not have a reliable method to detect if the floppy is
1620 present. The current method is to try to open the floppy at every
1621 I/O and to keep it opened during a few hundreds of ms. */
1622 static int fd_open(BlockDriverState
*bs
)
1624 BDRVRawState
*s
= bs
->opaque
;
1625 int last_media_present
;
1627 if (s
->type
!= FTYPE_FD
)
1629 last_media_present
= (s
->fd
>= 0);
1631 (get_clock() - s
->fd_open_time
) >= FD_OPEN_TIMEOUT
) {
1635 printf("Floppy closed\n");
1639 if (s
->fd_got_error
&&
1640 (get_clock() - s
->fd_error_time
) < FD_OPEN_TIMEOUT
) {
1642 printf("No floppy (open delayed)\n");
1646 s
->fd
= qemu_open(bs
->filename
, s
->open_flags
& ~O_NONBLOCK
);
1648 s
->fd_error_time
= get_clock();
1649 s
->fd_got_error
= 1;
1650 if (last_media_present
)
1651 s
->fd_media_changed
= 1;
1653 printf("No floppy\n");
1658 printf("Floppy opened\n");
1661 if (!last_media_present
)
1662 s
->fd_media_changed
= 1;
1663 s
->fd_open_time
= get_clock();
1664 s
->fd_got_error
= 0;
1668 static int hdev_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
1670 BDRVRawState
*s
= bs
->opaque
;
1672 return ioctl(s
->fd
, req
, buf
);
1675 static BlockDriverAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
1676 unsigned long int req
, void *buf
,
1677 BlockDriverCompletionFunc
*cb
, void *opaque
)
1679 BDRVRawState
*s
= bs
->opaque
;
1680 RawPosixAIOData
*acb
;
1683 if (fd_open(bs
) < 0)
1686 acb
= g_slice_new(RawPosixAIOData
);
1688 acb
->aio_type
= QEMU_AIO_IOCTL
;
1689 acb
->aio_fildes
= s
->fd
;
1690 acb
->aio_offset
= 0;
1691 acb
->aio_ioctl_buf
= buf
;
1692 acb
->aio_ioctl_cmd
= req
;
1693 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1694 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1697 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1698 static int fd_open(BlockDriverState
*bs
)
1700 BDRVRawState
*s
= bs
->opaque
;
1702 /* this is just to ensure s->fd is sane (its called by io ops) */
1707 #else /* !linux && !FreeBSD */
1709 static int fd_open(BlockDriverState
*bs
)
1714 #endif /* !linux && !FreeBSD */
1716 static coroutine_fn BlockDriverAIOCB
*hdev_aio_discard(BlockDriverState
*bs
,
1717 int64_t sector_num
, int nb_sectors
,
1718 BlockDriverCompletionFunc
*cb
, void *opaque
)
1720 BDRVRawState
*s
= bs
->opaque
;
1722 if (fd_open(bs
) < 0) {
1725 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1726 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1729 static coroutine_fn
int hdev_co_write_zeroes(BlockDriverState
*bs
,
1730 int64_t sector_num
, int nb_sectors
, BdrvRequestFlags flags
)
1732 BDRVRawState
*s
= bs
->opaque
;
1739 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1740 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1741 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
1742 } else if (s
->discard_zeroes
) {
1743 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1744 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1749 static int hdev_create(const char *filename
, QEMUOptionParameter
*options
,
1754 struct stat stat_buf
;
1755 int64_t total_size
= 0;
1757 /* Read out options */
1758 while (options
&& options
->name
) {
1759 if (!strcmp(options
->name
, "size")) {
1760 total_size
= options
->value
.n
/ BDRV_SECTOR_SIZE
;
1765 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
1768 error_setg_errno(errp
, -ret
, "Could not open device");
1772 if (fstat(fd
, &stat_buf
) < 0) {
1774 error_setg_errno(errp
, -ret
, "Could not stat device");
1775 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
1777 "The given file is neither a block nor a character device");
1779 } else if (lseek(fd
, 0, SEEK_END
) < total_size
* BDRV_SECTOR_SIZE
) {
1780 error_setg(errp
, "Device is too small");
1788 static BlockDriver bdrv_host_device
= {
1789 .format_name
= "host_device",
1790 .protocol_name
= "host_device",
1791 .instance_size
= sizeof(BDRVRawState
),
1792 .bdrv_needs_filename
= true,
1793 .bdrv_probe_device
= hdev_probe_device
,
1794 .bdrv_file_open
= hdev_open
,
1795 .bdrv_close
= raw_close
,
1796 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1797 .bdrv_reopen_commit
= raw_reopen_commit
,
1798 .bdrv_reopen_abort
= raw_reopen_abort
,
1799 .bdrv_create
= hdev_create
,
1800 .create_options
= raw_create_options
,
1801 .bdrv_co_write_zeroes
= hdev_co_write_zeroes
,
1803 .bdrv_aio_readv
= raw_aio_readv
,
1804 .bdrv_aio_writev
= raw_aio_writev
,
1805 .bdrv_aio_flush
= raw_aio_flush
,
1806 .bdrv_aio_discard
= hdev_aio_discard
,
1807 .bdrv_refresh_limits
= raw_refresh_limits
,
1809 .bdrv_truncate
= raw_truncate
,
1810 .bdrv_getlength
= raw_getlength
,
1811 .bdrv_get_info
= raw_get_info
,
1812 .bdrv_get_allocated_file_size
1813 = raw_get_allocated_file_size
,
1815 /* generic scsi device */
1817 .bdrv_ioctl
= hdev_ioctl
,
1818 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
1823 static int floppy_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1826 BDRVRawState
*s
= bs
->opaque
;
1827 Error
*local_err
= NULL
;
1832 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1833 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
1835 if (error_is_set(&local_err
)) {
1836 error_propagate(errp
, local_err
);
1841 /* close fd so that we can reopen it as needed */
1844 s
->fd_media_changed
= 1;
1849 static int floppy_probe_device(const char *filename
)
1853 struct floppy_struct fdparam
;
1856 if (strstart(filename
, "/dev/fd", NULL
) &&
1857 !strstart(filename
, "/dev/fdset/", NULL
)) {
1861 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
1865 ret
= fstat(fd
, &st
);
1866 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
1870 /* Attempt to detect via a floppy specific ioctl */
1871 ret
= ioctl(fd
, FDGETPRM
, &fdparam
);
1882 static int floppy_is_inserted(BlockDriverState
*bs
)
1884 return fd_open(bs
) >= 0;
1887 static int floppy_media_changed(BlockDriverState
*bs
)
1889 BDRVRawState
*s
= bs
->opaque
;
1893 * XXX: we do not have a true media changed indication.
1894 * It does not work if the floppy is changed without trying to read it.
1897 ret
= s
->fd_media_changed
;
1898 s
->fd_media_changed
= 0;
1900 printf("Floppy changed=%d\n", ret
);
1905 static void floppy_eject(BlockDriverState
*bs
, bool eject_flag
)
1907 BDRVRawState
*s
= bs
->opaque
;
1914 fd
= qemu_open(bs
->filename
, s
->open_flags
| O_NONBLOCK
);
1916 if (ioctl(fd
, FDEJECT
, 0) < 0)
1922 static BlockDriver bdrv_host_floppy
= {
1923 .format_name
= "host_floppy",
1924 .protocol_name
= "host_floppy",
1925 .instance_size
= sizeof(BDRVRawState
),
1926 .bdrv_needs_filename
= true,
1927 .bdrv_probe_device
= floppy_probe_device
,
1928 .bdrv_file_open
= floppy_open
,
1929 .bdrv_close
= raw_close
,
1930 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1931 .bdrv_reopen_commit
= raw_reopen_commit
,
1932 .bdrv_reopen_abort
= raw_reopen_abort
,
1933 .bdrv_create
= hdev_create
,
1934 .create_options
= raw_create_options
,
1936 .bdrv_aio_readv
= raw_aio_readv
,
1937 .bdrv_aio_writev
= raw_aio_writev
,
1938 .bdrv_aio_flush
= raw_aio_flush
,
1939 .bdrv_refresh_limits
= raw_refresh_limits
,
1941 .bdrv_truncate
= raw_truncate
,
1942 .bdrv_getlength
= raw_getlength
,
1943 .has_variable_length
= true,
1944 .bdrv_get_allocated_file_size
1945 = raw_get_allocated_file_size
,
1947 /* removable device support */
1948 .bdrv_is_inserted
= floppy_is_inserted
,
1949 .bdrv_media_changed
= floppy_media_changed
,
1950 .bdrv_eject
= floppy_eject
,
1953 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1956 BDRVRawState
*s
= bs
->opaque
;
1957 Error
*local_err
= NULL
;
1962 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
1963 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
1964 if (error_is_set(&local_err
)) {
1965 error_propagate(errp
, local_err
);
1970 static int cdrom_probe_device(const char *filename
)
1976 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
1980 ret
= fstat(fd
, &st
);
1981 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
1985 /* Attempt to detect via a CDROM specific ioctl */
1986 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
1996 static int cdrom_is_inserted(BlockDriverState
*bs
)
1998 BDRVRawState
*s
= bs
->opaque
;
2001 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2002 if (ret
== CDS_DISC_OK
)
2007 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2009 BDRVRawState
*s
= bs
->opaque
;
2012 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2013 perror("CDROMEJECT");
2015 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2016 perror("CDROMEJECT");
2020 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2022 BDRVRawState
*s
= bs
->opaque
;
2024 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2026 * Note: an error can happen if the distribution automatically
2029 /* perror("CDROM_LOCKDOOR"); */
2033 static BlockDriver bdrv_host_cdrom
= {
2034 .format_name
= "host_cdrom",
2035 .protocol_name
= "host_cdrom",
2036 .instance_size
= sizeof(BDRVRawState
),
2037 .bdrv_needs_filename
= true,
2038 .bdrv_probe_device
= cdrom_probe_device
,
2039 .bdrv_file_open
= cdrom_open
,
2040 .bdrv_close
= raw_close
,
2041 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2042 .bdrv_reopen_commit
= raw_reopen_commit
,
2043 .bdrv_reopen_abort
= raw_reopen_abort
,
2044 .bdrv_create
= hdev_create
,
2045 .create_options
= raw_create_options
,
2047 .bdrv_aio_readv
= raw_aio_readv
,
2048 .bdrv_aio_writev
= raw_aio_writev
,
2049 .bdrv_aio_flush
= raw_aio_flush
,
2050 .bdrv_refresh_limits
= raw_refresh_limits
,
2052 .bdrv_truncate
= raw_truncate
,
2053 .bdrv_getlength
= raw_getlength
,
2054 .has_variable_length
= true,
2055 .bdrv_get_allocated_file_size
2056 = raw_get_allocated_file_size
,
2058 /* removable device support */
2059 .bdrv_is_inserted
= cdrom_is_inserted
,
2060 .bdrv_eject
= cdrom_eject
,
2061 .bdrv_lock_medium
= cdrom_lock_medium
,
2063 /* generic scsi device */
2064 .bdrv_ioctl
= hdev_ioctl
,
2065 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2067 #endif /* __linux__ */
2069 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2070 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2073 BDRVRawState
*s
= bs
->opaque
;
2074 Error
*local_err
= NULL
;
2079 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2081 if (error_is_set(&local_err
)) {
2082 error_propagate(errp
, local_err
);
2087 /* make sure the door isn't locked at this time */
2088 ioctl(s
->fd
, CDIOCALLOW
);
2092 static int cdrom_probe_device(const char *filename
)
2094 if (strstart(filename
, "/dev/cd", NULL
) ||
2095 strstart(filename
, "/dev/acd", NULL
))
2100 static int cdrom_reopen(BlockDriverState
*bs
)
2102 BDRVRawState
*s
= bs
->opaque
;
2106 * Force reread of possibly changed/newly loaded disc,
2107 * FreeBSD seems to not notice sometimes...
2111 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
2118 /* make sure the door isn't locked at this time */
2119 ioctl(s
->fd
, CDIOCALLOW
);
2123 static int cdrom_is_inserted(BlockDriverState
*bs
)
2125 return raw_getlength(bs
) > 0;
2128 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2130 BDRVRawState
*s
= bs
->opaque
;
2135 (void) ioctl(s
->fd
, CDIOCALLOW
);
2138 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
2139 perror("CDIOCEJECT");
2141 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
2142 perror("CDIOCCLOSE");
2148 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2150 BDRVRawState
*s
= bs
->opaque
;
2154 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
2156 * Note: an error can happen if the distribution automatically
2159 /* perror("CDROM_LOCKDOOR"); */
2163 static BlockDriver bdrv_host_cdrom
= {
2164 .format_name
= "host_cdrom",
2165 .protocol_name
= "host_cdrom",
2166 .instance_size
= sizeof(BDRVRawState
),
2167 .bdrv_needs_filename
= true,
2168 .bdrv_probe_device
= cdrom_probe_device
,
2169 .bdrv_file_open
= cdrom_open
,
2170 .bdrv_close
= raw_close
,
2171 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2172 .bdrv_reopen_commit
= raw_reopen_commit
,
2173 .bdrv_reopen_abort
= raw_reopen_abort
,
2174 .bdrv_create
= hdev_create
,
2175 .create_options
= raw_create_options
,
2177 .bdrv_aio_readv
= raw_aio_readv
,
2178 .bdrv_aio_writev
= raw_aio_writev
,
2179 .bdrv_aio_flush
= raw_aio_flush
,
2180 .bdrv_refresh_limits
= raw_refresh_limits
,
2182 .bdrv_truncate
= raw_truncate
,
2183 .bdrv_getlength
= raw_getlength
,
2184 .has_variable_length
= true,
2185 .bdrv_get_allocated_file_size
2186 = raw_get_allocated_file_size
,
2188 /* removable device support */
2189 .bdrv_is_inserted
= cdrom_is_inserted
,
2190 .bdrv_eject
= cdrom_eject
,
2191 .bdrv_lock_medium
= cdrom_lock_medium
,
2193 #endif /* __FreeBSD__ */
2195 #ifdef CONFIG_LINUX_AIO
2197 * Return the file descriptor for Linux AIO
2199 * This function is a layering violation and should be removed when it becomes
2200 * possible to call the block layer outside the global mutex. It allows the
2201 * caller to hijack the file descriptor so I/O can be performed outside the
2204 int raw_get_aio_fd(BlockDriverState
*bs
)
2212 if (bs
->drv
== bdrv_find_format("raw")) {
2216 /* raw-posix has several protocols so just check for raw_aio_readv */
2217 if (bs
->drv
->bdrv_aio_readv
!= raw_aio_readv
) {
2227 #endif /* CONFIG_LINUX_AIO */
2229 static void bdrv_file_init(void)
2232 * Register all the drivers. Note that order is important, the driver
2233 * registered last will get probed first.
2235 bdrv_register(&bdrv_file
);
2236 bdrv_register(&bdrv_host_device
);
2238 bdrv_register(&bdrv_host_floppy
);
2239 bdrv_register(&bdrv_host_cdrom
);
2241 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2242 bdrv_register(&bdrv_host_cdrom
);
2246 block_init(bdrv_file_init
);