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 void raw_parse_filename(const char *filename
, QDict
*options
,
342 /* The filename does not have to be prefixed by the protocol name, since
343 * "file" is the default protocol; therefore, the return value of this
344 * function call can be ignored. */
345 strstart(filename
, "file:", &filename
);
347 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
350 static QemuOptsList raw_runtime_opts
= {
352 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
356 .type
= QEMU_OPT_STRING
,
357 .help
= "File name of the image",
359 { /* end of list */ }
363 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
364 int bdrv_flags
, int open_flags
, Error
**errp
)
366 BDRVRawState
*s
= bs
->opaque
;
368 Error
*local_err
= NULL
;
369 const char *filename
;
373 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
374 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
376 error_propagate(errp
, local_err
);
381 filename
= qemu_opt_get(opts
, "filename");
383 ret
= raw_normalize_devicepath(&filename
);
385 error_setg_errno(errp
, -ret
, "Could not normalize device path");
389 s
->open_flags
= open_flags
;
390 raw_parse_flags(bdrv_flags
, &s
->open_flags
);
393 fd
= qemu_open(filename
, s
->open_flags
, 0644);
403 #ifdef CONFIG_LINUX_AIO
404 if (raw_set_aio(&s
->aio_ctx
, &s
->use_aio
, bdrv_flags
)) {
407 error_setg_errno(errp
, -ret
, "Could not set AIO state");
412 s
->has_discard
= true;
413 s
->has_write_zeroes
= true;
415 if (fstat(s
->fd
, &st
) < 0) {
416 error_setg_errno(errp
, errno
, "Could not stat file");
419 if (S_ISREG(st
.st_mode
)) {
420 s
->discard_zeroes
= true;
422 if (S_ISBLK(st
.st_mode
)) {
423 #ifdef BLKDISCARDZEROES
425 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
426 s
->discard_zeroes
= true;
430 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
431 * not rely on the contents of discarded blocks unless using O_DIRECT.
432 * Same for BLKZEROOUT.
434 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
435 s
->discard_zeroes
= false;
436 s
->has_write_zeroes
= false;
442 if (platform_test_xfs_fd(s
->fd
)) {
453 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
456 BDRVRawState
*s
= bs
->opaque
;
457 Error
*local_err
= NULL
;
460 s
->type
= FTYPE_FILE
;
461 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
463 error_propagate(errp
, local_err
);
468 static int raw_reopen_prepare(BDRVReopenState
*state
,
469 BlockReopenQueue
*queue
, Error
**errp
)
472 BDRVRawReopenState
*raw_s
;
475 assert(state
!= NULL
);
476 assert(state
->bs
!= NULL
);
478 s
= state
->bs
->opaque
;
480 state
->opaque
= g_malloc0(sizeof(BDRVRawReopenState
));
481 raw_s
= state
->opaque
;
483 #ifdef CONFIG_LINUX_AIO
484 raw_s
->use_aio
= s
->use_aio
;
486 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
487 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
488 * won't override aio_ctx if aio_ctx is non-NULL */
489 if (raw_set_aio(&s
->aio_ctx
, &raw_s
->use_aio
, state
->flags
)) {
490 error_setg(errp
, "Could not set AIO state");
495 if (s
->type
== FTYPE_FD
|| s
->type
== FTYPE_CD
) {
496 raw_s
->open_flags
|= O_NONBLOCK
;
499 raw_parse_flags(state
->flags
, &raw_s
->open_flags
);
503 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
505 fcntl_flags
|= O_NOATIME
;
509 /* Not all operating systems have O_ASYNC, and those that don't
510 * will not let us track the state into raw_s->open_flags (typically
511 * you achieve the same effect with an ioctl, for example I_SETSIG
512 * on Solaris). But we do not use O_ASYNC, so that's fine.
514 assert((s
->open_flags
& O_ASYNC
) == 0);
517 if ((raw_s
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
518 /* dup the original fd */
519 /* TODO: use qemu fcntl wrapper */
520 #ifdef F_DUPFD_CLOEXEC
521 raw_s
->fd
= fcntl(s
->fd
, F_DUPFD_CLOEXEC
, 0);
523 raw_s
->fd
= dup(s
->fd
);
524 if (raw_s
->fd
!= -1) {
525 qemu_set_cloexec(raw_s
->fd
);
528 if (raw_s
->fd
>= 0) {
529 ret
= fcntl_setfl(raw_s
->fd
, raw_s
->open_flags
);
531 qemu_close(raw_s
->fd
);
537 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
538 if (raw_s
->fd
== -1) {
539 assert(!(raw_s
->open_flags
& O_CREAT
));
540 raw_s
->fd
= qemu_open(state
->bs
->filename
, raw_s
->open_flags
);
541 if (raw_s
->fd
== -1) {
542 error_setg_errno(errp
, errno
, "Could not reopen file");
549 static void raw_reopen_commit(BDRVReopenState
*state
)
551 BDRVRawReopenState
*raw_s
= state
->opaque
;
552 BDRVRawState
*s
= state
->bs
->opaque
;
554 s
->open_flags
= raw_s
->open_flags
;
558 #ifdef CONFIG_LINUX_AIO
559 s
->use_aio
= raw_s
->use_aio
;
562 g_free(state
->opaque
);
563 state
->opaque
= NULL
;
567 static void raw_reopen_abort(BDRVReopenState
*state
)
569 BDRVRawReopenState
*raw_s
= state
->opaque
;
571 /* nothing to do if NULL, we didn't get far enough */
576 if (raw_s
->fd
>= 0) {
577 qemu_close(raw_s
->fd
);
580 g_free(state
->opaque
);
581 state
->opaque
= NULL
;
584 static int raw_refresh_limits(BlockDriverState
*bs
)
586 BDRVRawState
*s
= bs
->opaque
;
588 raw_probe_alignment(bs
);
589 bs
->bl
.opt_mem_alignment
= s
->buf_align
;
594 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
598 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
606 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
610 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
619 static bool preadv_present
= true;
622 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
624 return preadv(fd
, iov
, nr_iov
, offset
);
628 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
630 return pwritev(fd
, iov
, nr_iov
, offset
);
635 static bool preadv_present
= false;
638 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
644 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
651 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
656 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
657 len
= qemu_pwritev(aiocb
->aio_fildes
,
662 len
= qemu_preadv(aiocb
->aio_fildes
,
666 } while (len
== -1 && errno
== EINTR
);
675 * Read/writes the data to/from a given linear buffer.
677 * Returns the number of bytes handles or -errno in case of an error. Short
678 * reads are only returned if the end of the file is reached.
680 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
685 while (offset
< aiocb
->aio_nbytes
) {
686 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
687 len
= pwrite(aiocb
->aio_fildes
,
688 (const char *)buf
+ offset
,
689 aiocb
->aio_nbytes
- offset
,
690 aiocb
->aio_offset
+ offset
);
692 len
= pread(aiocb
->aio_fildes
,
694 aiocb
->aio_nbytes
- offset
,
695 aiocb
->aio_offset
+ offset
);
697 if (len
== -1 && errno
== EINTR
) {
699 } else if (len
== -1) {
702 } else if (len
== 0) {
711 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
716 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
718 * If there is just a single buffer, and it is properly aligned
719 * we can just use plain pread/pwrite without any problems.
721 if (aiocb
->aio_niov
== 1) {
722 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
725 * We have more than one iovec, and all are properly aligned.
727 * Try preadv/pwritev first and fall back to linearizing the
728 * buffer if it's not supported.
730 if (preadv_present
) {
731 nbytes
= handle_aiocb_rw_vector(aiocb
);
732 if (nbytes
== aiocb
->aio_nbytes
||
733 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
736 preadv_present
= false;
740 * XXX(hch): short read/write. no easy way to handle the reminder
741 * using these interfaces. For now retry using plain
747 * Ok, we have to do it the hard way, copy all segments into
748 * a single aligned buffer.
750 buf
= qemu_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
751 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
755 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
756 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
757 p
+= aiocb
->aio_iov
[i
].iov_len
;
761 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
762 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
764 size_t count
= aiocb
->aio_nbytes
, copy
;
767 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
769 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
770 copy
= aiocb
->aio_iov
[i
].iov_len
;
772 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
783 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
785 struct xfs_flock64 fl
;
787 memset(&fl
, 0, sizeof(fl
));
788 fl
.l_whence
= SEEK_SET
;
792 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
793 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno
));
800 static int xfs_discard(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
802 struct xfs_flock64 fl
;
804 memset(&fl
, 0, sizeof(fl
));
805 fl
.l_whence
= SEEK_SET
;
809 if (xfsctl(NULL
, s
->fd
, XFS_IOC_UNRESVSP64
, &fl
) < 0) {
810 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno
));
818 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
820 int ret
= -EOPNOTSUPP
;
821 BDRVRawState
*s
= aiocb
->bs
->opaque
;
823 if (s
->has_write_zeroes
== 0) {
827 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
830 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
831 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
834 } while (errno
== EINTR
);
841 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
846 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
848 s
->has_write_zeroes
= false;
854 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
856 int ret
= -EOPNOTSUPP
;
857 BDRVRawState
*s
= aiocb
->bs
->opaque
;
859 if (!s
->has_discard
) {
863 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
866 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
867 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
870 } while (errno
== EINTR
);
877 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
881 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
883 if (fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
884 aiocb
->aio_offset
, aiocb
->aio_nbytes
) == 0) {
887 } while (errno
== EINTR
);
893 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
895 s
->has_discard
= false;
901 static int aio_worker(void *arg
)
903 RawPosixAIOData
*aiocb
= arg
;
906 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
908 ret
= handle_aiocb_rw(aiocb
);
909 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
&& aiocb
->bs
->growable
) {
910 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
911 0, aiocb
->aio_nbytes
- ret
);
913 ret
= aiocb
->aio_nbytes
;
915 if (ret
== aiocb
->aio_nbytes
) {
917 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
922 ret
= handle_aiocb_rw(aiocb
);
923 if (ret
== aiocb
->aio_nbytes
) {
925 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
930 ret
= handle_aiocb_flush(aiocb
);
933 ret
= handle_aiocb_ioctl(aiocb
);
935 case QEMU_AIO_DISCARD
:
936 ret
= handle_aiocb_discard(aiocb
);
938 case QEMU_AIO_WRITE_ZEROES
:
939 ret
= handle_aiocb_write_zeroes(aiocb
);
942 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
947 g_slice_free(RawPosixAIOData
, aiocb
);
951 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
952 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
955 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
959 acb
->aio_type
= type
;
960 acb
->aio_fildes
= fd
;
963 acb
->aio_iov
= qiov
->iov
;
964 acb
->aio_niov
= qiov
->niov
;
966 acb
->aio_nbytes
= nb_sectors
* 512;
967 acb
->aio_offset
= sector_num
* 512;
969 trace_paio_submit_co(sector_num
, nb_sectors
, type
);
970 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
971 return thread_pool_submit_co(pool
, aio_worker
, acb
);
974 static BlockDriverAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
975 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
976 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
978 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
982 acb
->aio_type
= type
;
983 acb
->aio_fildes
= fd
;
986 acb
->aio_iov
= qiov
->iov
;
987 acb
->aio_niov
= qiov
->niov
;
989 acb
->aio_nbytes
= nb_sectors
* 512;
990 acb
->aio_offset
= sector_num
* 512;
992 trace_paio_submit(acb
, opaque
, sector_num
, nb_sectors
, type
);
993 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
994 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
997 static BlockDriverAIOCB
*raw_aio_submit(BlockDriverState
*bs
,
998 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
999 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
1001 BDRVRawState
*s
= bs
->opaque
;
1003 if (fd_open(bs
) < 0)
1007 * If O_DIRECT is used the buffer needs to be aligned on a sector
1008 * boundary. Check if this is the case or tell the low-level
1009 * driver that it needs to copy the buffer.
1011 if ((bs
->open_flags
& BDRV_O_NOCACHE
)) {
1012 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1013 type
|= QEMU_AIO_MISALIGNED
;
1014 #ifdef CONFIG_LINUX_AIO
1015 } else if (s
->use_aio
) {
1016 return laio_submit(bs
, s
->aio_ctx
, s
->fd
, sector_num
, qiov
,
1017 nb_sectors
, cb
, opaque
, type
);
1022 return paio_submit(bs
, s
->fd
, sector_num
, qiov
, nb_sectors
,
1026 static BlockDriverAIOCB
*raw_aio_readv(BlockDriverState
*bs
,
1027 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1028 BlockDriverCompletionFunc
*cb
, void *opaque
)
1030 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1031 cb
, opaque
, QEMU_AIO_READ
);
1034 static BlockDriverAIOCB
*raw_aio_writev(BlockDriverState
*bs
,
1035 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1036 BlockDriverCompletionFunc
*cb
, void *opaque
)
1038 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1039 cb
, opaque
, QEMU_AIO_WRITE
);
1042 static BlockDriverAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1043 BlockDriverCompletionFunc
*cb
, void *opaque
)
1045 BDRVRawState
*s
= bs
->opaque
;
1047 if (fd_open(bs
) < 0)
1050 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1053 static void raw_close(BlockDriverState
*bs
)
1055 BDRVRawState
*s
= bs
->opaque
;
1062 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
1064 BDRVRawState
*s
= bs
->opaque
;
1067 if (fstat(s
->fd
, &st
)) {
1071 if (S_ISREG(st
.st_mode
)) {
1072 if (ftruncate(s
->fd
, offset
) < 0) {
1075 } else if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1076 if (offset
> raw_getlength(bs
)) {
1087 static int64_t raw_getlength(BlockDriverState
*bs
)
1089 BDRVRawState
*s
= bs
->opaque
;
1095 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1096 struct disklabel dl
;
1098 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1100 return (uint64_t)dl
.d_secsize
*
1101 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1105 #elif defined(__NetBSD__)
1106 static int64_t raw_getlength(BlockDriverState
*bs
)
1108 BDRVRawState
*s
= bs
->opaque
;
1114 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1115 struct dkwedge_info dkw
;
1117 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1118 return dkw
.dkw_size
* 512;
1120 struct disklabel dl
;
1122 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1124 return (uint64_t)dl
.d_secsize
*
1125 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1130 #elif defined(__sun__)
1131 static int64_t raw_getlength(BlockDriverState
*bs
)
1133 BDRVRawState
*s
= bs
->opaque
;
1134 struct dk_minfo minfo
;
1143 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1145 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1147 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1151 * There are reports that lseek on some devices fails, but
1152 * irc discussion said that contingency on contingency was overkill.
1154 return lseek(s
->fd
, 0, SEEK_END
);
1156 #elif defined(CONFIG_BSD)
1157 static int64_t raw_getlength(BlockDriverState
*bs
)
1159 BDRVRawState
*s
= bs
->opaque
;
1163 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1172 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1175 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1176 #ifdef DIOCGMEDIASIZE
1177 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1178 #elif defined(DIOCGPART)
1181 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1182 size
= pi
.media_size
;
1188 #if defined(__APPLE__) && defined(__MACH__)
1189 size
= LONG_LONG_MAX
;
1191 size
= lseek(fd
, 0LL, SEEK_END
);
1193 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1196 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1197 if (size
== 2048LL * (unsigned)-1)
1199 /* XXX no disc? maybe we need to reopen... */
1200 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1207 size
= lseek(fd
, 0, SEEK_END
);
1212 static int64_t raw_getlength(BlockDriverState
*bs
)
1214 BDRVRawState
*s
= bs
->opaque
;
1222 return lseek(s
->fd
, 0, SEEK_END
);
1226 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
1229 BDRVRawState
*s
= bs
->opaque
;
1231 if (fstat(s
->fd
, &st
) < 0) {
1234 return (int64_t)st
.st_blocks
* 512;
1237 static int raw_create(const char *filename
, QEMUOptionParameter
*options
,
1242 int64_t total_size
= 0;
1244 strstart(filename
, "file:", &filename
);
1246 /* Read out options */
1247 while (options
&& options
->name
) {
1248 if (!strcmp(options
->name
, BLOCK_OPT_SIZE
)) {
1249 total_size
= options
->value
.n
/ BDRV_SECTOR_SIZE
;
1254 fd
= qemu_open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
1258 error_setg_errno(errp
, -result
, "Could not create file");
1260 if (ftruncate(fd
, total_size
* BDRV_SECTOR_SIZE
) != 0) {
1262 error_setg_errno(errp
, -result
, "Could not resize file");
1264 if (qemu_close(fd
) != 0) {
1266 error_setg_errno(errp
, -result
, "Could not close the new file");
1273 * Returns true iff the specified sector is present in the disk image. Drivers
1274 * not implementing the functionality are assumed to not support backing files,
1275 * hence all their sectors are reported as allocated.
1277 * If 'sector_num' is beyond the end of the disk image the return value is 0
1278 * and 'pnum' is set to 0.
1280 * 'pnum' is set to the number of sectors (including and immediately following
1281 * the specified sector) that are known to be in the same
1282 * allocated/unallocated state.
1284 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1285 * beyond the end of the disk image it will be clamped.
1287 static int64_t coroutine_fn
raw_co_get_block_status(BlockDriverState
*bs
,
1289 int nb_sectors
, int *pnum
)
1291 off_t start
, data
, hole
;
1299 start
= sector_num
* BDRV_SECTOR_SIZE
;
1300 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1302 #ifdef CONFIG_FIEMAP
1304 BDRVRawState
*s
= bs
->opaque
;
1307 struct fiemap_extent fe
;
1310 f
.fm
.fm_start
= start
;
1311 f
.fm
.fm_length
= (int64_t)nb_sectors
* BDRV_SECTOR_SIZE
;
1313 f
.fm
.fm_extent_count
= 1;
1314 f
.fm
.fm_reserved
= 0;
1315 if (ioctl(s
->fd
, FS_IOC_FIEMAP
, &f
) == -1) {
1316 /* Assume everything is allocated. */
1321 if (f
.fm
.fm_mapped_extents
== 0) {
1322 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1323 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1325 off_t length
= lseek(s
->fd
, 0, SEEK_END
);
1326 hole
= f
.fm
.fm_start
;
1327 data
= MIN(f
.fm
.fm_start
+ f
.fm
.fm_length
, length
);
1329 data
= f
.fe
.fe_logical
;
1330 hole
= f
.fe
.fe_logical
+ f
.fe
.fe_length
;
1331 if (f
.fe
.fe_flags
& FIEMAP_EXTENT_UNWRITTEN
) {
1332 ret
|= BDRV_BLOCK_ZERO
;
1336 #elif defined SEEK_HOLE && defined SEEK_DATA
1338 BDRVRawState
*s
= bs
->opaque
;
1340 hole
= lseek(s
->fd
, start
, SEEK_HOLE
);
1342 /* -ENXIO indicates that sector_num was past the end of the file.
1343 * There is a virtual hole there. */
1344 assert(errno
!= -ENXIO
);
1346 /* Most likely EINVAL. Assume everything is allocated. */
1354 /* On a hole. We need another syscall to find its end. */
1355 data
= lseek(s
->fd
, start
, SEEK_DATA
);
1357 data
= lseek(s
->fd
, 0, SEEK_END
);
1362 hole
= start
+ nb_sectors
* BDRV_SECTOR_SIZE
;
1365 if (data
<= start
) {
1366 /* On a data extent, compute sectors to the end of the extent. */
1367 *pnum
= MIN(nb_sectors
, (hole
- start
) / BDRV_SECTOR_SIZE
);
1369 /* On a hole, compute sectors to the beginning of the next extent. */
1370 *pnum
= MIN(nb_sectors
, (data
- start
) / BDRV_SECTOR_SIZE
);
1371 ret
&= ~BDRV_BLOCK_DATA
;
1372 ret
|= BDRV_BLOCK_ZERO
;
1378 static coroutine_fn BlockDriverAIOCB
*raw_aio_discard(BlockDriverState
*bs
,
1379 int64_t sector_num
, int nb_sectors
,
1380 BlockDriverCompletionFunc
*cb
, void *opaque
)
1382 BDRVRawState
*s
= bs
->opaque
;
1384 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1385 cb
, opaque
, QEMU_AIO_DISCARD
);
1388 static int coroutine_fn
raw_co_write_zeroes(
1389 BlockDriverState
*bs
, int64_t sector_num
,
1390 int nb_sectors
, BdrvRequestFlags flags
)
1392 BDRVRawState
*s
= bs
->opaque
;
1394 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1395 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1396 QEMU_AIO_WRITE_ZEROES
);
1397 } else if (s
->discard_zeroes
) {
1398 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1404 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1406 BDRVRawState
*s
= bs
->opaque
;
1408 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
1409 bdi
->can_write_zeroes_with_unmap
= s
->discard_zeroes
;
1413 static QEMUOptionParameter raw_create_options
[] = {
1415 .name
= BLOCK_OPT_SIZE
,
1417 .help
= "Virtual disk size"
1422 static BlockDriver bdrv_file
= {
1423 .format_name
= "file",
1424 .protocol_name
= "file",
1425 .instance_size
= sizeof(BDRVRawState
),
1426 .bdrv_needs_filename
= true,
1427 .bdrv_probe
= NULL
, /* no probe for protocols */
1428 .bdrv_parse_filename
= raw_parse_filename
,
1429 .bdrv_file_open
= raw_open
,
1430 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1431 .bdrv_reopen_commit
= raw_reopen_commit
,
1432 .bdrv_reopen_abort
= raw_reopen_abort
,
1433 .bdrv_close
= raw_close
,
1434 .bdrv_create
= raw_create
,
1435 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
1436 .bdrv_co_get_block_status
= raw_co_get_block_status
,
1437 .bdrv_co_write_zeroes
= raw_co_write_zeroes
,
1439 .bdrv_aio_readv
= raw_aio_readv
,
1440 .bdrv_aio_writev
= raw_aio_writev
,
1441 .bdrv_aio_flush
= raw_aio_flush
,
1442 .bdrv_aio_discard
= raw_aio_discard
,
1443 .bdrv_refresh_limits
= raw_refresh_limits
,
1445 .bdrv_truncate
= raw_truncate
,
1446 .bdrv_getlength
= raw_getlength
,
1447 .bdrv_get_info
= raw_get_info
,
1448 .bdrv_get_allocated_file_size
1449 = raw_get_allocated_file_size
,
1451 .create_options
= raw_create_options
,
1454 /***********************************************/
1457 #if defined(__APPLE__) && defined(__MACH__)
1458 static kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
);
1459 static kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
);
1461 kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
)
1463 kern_return_t kernResult
;
1464 mach_port_t masterPort
;
1465 CFMutableDictionaryRef classesToMatch
;
1467 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
1468 if ( KERN_SUCCESS
!= kernResult
) {
1469 printf( "IOMasterPort returned %d\n", kernResult
);
1472 classesToMatch
= IOServiceMatching( kIOCDMediaClass
);
1473 if ( classesToMatch
== NULL
) {
1474 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1476 CFDictionarySetValue( classesToMatch
, CFSTR( kIOMediaEjectableKey
), kCFBooleanTrue
);
1478 kernResult
= IOServiceGetMatchingServices( masterPort
, classesToMatch
, mediaIterator
);
1479 if ( KERN_SUCCESS
!= kernResult
)
1481 printf( "IOServiceGetMatchingServices returned %d\n", kernResult
);
1487 kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
)
1489 io_object_t nextMedia
;
1490 kern_return_t kernResult
= KERN_FAILURE
;
1492 nextMedia
= IOIteratorNext( mediaIterator
);
1495 CFTypeRef bsdPathAsCFString
;
1496 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
1497 if ( bsdPathAsCFString
) {
1498 size_t devPathLength
;
1499 strcpy( bsdPath
, _PATH_DEV
);
1500 strcat( bsdPath
, "r" );
1501 devPathLength
= strlen( bsdPath
);
1502 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
1503 kernResult
= KERN_SUCCESS
;
1505 CFRelease( bsdPathAsCFString
);
1507 IOObjectRelease( nextMedia
);
1515 static int hdev_probe_device(const char *filename
)
1519 /* allow a dedicated CD-ROM driver to match with a higher priority */
1520 if (strstart(filename
, "/dev/cdrom", NULL
))
1523 if (stat(filename
, &st
) >= 0 &&
1524 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
1531 static int check_hdev_writable(BDRVRawState
*s
)
1533 #if defined(BLKROGET)
1534 /* Linux block devices can be configured "read-only" using blockdev(8).
1535 * This is independent of device node permissions and therefore open(2)
1536 * with O_RDWR succeeds. Actual writes fail with EPERM.
1538 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1539 * check for read-only block devices so that Linux block devices behave
1545 if (fstat(s
->fd
, &st
)) {
1549 if (!S_ISBLK(st
.st_mode
)) {
1553 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
1560 #endif /* defined(BLKROGET) */
1564 static void hdev_parse_filename(const char *filename
, QDict
*options
,
1567 /* The prefix is optional, just as for "file". */
1568 strstart(filename
, "host_device:", &filename
);
1570 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
1573 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1576 BDRVRawState
*s
= bs
->opaque
;
1577 Error
*local_err
= NULL
;
1579 const char *filename
= qdict_get_str(options
, "filename");
1581 #if defined(__APPLE__) && defined(__MACH__)
1582 if (strstart(filename
, "/dev/cdrom", NULL
)) {
1583 kern_return_t kernResult
;
1584 io_iterator_t mediaIterator
;
1585 char bsdPath
[ MAXPATHLEN
];
1588 kernResult
= FindEjectableCDMedia( &mediaIterator
);
1589 kernResult
= GetBSDPath( mediaIterator
, bsdPath
, sizeof( bsdPath
) );
1591 if ( bsdPath
[ 0 ] != '\0' ) {
1592 strcat(bsdPath
,"s0");
1593 /* some CDs don't have a partition 0 */
1594 fd
= qemu_open(bsdPath
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
1596 bsdPath
[strlen(bsdPath
)-1] = '1';
1601 qdict_put(options
, "filename", qstring_from_str(filename
));
1604 if ( mediaIterator
)
1605 IOObjectRelease( mediaIterator
);
1609 s
->type
= FTYPE_FILE
;
1610 #if defined(__linux__)
1612 char resolved_path
[ MAXPATHLEN
], *temp
;
1614 temp
= realpath(filename
, resolved_path
);
1615 if (temp
&& strstart(temp
, "/dev/sg", NULL
)) {
1621 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
1624 error_propagate(errp
, local_err
);
1629 if (flags
& BDRV_O_RDWR
) {
1630 ret
= check_hdev_writable(s
);
1633 error_setg_errno(errp
, -ret
, "The device is not writable");
1641 #if defined(__linux__)
1642 /* Note: we do not have a reliable method to detect if the floppy is
1643 present. The current method is to try to open the floppy at every
1644 I/O and to keep it opened during a few hundreds of ms. */
1645 static int fd_open(BlockDriverState
*bs
)
1647 BDRVRawState
*s
= bs
->opaque
;
1648 int last_media_present
;
1650 if (s
->type
!= FTYPE_FD
)
1652 last_media_present
= (s
->fd
>= 0);
1654 (get_clock() - s
->fd_open_time
) >= FD_OPEN_TIMEOUT
) {
1658 printf("Floppy closed\n");
1662 if (s
->fd_got_error
&&
1663 (get_clock() - s
->fd_error_time
) < FD_OPEN_TIMEOUT
) {
1665 printf("No floppy (open delayed)\n");
1669 s
->fd
= qemu_open(bs
->filename
, s
->open_flags
& ~O_NONBLOCK
);
1671 s
->fd_error_time
= get_clock();
1672 s
->fd_got_error
= 1;
1673 if (last_media_present
)
1674 s
->fd_media_changed
= 1;
1676 printf("No floppy\n");
1681 printf("Floppy opened\n");
1684 if (!last_media_present
)
1685 s
->fd_media_changed
= 1;
1686 s
->fd_open_time
= get_clock();
1687 s
->fd_got_error
= 0;
1691 static int hdev_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
1693 BDRVRawState
*s
= bs
->opaque
;
1695 return ioctl(s
->fd
, req
, buf
);
1698 static BlockDriverAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
1699 unsigned long int req
, void *buf
,
1700 BlockDriverCompletionFunc
*cb
, void *opaque
)
1702 BDRVRawState
*s
= bs
->opaque
;
1703 RawPosixAIOData
*acb
;
1706 if (fd_open(bs
) < 0)
1709 acb
= g_slice_new(RawPosixAIOData
);
1711 acb
->aio_type
= QEMU_AIO_IOCTL
;
1712 acb
->aio_fildes
= s
->fd
;
1713 acb
->aio_offset
= 0;
1714 acb
->aio_ioctl_buf
= buf
;
1715 acb
->aio_ioctl_cmd
= req
;
1716 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1717 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1720 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1721 static int fd_open(BlockDriverState
*bs
)
1723 BDRVRawState
*s
= bs
->opaque
;
1725 /* this is just to ensure s->fd is sane (its called by io ops) */
1730 #else /* !linux && !FreeBSD */
1732 static int fd_open(BlockDriverState
*bs
)
1737 #endif /* !linux && !FreeBSD */
1739 static coroutine_fn BlockDriverAIOCB
*hdev_aio_discard(BlockDriverState
*bs
,
1740 int64_t sector_num
, int nb_sectors
,
1741 BlockDriverCompletionFunc
*cb
, void *opaque
)
1743 BDRVRawState
*s
= bs
->opaque
;
1745 if (fd_open(bs
) < 0) {
1748 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1749 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1752 static coroutine_fn
int hdev_co_write_zeroes(BlockDriverState
*bs
,
1753 int64_t sector_num
, int nb_sectors
, BdrvRequestFlags flags
)
1755 BDRVRawState
*s
= bs
->opaque
;
1762 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1763 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1764 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
1765 } else if (s
->discard_zeroes
) {
1766 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1767 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1772 static int hdev_create(const char *filename
, QEMUOptionParameter
*options
,
1777 struct stat stat_buf
;
1778 int64_t total_size
= 0;
1781 /* This function is used by all three protocol block drivers and therefore
1782 * any of these three prefixes may be given.
1783 * The return value has to be stored somewhere, otherwise this is an error
1784 * due to -Werror=unused-value. */
1786 strstart(filename
, "host_device:", &filename
) ||
1787 strstart(filename
, "host_cdrom:" , &filename
) ||
1788 strstart(filename
, "host_floppy:", &filename
);
1792 /* Read out options */
1793 while (options
&& options
->name
) {
1794 if (!strcmp(options
->name
, "size")) {
1795 total_size
= options
->value
.n
/ BDRV_SECTOR_SIZE
;
1800 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
1803 error_setg_errno(errp
, -ret
, "Could not open device");
1807 if (fstat(fd
, &stat_buf
) < 0) {
1809 error_setg_errno(errp
, -ret
, "Could not stat device");
1810 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
1812 "The given file is neither a block nor a character device");
1814 } else if (lseek(fd
, 0, SEEK_END
) < total_size
* BDRV_SECTOR_SIZE
) {
1815 error_setg(errp
, "Device is too small");
1823 static BlockDriver bdrv_host_device
= {
1824 .format_name
= "host_device",
1825 .protocol_name
= "host_device",
1826 .instance_size
= sizeof(BDRVRawState
),
1827 .bdrv_needs_filename
= true,
1828 .bdrv_probe_device
= hdev_probe_device
,
1829 .bdrv_parse_filename
= hdev_parse_filename
,
1830 .bdrv_file_open
= hdev_open
,
1831 .bdrv_close
= raw_close
,
1832 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1833 .bdrv_reopen_commit
= raw_reopen_commit
,
1834 .bdrv_reopen_abort
= raw_reopen_abort
,
1835 .bdrv_create
= hdev_create
,
1836 .create_options
= raw_create_options
,
1837 .bdrv_co_write_zeroes
= hdev_co_write_zeroes
,
1839 .bdrv_aio_readv
= raw_aio_readv
,
1840 .bdrv_aio_writev
= raw_aio_writev
,
1841 .bdrv_aio_flush
= raw_aio_flush
,
1842 .bdrv_aio_discard
= hdev_aio_discard
,
1843 .bdrv_refresh_limits
= raw_refresh_limits
,
1845 .bdrv_truncate
= raw_truncate
,
1846 .bdrv_getlength
= raw_getlength
,
1847 .bdrv_get_info
= raw_get_info
,
1848 .bdrv_get_allocated_file_size
1849 = raw_get_allocated_file_size
,
1851 /* generic scsi device */
1853 .bdrv_ioctl
= hdev_ioctl
,
1854 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
1859 static void floppy_parse_filename(const char *filename
, QDict
*options
,
1862 /* The prefix is optional, just as for "file". */
1863 strstart(filename
, "host_floppy:", &filename
);
1865 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
1868 static int floppy_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1871 BDRVRawState
*s
= bs
->opaque
;
1872 Error
*local_err
= NULL
;
1877 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1878 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
1881 error_propagate(errp
, local_err
);
1886 /* close fd so that we can reopen it as needed */
1889 s
->fd_media_changed
= 1;
1894 static int floppy_probe_device(const char *filename
)
1898 struct floppy_struct fdparam
;
1901 if (strstart(filename
, "/dev/fd", NULL
) &&
1902 !strstart(filename
, "/dev/fdset/", NULL
)) {
1906 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
1910 ret
= fstat(fd
, &st
);
1911 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
1915 /* Attempt to detect via a floppy specific ioctl */
1916 ret
= ioctl(fd
, FDGETPRM
, &fdparam
);
1927 static int floppy_is_inserted(BlockDriverState
*bs
)
1929 return fd_open(bs
) >= 0;
1932 static int floppy_media_changed(BlockDriverState
*bs
)
1934 BDRVRawState
*s
= bs
->opaque
;
1938 * XXX: we do not have a true media changed indication.
1939 * It does not work if the floppy is changed without trying to read it.
1942 ret
= s
->fd_media_changed
;
1943 s
->fd_media_changed
= 0;
1945 printf("Floppy changed=%d\n", ret
);
1950 static void floppy_eject(BlockDriverState
*bs
, bool eject_flag
)
1952 BDRVRawState
*s
= bs
->opaque
;
1959 fd
= qemu_open(bs
->filename
, s
->open_flags
| O_NONBLOCK
);
1961 if (ioctl(fd
, FDEJECT
, 0) < 0)
1967 static BlockDriver bdrv_host_floppy
= {
1968 .format_name
= "host_floppy",
1969 .protocol_name
= "host_floppy",
1970 .instance_size
= sizeof(BDRVRawState
),
1971 .bdrv_needs_filename
= true,
1972 .bdrv_probe_device
= floppy_probe_device
,
1973 .bdrv_parse_filename
= floppy_parse_filename
,
1974 .bdrv_file_open
= floppy_open
,
1975 .bdrv_close
= raw_close
,
1976 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1977 .bdrv_reopen_commit
= raw_reopen_commit
,
1978 .bdrv_reopen_abort
= raw_reopen_abort
,
1979 .bdrv_create
= hdev_create
,
1980 .create_options
= raw_create_options
,
1982 .bdrv_aio_readv
= raw_aio_readv
,
1983 .bdrv_aio_writev
= raw_aio_writev
,
1984 .bdrv_aio_flush
= raw_aio_flush
,
1985 .bdrv_refresh_limits
= raw_refresh_limits
,
1987 .bdrv_truncate
= raw_truncate
,
1988 .bdrv_getlength
= raw_getlength
,
1989 .has_variable_length
= true,
1990 .bdrv_get_allocated_file_size
1991 = raw_get_allocated_file_size
,
1993 /* removable device support */
1994 .bdrv_is_inserted
= floppy_is_inserted
,
1995 .bdrv_media_changed
= floppy_media_changed
,
1996 .bdrv_eject
= floppy_eject
,
2000 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2001 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2004 /* The prefix is optional, just as for "file". */
2005 strstart(filename
, "host_cdrom:", &filename
);
2007 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2012 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2015 BDRVRawState
*s
= bs
->opaque
;
2016 Error
*local_err
= NULL
;
2021 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2022 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2024 error_propagate(errp
, local_err
);
2029 static int cdrom_probe_device(const char *filename
)
2035 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2039 ret
= fstat(fd
, &st
);
2040 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2044 /* Attempt to detect via a CDROM specific ioctl */
2045 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2055 static int cdrom_is_inserted(BlockDriverState
*bs
)
2057 BDRVRawState
*s
= bs
->opaque
;
2060 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2061 if (ret
== CDS_DISC_OK
)
2066 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2068 BDRVRawState
*s
= bs
->opaque
;
2071 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2072 perror("CDROMEJECT");
2074 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2075 perror("CDROMEJECT");
2079 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2081 BDRVRawState
*s
= bs
->opaque
;
2083 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2085 * Note: an error can happen if the distribution automatically
2088 /* perror("CDROM_LOCKDOOR"); */
2092 static BlockDriver bdrv_host_cdrom
= {
2093 .format_name
= "host_cdrom",
2094 .protocol_name
= "host_cdrom",
2095 .instance_size
= sizeof(BDRVRawState
),
2096 .bdrv_needs_filename
= true,
2097 .bdrv_probe_device
= cdrom_probe_device
,
2098 .bdrv_parse_filename
= cdrom_parse_filename
,
2099 .bdrv_file_open
= cdrom_open
,
2100 .bdrv_close
= raw_close
,
2101 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2102 .bdrv_reopen_commit
= raw_reopen_commit
,
2103 .bdrv_reopen_abort
= raw_reopen_abort
,
2104 .bdrv_create
= hdev_create
,
2105 .create_options
= raw_create_options
,
2107 .bdrv_aio_readv
= raw_aio_readv
,
2108 .bdrv_aio_writev
= raw_aio_writev
,
2109 .bdrv_aio_flush
= raw_aio_flush
,
2110 .bdrv_refresh_limits
= raw_refresh_limits
,
2112 .bdrv_truncate
= raw_truncate
,
2113 .bdrv_getlength
= raw_getlength
,
2114 .has_variable_length
= true,
2115 .bdrv_get_allocated_file_size
2116 = raw_get_allocated_file_size
,
2118 /* removable device support */
2119 .bdrv_is_inserted
= cdrom_is_inserted
,
2120 .bdrv_eject
= cdrom_eject
,
2121 .bdrv_lock_medium
= cdrom_lock_medium
,
2123 /* generic scsi device */
2124 .bdrv_ioctl
= hdev_ioctl
,
2125 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2127 #endif /* __linux__ */
2129 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2130 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2133 BDRVRawState
*s
= bs
->opaque
;
2134 Error
*local_err
= NULL
;
2139 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2142 error_propagate(errp
, local_err
);
2147 /* make sure the door isn't locked at this time */
2148 ioctl(s
->fd
, CDIOCALLOW
);
2152 static int cdrom_probe_device(const char *filename
)
2154 if (strstart(filename
, "/dev/cd", NULL
) ||
2155 strstart(filename
, "/dev/acd", NULL
))
2160 static int cdrom_reopen(BlockDriverState
*bs
)
2162 BDRVRawState
*s
= bs
->opaque
;
2166 * Force reread of possibly changed/newly loaded disc,
2167 * FreeBSD seems to not notice sometimes...
2171 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
2178 /* make sure the door isn't locked at this time */
2179 ioctl(s
->fd
, CDIOCALLOW
);
2183 static int cdrom_is_inserted(BlockDriverState
*bs
)
2185 return raw_getlength(bs
) > 0;
2188 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2190 BDRVRawState
*s
= bs
->opaque
;
2195 (void) ioctl(s
->fd
, CDIOCALLOW
);
2198 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
2199 perror("CDIOCEJECT");
2201 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
2202 perror("CDIOCCLOSE");
2208 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2210 BDRVRawState
*s
= bs
->opaque
;
2214 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
2216 * Note: an error can happen if the distribution automatically
2219 /* perror("CDROM_LOCKDOOR"); */
2223 static BlockDriver bdrv_host_cdrom
= {
2224 .format_name
= "host_cdrom",
2225 .protocol_name
= "host_cdrom",
2226 .instance_size
= sizeof(BDRVRawState
),
2227 .bdrv_needs_filename
= true,
2228 .bdrv_probe_device
= cdrom_probe_device
,
2229 .bdrv_parse_filename
= cdrom_parse_filename
,
2230 .bdrv_file_open
= cdrom_open
,
2231 .bdrv_close
= raw_close
,
2232 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2233 .bdrv_reopen_commit
= raw_reopen_commit
,
2234 .bdrv_reopen_abort
= raw_reopen_abort
,
2235 .bdrv_create
= hdev_create
,
2236 .create_options
= raw_create_options
,
2238 .bdrv_aio_readv
= raw_aio_readv
,
2239 .bdrv_aio_writev
= raw_aio_writev
,
2240 .bdrv_aio_flush
= raw_aio_flush
,
2241 .bdrv_refresh_limits
= raw_refresh_limits
,
2243 .bdrv_truncate
= raw_truncate
,
2244 .bdrv_getlength
= raw_getlength
,
2245 .has_variable_length
= true,
2246 .bdrv_get_allocated_file_size
2247 = raw_get_allocated_file_size
,
2249 /* removable device support */
2250 .bdrv_is_inserted
= cdrom_is_inserted
,
2251 .bdrv_eject
= cdrom_eject
,
2252 .bdrv_lock_medium
= cdrom_lock_medium
,
2254 #endif /* __FreeBSD__ */
2256 #ifdef CONFIG_LINUX_AIO
2258 * Return the file descriptor for Linux AIO
2260 * This function is a layering violation and should be removed when it becomes
2261 * possible to call the block layer outside the global mutex. It allows the
2262 * caller to hijack the file descriptor so I/O can be performed outside the
2265 int raw_get_aio_fd(BlockDriverState
*bs
)
2273 if (bs
->drv
== bdrv_find_format("raw")) {
2277 /* raw-posix has several protocols so just check for raw_aio_readv */
2278 if (bs
->drv
->bdrv_aio_readv
!= raw_aio_readv
) {
2288 #endif /* CONFIG_LINUX_AIO */
2290 static void bdrv_file_init(void)
2293 * Register all the drivers. Note that order is important, the driver
2294 * registered last will get probed first.
2296 bdrv_register(&bdrv_file
);
2297 bdrv_register(&bdrv_host_device
);
2299 bdrv_register(&bdrv_host_floppy
);
2300 bdrv_register(&bdrv_host_cdrom
);
2302 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2303 bdrv_register(&bdrv_host_cdrom
);
2307 block_init(bdrv_file_init
);