2 * Block driver for RAW files (posix)
4 * Copyright (c) 2006 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 #include "qemu-common.h"
25 #include "qemu/timer.h"
27 #include "block/block_int.h"
28 #include "qemu/module.h"
30 #include "block/thread-pool.h"
34 #if defined(__APPLE__) && (__MACH__)
36 #include <sys/param.h>
37 #include <IOKit/IOKitLib.h>
38 #include <IOKit/IOBSD.h>
39 #include <IOKit/storage/IOMediaBSDClient.h>
40 #include <IOKit/storage/IOMedia.h>
41 #include <IOKit/storage/IOCDMedia.h>
42 //#include <IOKit/storage/IOCDTypes.h>
43 #include <CoreFoundation/CoreFoundation.h>
47 #define _POSIX_PTHREAD_SEMANTICS 1
51 #include <sys/types.h>
53 #include <sys/ioctl.h>
54 #include <sys/param.h>
55 #include <linux/cdrom.h>
60 #include <linux/fiemap.h>
62 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
63 #include <linux/falloc.h>
65 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
71 #include <sys/ioctl.h>
72 #include <sys/disklabel.h>
77 #include <sys/ioctl.h>
78 #include <sys/disklabel.h>
84 #include <sys/ioctl.h>
85 #include <sys/diskslice.h>
92 //#define DEBUG_FLOPPY
95 #if defined(DEBUG_BLOCK)
96 #define DEBUG_BLOCK_PRINT(formatCstr, ...) do { if (qemu_log_enabled()) \
97 { qemu_log(formatCstr, ## __VA_ARGS__); qemu_log_flush(); } } while (0)
99 #define DEBUG_BLOCK_PRINT(formatCstr, ...)
102 /* OS X does not have O_DSYNC */
105 #define O_DSYNC O_SYNC
106 #elif defined(O_FSYNC)
107 #define O_DSYNC O_FSYNC
111 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
113 #define O_DIRECT O_DSYNC
120 /* if the FD is not accessed during that time (in ns), we try to
121 reopen it to see if the disk has been changed */
122 #define FD_OPEN_TIMEOUT (1000000000)
124 #define MAX_BLOCKSIZE 4096
126 typedef struct BDRVRawState
{
132 #if defined(__linux__)
133 /* linux floppy specific */
134 int64_t fd_open_time
;
135 int64_t fd_error_time
;
137 int fd_media_changed
;
139 #ifdef CONFIG_LINUX_AIO
147 bool has_write_zeroes
:1;
148 bool discard_zeroes
:1;
154 typedef struct BDRVRawReopenState
{
157 #ifdef CONFIG_LINUX_AIO
160 } BDRVRawReopenState
;
162 static int fd_open(BlockDriverState
*bs
);
163 static int64_t raw_getlength(BlockDriverState
*bs
);
165 typedef struct RawPosixAIOData
{
166 BlockDriverState
*bs
;
169 struct iovec
*aio_iov
;
174 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
179 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
180 static int cdrom_reopen(BlockDriverState
*bs
);
183 #if defined(__NetBSD__)
184 static int raw_normalize_devicepath(const char **filename
)
186 static char namebuf
[PATH_MAX
];
187 const char *dp
, *fname
;
191 dp
= strrchr(fname
, '/');
192 if (lstat(fname
, &sb
) < 0) {
193 fprintf(stderr
, "%s: stat failed: %s\n",
194 fname
, strerror(errno
));
198 if (!S_ISBLK(sb
.st_mode
)) {
203 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
205 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
206 (int)(dp
- fname
), fname
, dp
+ 1);
208 fprintf(stderr
, "%s is a block device", fname
);
210 fprintf(stderr
, ", using %s\n", *filename
);
215 static int raw_normalize_devicepath(const char **filename
)
221 static void raw_probe_alignment(BlockDriverState
*bs
)
223 BDRVRawState
*s
= bs
->opaque
;
225 unsigned int sector_size
;
227 /* For /dev/sg devices the alignment is not really used.
228 With buffered I/O, we don't have any restrictions. */
229 if (bs
->sg
|| !(s
->open_flags
& O_DIRECT
)) {
230 bs
->request_alignment
= 1;
235 /* Try a few ioctls to get the right size */
236 bs
->request_alignment
= 0;
240 if (ioctl(s
->fd
, BLKSSZGET
, §or_size
) >= 0) {
241 bs
->request_alignment
= sector_size
;
244 #ifdef DKIOCGETBLOCKSIZE
245 if (ioctl(s
->fd
, DKIOCGETBLOCKSIZE
, §or_size
) >= 0) {
246 bs
->request_alignment
= sector_size
;
249 #ifdef DIOCGSECTORSIZE
250 if (ioctl(s
->fd
, DIOCGSECTORSIZE
, §or_size
) >= 0) {
251 bs
->request_alignment
= sector_size
;
257 if (xfsctl(NULL
, s
->fd
, XFS_IOC_DIOINFO
, &da
) >= 0) {
258 bs
->request_alignment
= da
.d_miniosz
;
259 /* The kernel returns wrong information for d_mem */
260 /* s->buf_align = da.d_mem; */
265 /* If we could not get the sizes so far, we can only guess them */
268 buf
= qemu_memalign(MAX_BLOCKSIZE
, 2 * MAX_BLOCKSIZE
);
269 for (align
= 512; align
<= MAX_BLOCKSIZE
; align
<<= 1) {
270 if (pread(s
->fd
, buf
+ align
, MAX_BLOCKSIZE
, 0) >= 0) {
271 s
->buf_align
= align
;
278 if (!bs
->request_alignment
) {
280 buf
= qemu_memalign(s
->buf_align
, MAX_BLOCKSIZE
);
281 for (align
= 512; align
<= MAX_BLOCKSIZE
; align
<<= 1) {
282 if (pread(s
->fd
, buf
, align
, 0) >= 0) {
283 bs
->request_alignment
= align
;
291 static void raw_parse_flags(int bdrv_flags
, int *open_flags
)
293 assert(open_flags
!= NULL
);
295 *open_flags
|= O_BINARY
;
296 *open_flags
&= ~O_ACCMODE
;
297 if (bdrv_flags
& BDRV_O_RDWR
) {
298 *open_flags
|= O_RDWR
;
300 *open_flags
|= O_RDONLY
;
303 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
304 * and O_DIRECT for no caching. */
305 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
306 *open_flags
|= O_DIRECT
;
310 static void raw_detach_aio_context(BlockDriverState
*bs
)
312 #ifdef CONFIG_LINUX_AIO
313 BDRVRawState
*s
= bs
->opaque
;
316 laio_detach_aio_context(s
->aio_ctx
, bdrv_get_aio_context(bs
));
321 static void raw_attach_aio_context(BlockDriverState
*bs
,
322 AioContext
*new_context
)
324 #ifdef CONFIG_LINUX_AIO
325 BDRVRawState
*s
= bs
->opaque
;
328 laio_attach_aio_context(s
->aio_ctx
, new_context
);
333 #ifdef CONFIG_LINUX_AIO
334 static int raw_set_aio(void **aio_ctx
, int *use_aio
, int bdrv_flags
)
337 assert(aio_ctx
!= NULL
);
338 assert(use_aio
!= NULL
);
340 * Currently Linux do AIO only for files opened with O_DIRECT
341 * specified so check NOCACHE flag too
343 if ((bdrv_flags
& (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) ==
344 (BDRV_O_NOCACHE
|BDRV_O_NATIVE_AIO
)) {
346 /* if non-NULL, laio_init() has already been run */
347 if (*aio_ctx
== NULL
) {
348 *aio_ctx
= laio_init();
365 static void raw_parse_filename(const char *filename
, QDict
*options
,
368 /* The filename does not have to be prefixed by the protocol name, since
369 * "file" is the default protocol; therefore, the return value of this
370 * function call can be ignored. */
371 strstart(filename
, "file:", &filename
);
373 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
376 static QemuOptsList raw_runtime_opts
= {
378 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
382 .type
= QEMU_OPT_STRING
,
383 .help
= "File name of the image",
385 { /* end of list */ }
389 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
390 int bdrv_flags
, int open_flags
, Error
**errp
)
392 BDRVRawState
*s
= bs
->opaque
;
394 Error
*local_err
= NULL
;
395 const char *filename
= NULL
;
399 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
400 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
402 error_propagate(errp
, local_err
);
407 filename
= qemu_opt_get(opts
, "filename");
409 ret
= raw_normalize_devicepath(&filename
);
411 error_setg_errno(errp
, -ret
, "Could not normalize device path");
415 s
->open_flags
= open_flags
;
416 raw_parse_flags(bdrv_flags
, &s
->open_flags
);
419 fd
= qemu_open(filename
, s
->open_flags
, 0644);
429 #ifdef CONFIG_LINUX_AIO
430 if (raw_set_aio(&s
->aio_ctx
, &s
->use_aio
, bdrv_flags
)) {
433 error_setg_errno(errp
, -ret
, "Could not set AIO state");
438 s
->has_discard
= true;
439 s
->has_write_zeroes
= true;
441 if (fstat(s
->fd
, &st
) < 0) {
442 error_setg_errno(errp
, errno
, "Could not stat file");
445 if (S_ISREG(st
.st_mode
)) {
446 s
->discard_zeroes
= true;
448 if (S_ISBLK(st
.st_mode
)) {
449 #ifdef BLKDISCARDZEROES
451 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
452 s
->discard_zeroes
= true;
456 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
457 * not rely on the contents of discarded blocks unless using O_DIRECT.
458 * Same for BLKZEROOUT.
460 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
461 s
->discard_zeroes
= false;
462 s
->has_write_zeroes
= false;
468 if (platform_test_xfs_fd(s
->fd
)) {
473 raw_attach_aio_context(bs
, bdrv_get_aio_context(bs
));
477 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
484 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
487 BDRVRawState
*s
= bs
->opaque
;
488 Error
*local_err
= NULL
;
491 s
->type
= FTYPE_FILE
;
492 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
494 error_propagate(errp
, local_err
);
499 static int raw_reopen_prepare(BDRVReopenState
*state
,
500 BlockReopenQueue
*queue
, Error
**errp
)
503 BDRVRawReopenState
*raw_s
;
506 assert(state
!= NULL
);
507 assert(state
->bs
!= NULL
);
509 s
= state
->bs
->opaque
;
511 state
->opaque
= g_malloc0(sizeof(BDRVRawReopenState
));
512 raw_s
= state
->opaque
;
514 #ifdef CONFIG_LINUX_AIO
515 raw_s
->use_aio
= s
->use_aio
;
517 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
518 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
519 * won't override aio_ctx if aio_ctx is non-NULL */
520 if (raw_set_aio(&s
->aio_ctx
, &raw_s
->use_aio
, state
->flags
)) {
521 error_setg(errp
, "Could not set AIO state");
526 if (s
->type
== FTYPE_FD
|| s
->type
== FTYPE_CD
) {
527 raw_s
->open_flags
|= O_NONBLOCK
;
530 raw_parse_flags(state
->flags
, &raw_s
->open_flags
);
534 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
536 fcntl_flags
|= O_NOATIME
;
540 /* Not all operating systems have O_ASYNC, and those that don't
541 * will not let us track the state into raw_s->open_flags (typically
542 * you achieve the same effect with an ioctl, for example I_SETSIG
543 * on Solaris). But we do not use O_ASYNC, so that's fine.
545 assert((s
->open_flags
& O_ASYNC
) == 0);
548 if ((raw_s
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
549 /* dup the original fd */
550 /* TODO: use qemu fcntl wrapper */
551 #ifdef F_DUPFD_CLOEXEC
552 raw_s
->fd
= fcntl(s
->fd
, F_DUPFD_CLOEXEC
, 0);
554 raw_s
->fd
= dup(s
->fd
);
555 if (raw_s
->fd
!= -1) {
556 qemu_set_cloexec(raw_s
->fd
);
559 if (raw_s
->fd
>= 0) {
560 ret
= fcntl_setfl(raw_s
->fd
, raw_s
->open_flags
);
562 qemu_close(raw_s
->fd
);
568 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
569 if (raw_s
->fd
== -1) {
570 assert(!(raw_s
->open_flags
& O_CREAT
));
571 raw_s
->fd
= qemu_open(state
->bs
->filename
, raw_s
->open_flags
);
572 if (raw_s
->fd
== -1) {
573 error_setg_errno(errp
, errno
, "Could not reopen file");
580 static void raw_reopen_commit(BDRVReopenState
*state
)
582 BDRVRawReopenState
*raw_s
= state
->opaque
;
583 BDRVRawState
*s
= state
->bs
->opaque
;
585 s
->open_flags
= raw_s
->open_flags
;
589 #ifdef CONFIG_LINUX_AIO
590 s
->use_aio
= raw_s
->use_aio
;
593 g_free(state
->opaque
);
594 state
->opaque
= NULL
;
598 static void raw_reopen_abort(BDRVReopenState
*state
)
600 BDRVRawReopenState
*raw_s
= state
->opaque
;
602 /* nothing to do if NULL, we didn't get far enough */
607 if (raw_s
->fd
>= 0) {
608 qemu_close(raw_s
->fd
);
611 g_free(state
->opaque
);
612 state
->opaque
= NULL
;
615 static int raw_refresh_limits(BlockDriverState
*bs
)
617 BDRVRawState
*s
= bs
->opaque
;
619 raw_probe_alignment(bs
);
620 bs
->bl
.opt_mem_alignment
= s
->buf_align
;
625 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
629 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
637 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
641 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
650 static bool preadv_present
= true;
653 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
655 return preadv(fd
, iov
, nr_iov
, offset
);
659 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
661 return pwritev(fd
, iov
, nr_iov
, offset
);
666 static bool preadv_present
= false;
669 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
675 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
682 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
687 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
688 len
= qemu_pwritev(aiocb
->aio_fildes
,
693 len
= qemu_preadv(aiocb
->aio_fildes
,
697 } while (len
== -1 && errno
== EINTR
);
706 * Read/writes the data to/from a given linear buffer.
708 * Returns the number of bytes handles or -errno in case of an error. Short
709 * reads are only returned if the end of the file is reached.
711 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
716 while (offset
< aiocb
->aio_nbytes
) {
717 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
718 len
= pwrite(aiocb
->aio_fildes
,
719 (const char *)buf
+ offset
,
720 aiocb
->aio_nbytes
- offset
,
721 aiocb
->aio_offset
+ offset
);
723 len
= pread(aiocb
->aio_fildes
,
725 aiocb
->aio_nbytes
- offset
,
726 aiocb
->aio_offset
+ offset
);
728 if (len
== -1 && errno
== EINTR
) {
730 } else if (len
== -1) {
733 } else if (len
== 0) {
742 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
747 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
749 * If there is just a single buffer, and it is properly aligned
750 * we can just use plain pread/pwrite without any problems.
752 if (aiocb
->aio_niov
== 1) {
753 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
756 * We have more than one iovec, and all are properly aligned.
758 * Try preadv/pwritev first and fall back to linearizing the
759 * buffer if it's not supported.
761 if (preadv_present
) {
762 nbytes
= handle_aiocb_rw_vector(aiocb
);
763 if (nbytes
== aiocb
->aio_nbytes
||
764 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
767 preadv_present
= false;
771 * XXX(hch): short read/write. no easy way to handle the reminder
772 * using these interfaces. For now retry using plain
778 * Ok, we have to do it the hard way, copy all segments into
779 * a single aligned buffer.
781 buf
= qemu_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
782 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
786 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
787 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
788 p
+= aiocb
->aio_iov
[i
].iov_len
;
792 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
793 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
795 size_t count
= aiocb
->aio_nbytes
, copy
;
798 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
800 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
801 copy
= aiocb
->aio_iov
[i
].iov_len
;
803 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
814 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
816 struct xfs_flock64 fl
;
818 memset(&fl
, 0, sizeof(fl
));
819 fl
.l_whence
= SEEK_SET
;
823 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
824 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno
));
831 static int xfs_discard(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
833 struct xfs_flock64 fl
;
835 memset(&fl
, 0, sizeof(fl
));
836 fl
.l_whence
= SEEK_SET
;
840 if (xfsctl(NULL
, s
->fd
, XFS_IOC_UNRESVSP64
, &fl
) < 0) {
841 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno
));
849 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
851 int ret
= -EOPNOTSUPP
;
852 BDRVRawState
*s
= aiocb
->bs
->opaque
;
854 if (s
->has_write_zeroes
== 0) {
858 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
861 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
862 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
865 } while (errno
== EINTR
);
872 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
877 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
879 s
->has_write_zeroes
= false;
885 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
887 int ret
= -EOPNOTSUPP
;
888 BDRVRawState
*s
= aiocb
->bs
->opaque
;
890 if (!s
->has_discard
) {
894 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
897 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
898 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
901 } while (errno
== EINTR
);
908 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
912 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
914 if (fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
915 aiocb
->aio_offset
, aiocb
->aio_nbytes
) == 0) {
918 } while (errno
== EINTR
);
924 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
926 s
->has_discard
= false;
932 static int aio_worker(void *arg
)
934 RawPosixAIOData
*aiocb
= arg
;
937 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
939 ret
= handle_aiocb_rw(aiocb
);
940 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
&& aiocb
->bs
->growable
) {
941 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
942 0, aiocb
->aio_nbytes
- ret
);
944 ret
= aiocb
->aio_nbytes
;
946 if (ret
== aiocb
->aio_nbytes
) {
948 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
953 ret
= handle_aiocb_rw(aiocb
);
954 if (ret
== aiocb
->aio_nbytes
) {
956 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
961 ret
= handle_aiocb_flush(aiocb
);
964 ret
= handle_aiocb_ioctl(aiocb
);
966 case QEMU_AIO_DISCARD
:
967 ret
= handle_aiocb_discard(aiocb
);
969 case QEMU_AIO_WRITE_ZEROES
:
970 ret
= handle_aiocb_write_zeroes(aiocb
);
973 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
978 g_slice_free(RawPosixAIOData
, aiocb
);
982 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
983 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
986 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
990 acb
->aio_type
= type
;
991 acb
->aio_fildes
= fd
;
994 acb
->aio_iov
= qiov
->iov
;
995 acb
->aio_niov
= qiov
->niov
;
997 acb
->aio_nbytes
= nb_sectors
* 512;
998 acb
->aio_offset
= sector_num
* 512;
1000 trace_paio_submit_co(sector_num
, nb_sectors
, type
);
1001 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1002 return thread_pool_submit_co(pool
, aio_worker
, acb
);
1005 static BlockDriverAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
1006 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1007 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
1009 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
1013 acb
->aio_type
= type
;
1014 acb
->aio_fildes
= fd
;
1017 acb
->aio_iov
= qiov
->iov
;
1018 acb
->aio_niov
= qiov
->niov
;
1020 acb
->aio_nbytes
= nb_sectors
* 512;
1021 acb
->aio_offset
= sector_num
* 512;
1023 trace_paio_submit(acb
, opaque
, sector_num
, nb_sectors
, type
);
1024 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1025 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1028 static BlockDriverAIOCB
*raw_aio_submit(BlockDriverState
*bs
,
1029 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1030 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
1032 BDRVRawState
*s
= bs
->opaque
;
1034 if (fd_open(bs
) < 0)
1038 * If O_DIRECT is used the buffer needs to be aligned on a sector
1039 * boundary. Check if this is the case or tell the low-level
1040 * driver that it needs to copy the buffer.
1042 if ((bs
->open_flags
& BDRV_O_NOCACHE
)) {
1043 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1044 type
|= QEMU_AIO_MISALIGNED
;
1045 #ifdef CONFIG_LINUX_AIO
1046 } else if (s
->use_aio
) {
1047 return laio_submit(bs
, s
->aio_ctx
, s
->fd
, sector_num
, qiov
,
1048 nb_sectors
, cb
, opaque
, type
);
1053 return paio_submit(bs
, s
->fd
, sector_num
, qiov
, nb_sectors
,
1057 static BlockDriverAIOCB
*raw_aio_readv(BlockDriverState
*bs
,
1058 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1059 BlockDriverCompletionFunc
*cb
, void *opaque
)
1061 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1062 cb
, opaque
, QEMU_AIO_READ
);
1065 static BlockDriverAIOCB
*raw_aio_writev(BlockDriverState
*bs
,
1066 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1067 BlockDriverCompletionFunc
*cb
, void *opaque
)
1069 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1070 cb
, opaque
, QEMU_AIO_WRITE
);
1073 static BlockDriverAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1074 BlockDriverCompletionFunc
*cb
, void *opaque
)
1076 BDRVRawState
*s
= bs
->opaque
;
1078 if (fd_open(bs
) < 0)
1081 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1084 static void raw_close(BlockDriverState
*bs
)
1086 BDRVRawState
*s
= bs
->opaque
;
1088 raw_detach_aio_context(bs
);
1090 #ifdef CONFIG_LINUX_AIO
1092 laio_cleanup(s
->aio_ctx
);
1101 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
1103 BDRVRawState
*s
= bs
->opaque
;
1106 if (fstat(s
->fd
, &st
)) {
1110 if (S_ISREG(st
.st_mode
)) {
1111 if (ftruncate(s
->fd
, offset
) < 0) {
1114 } else if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1115 if (offset
> raw_getlength(bs
)) {
1126 static int64_t raw_getlength(BlockDriverState
*bs
)
1128 BDRVRawState
*s
= bs
->opaque
;
1134 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1135 struct disklabel dl
;
1137 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1139 return (uint64_t)dl
.d_secsize
*
1140 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1144 #elif defined(__NetBSD__)
1145 static int64_t raw_getlength(BlockDriverState
*bs
)
1147 BDRVRawState
*s
= bs
->opaque
;
1153 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1154 struct dkwedge_info dkw
;
1156 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1157 return dkw
.dkw_size
* 512;
1159 struct disklabel dl
;
1161 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1163 return (uint64_t)dl
.d_secsize
*
1164 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1169 #elif defined(__sun__)
1170 static int64_t raw_getlength(BlockDriverState
*bs
)
1172 BDRVRawState
*s
= bs
->opaque
;
1173 struct dk_minfo minfo
;
1182 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1184 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1186 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1190 * There are reports that lseek on some devices fails, but
1191 * irc discussion said that contingency on contingency was overkill.
1193 return lseek(s
->fd
, 0, SEEK_END
);
1195 #elif defined(CONFIG_BSD)
1196 static int64_t raw_getlength(BlockDriverState
*bs
)
1198 BDRVRawState
*s
= bs
->opaque
;
1202 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1211 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1214 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1215 #ifdef DIOCGMEDIASIZE
1216 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1217 #elif defined(DIOCGPART)
1220 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1221 size
= pi
.media_size
;
1227 #if defined(__APPLE__) && defined(__MACH__)
1230 size
= lseek(fd
, 0LL, SEEK_END
);
1232 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1235 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1236 if (size
== 2048LL * (unsigned)-1)
1238 /* XXX no disc? maybe we need to reopen... */
1239 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1246 size
= lseek(fd
, 0, SEEK_END
);
1251 static int64_t raw_getlength(BlockDriverState
*bs
)
1253 BDRVRawState
*s
= bs
->opaque
;
1261 return lseek(s
->fd
, 0, SEEK_END
);
1265 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
1268 BDRVRawState
*s
= bs
->opaque
;
1270 if (fstat(s
->fd
, &st
) < 0) {
1273 return (int64_t)st
.st_blocks
* 512;
1276 static int raw_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1280 int64_t total_size
= 0;
1282 strstart(filename
, "file:", &filename
);
1284 /* Read out options */
1286 qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0) / BDRV_SECTOR_SIZE
;
1288 fd
= qemu_open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
1292 error_setg_errno(errp
, -result
, "Could not create file");
1294 if (ftruncate(fd
, total_size
* BDRV_SECTOR_SIZE
) != 0) {
1296 error_setg_errno(errp
, -result
, "Could not resize file");
1298 if (qemu_close(fd
) != 0) {
1300 error_setg_errno(errp
, -result
, "Could not close the new file");
1306 static int64_t try_fiemap(BlockDriverState
*bs
, off_t start
, off_t
*data
,
1307 off_t
*hole
, int nb_sectors
, int *pnum
)
1309 #ifdef CONFIG_FIEMAP
1310 BDRVRawState
*s
= bs
->opaque
;
1311 int64_t ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1314 struct fiemap_extent fe
;
1317 if (s
->skip_fiemap
) {
1321 f
.fm
.fm_start
= start
;
1322 f
.fm
.fm_length
= (int64_t)nb_sectors
* BDRV_SECTOR_SIZE
;
1324 f
.fm
.fm_extent_count
= 1;
1325 f
.fm
.fm_reserved
= 0;
1326 if (ioctl(s
->fd
, FS_IOC_FIEMAP
, &f
) == -1) {
1327 s
->skip_fiemap
= true;
1331 if (f
.fm
.fm_mapped_extents
== 0) {
1332 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1333 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1335 off_t length
= lseek(s
->fd
, 0, SEEK_END
);
1336 *hole
= f
.fm
.fm_start
;
1337 *data
= MIN(f
.fm
.fm_start
+ f
.fm
.fm_length
, length
);
1339 *data
= f
.fe
.fe_logical
;
1340 *hole
= f
.fe
.fe_logical
+ f
.fe
.fe_length
;
1341 if (f
.fe
.fe_flags
& FIEMAP_EXTENT_UNWRITTEN
) {
1342 ret
|= BDRV_BLOCK_ZERO
;
1352 static int64_t try_seek_hole(BlockDriverState
*bs
, off_t start
, off_t
*data
,
1353 off_t
*hole
, int *pnum
)
1355 #if defined SEEK_HOLE && defined SEEK_DATA
1356 BDRVRawState
*s
= bs
->opaque
;
1358 *hole
= lseek(s
->fd
, start
, SEEK_HOLE
);
1360 /* -ENXIO indicates that sector_num was past the end of the file.
1361 * There is a virtual hole there. */
1362 assert(errno
!= -ENXIO
);
1367 if (*hole
> start
) {
1370 /* On a hole. We need another syscall to find its end. */
1371 *data
= lseek(s
->fd
, start
, SEEK_DATA
);
1373 *data
= lseek(s
->fd
, 0, SEEK_END
);
1377 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1384 * Returns true iff the specified sector is present in the disk image. Drivers
1385 * not implementing the functionality are assumed to not support backing files,
1386 * hence all their sectors are reported as allocated.
1388 * If 'sector_num' is beyond the end of the disk image the return value is 0
1389 * and 'pnum' is set to 0.
1391 * 'pnum' is set to the number of sectors (including and immediately following
1392 * the specified sector) that are known to be in the same
1393 * allocated/unallocated state.
1395 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1396 * beyond the end of the disk image it will be clamped.
1398 static int64_t coroutine_fn
raw_co_get_block_status(BlockDriverState
*bs
,
1400 int nb_sectors
, int *pnum
)
1402 off_t start
, data
= 0, hole
= 0;
1410 start
= sector_num
* BDRV_SECTOR_SIZE
;
1412 ret
= try_fiemap(bs
, start
, &data
, &hole
, nb_sectors
, pnum
);
1414 ret
= try_seek_hole(bs
, start
, &data
, &hole
, pnum
);
1416 /* Assume everything is allocated. */
1418 hole
= start
+ nb_sectors
* BDRV_SECTOR_SIZE
;
1419 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1423 if (data
<= start
) {
1424 /* On a data extent, compute sectors to the end of the extent. */
1425 *pnum
= MIN(nb_sectors
, (hole
- start
) / BDRV_SECTOR_SIZE
);
1427 /* On a hole, compute sectors to the beginning of the next extent. */
1428 *pnum
= MIN(nb_sectors
, (data
- start
) / BDRV_SECTOR_SIZE
);
1429 ret
&= ~BDRV_BLOCK_DATA
;
1430 ret
|= BDRV_BLOCK_ZERO
;
1436 static coroutine_fn BlockDriverAIOCB
*raw_aio_discard(BlockDriverState
*bs
,
1437 int64_t sector_num
, int nb_sectors
,
1438 BlockDriverCompletionFunc
*cb
, void *opaque
)
1440 BDRVRawState
*s
= bs
->opaque
;
1442 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1443 cb
, opaque
, QEMU_AIO_DISCARD
);
1446 static int coroutine_fn
raw_co_write_zeroes(
1447 BlockDriverState
*bs
, int64_t sector_num
,
1448 int nb_sectors
, BdrvRequestFlags flags
)
1450 BDRVRawState
*s
= bs
->opaque
;
1452 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1453 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1454 QEMU_AIO_WRITE_ZEROES
);
1455 } else if (s
->discard_zeroes
) {
1456 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1462 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1464 BDRVRawState
*s
= bs
->opaque
;
1466 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
1467 bdi
->can_write_zeroes_with_unmap
= s
->discard_zeroes
;
1471 static QemuOptsList raw_create_opts
= {
1472 .name
= "raw-create-opts",
1473 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
1476 .name
= BLOCK_OPT_SIZE
,
1477 .type
= QEMU_OPT_SIZE
,
1478 .help
= "Virtual disk size"
1480 { /* end of list */ }
1484 static BlockDriver bdrv_file
= {
1485 .format_name
= "file",
1486 .protocol_name
= "file",
1487 .instance_size
= sizeof(BDRVRawState
),
1488 .bdrv_needs_filename
= true,
1489 .bdrv_probe
= NULL
, /* no probe for protocols */
1490 .bdrv_parse_filename
= raw_parse_filename
,
1491 .bdrv_file_open
= raw_open
,
1492 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1493 .bdrv_reopen_commit
= raw_reopen_commit
,
1494 .bdrv_reopen_abort
= raw_reopen_abort
,
1495 .bdrv_close
= raw_close
,
1496 .bdrv_create
= raw_create
,
1497 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
1498 .bdrv_co_get_block_status
= raw_co_get_block_status
,
1499 .bdrv_co_write_zeroes
= raw_co_write_zeroes
,
1501 .bdrv_aio_readv
= raw_aio_readv
,
1502 .bdrv_aio_writev
= raw_aio_writev
,
1503 .bdrv_aio_flush
= raw_aio_flush
,
1504 .bdrv_aio_discard
= raw_aio_discard
,
1505 .bdrv_refresh_limits
= raw_refresh_limits
,
1507 .bdrv_truncate
= raw_truncate
,
1508 .bdrv_getlength
= raw_getlength
,
1509 .bdrv_get_info
= raw_get_info
,
1510 .bdrv_get_allocated_file_size
1511 = raw_get_allocated_file_size
,
1513 .bdrv_detach_aio_context
= raw_detach_aio_context
,
1514 .bdrv_attach_aio_context
= raw_attach_aio_context
,
1516 .create_opts
= &raw_create_opts
,
1519 /***********************************************/
1522 #if defined(__APPLE__) && defined(__MACH__)
1523 static kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
);
1524 static kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
);
1526 kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
)
1528 kern_return_t kernResult
;
1529 mach_port_t masterPort
;
1530 CFMutableDictionaryRef classesToMatch
;
1532 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
1533 if ( KERN_SUCCESS
!= kernResult
) {
1534 printf( "IOMasterPort returned %d\n", kernResult
);
1537 classesToMatch
= IOServiceMatching( kIOCDMediaClass
);
1538 if ( classesToMatch
== NULL
) {
1539 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1541 CFDictionarySetValue( classesToMatch
, CFSTR( kIOMediaEjectableKey
), kCFBooleanTrue
);
1543 kernResult
= IOServiceGetMatchingServices( masterPort
, classesToMatch
, mediaIterator
);
1544 if ( KERN_SUCCESS
!= kernResult
)
1546 printf( "IOServiceGetMatchingServices returned %d\n", kernResult
);
1552 kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
)
1554 io_object_t nextMedia
;
1555 kern_return_t kernResult
= KERN_FAILURE
;
1557 nextMedia
= IOIteratorNext( mediaIterator
);
1560 CFTypeRef bsdPathAsCFString
;
1561 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
1562 if ( bsdPathAsCFString
) {
1563 size_t devPathLength
;
1564 strcpy( bsdPath
, _PATH_DEV
);
1565 strcat( bsdPath
, "r" );
1566 devPathLength
= strlen( bsdPath
);
1567 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
1568 kernResult
= KERN_SUCCESS
;
1570 CFRelease( bsdPathAsCFString
);
1572 IOObjectRelease( nextMedia
);
1580 static int hdev_probe_device(const char *filename
)
1584 /* allow a dedicated CD-ROM driver to match with a higher priority */
1585 if (strstart(filename
, "/dev/cdrom", NULL
))
1588 if (stat(filename
, &st
) >= 0 &&
1589 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
1596 static int check_hdev_writable(BDRVRawState
*s
)
1598 #if defined(BLKROGET)
1599 /* Linux block devices can be configured "read-only" using blockdev(8).
1600 * This is independent of device node permissions and therefore open(2)
1601 * with O_RDWR succeeds. Actual writes fail with EPERM.
1603 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1604 * check for read-only block devices so that Linux block devices behave
1610 if (fstat(s
->fd
, &st
)) {
1614 if (!S_ISBLK(st
.st_mode
)) {
1618 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
1625 #endif /* defined(BLKROGET) */
1629 static void hdev_parse_filename(const char *filename
, QDict
*options
,
1632 /* The prefix is optional, just as for "file". */
1633 strstart(filename
, "host_device:", &filename
);
1635 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
1638 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1641 BDRVRawState
*s
= bs
->opaque
;
1642 Error
*local_err
= NULL
;
1644 const char *filename
= qdict_get_str(options
, "filename");
1646 #if defined(__APPLE__) && defined(__MACH__)
1647 if (strstart(filename
, "/dev/cdrom", NULL
)) {
1648 kern_return_t kernResult
;
1649 io_iterator_t mediaIterator
;
1650 char bsdPath
[ MAXPATHLEN
];
1653 kernResult
= FindEjectableCDMedia( &mediaIterator
);
1654 kernResult
= GetBSDPath( mediaIterator
, bsdPath
, sizeof( bsdPath
) );
1656 if ( bsdPath
[ 0 ] != '\0' ) {
1657 strcat(bsdPath
,"s0");
1658 /* some CDs don't have a partition 0 */
1659 fd
= qemu_open(bsdPath
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
1661 bsdPath
[strlen(bsdPath
)-1] = '1';
1666 qdict_put(options
, "filename", qstring_from_str(filename
));
1669 if ( mediaIterator
)
1670 IOObjectRelease( mediaIterator
);
1674 s
->type
= FTYPE_FILE
;
1675 #if defined(__linux__)
1677 char resolved_path
[ MAXPATHLEN
], *temp
;
1679 temp
= realpath(filename
, resolved_path
);
1680 if (temp
&& strstart(temp
, "/dev/sg", NULL
)) {
1686 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
1689 error_propagate(errp
, local_err
);
1694 if (flags
& BDRV_O_RDWR
) {
1695 ret
= check_hdev_writable(s
);
1698 error_setg_errno(errp
, -ret
, "The device is not writable");
1706 #if defined(__linux__)
1707 /* Note: we do not have a reliable method to detect if the floppy is
1708 present. The current method is to try to open the floppy at every
1709 I/O and to keep it opened during a few hundreds of ms. */
1710 static int fd_open(BlockDriverState
*bs
)
1712 BDRVRawState
*s
= bs
->opaque
;
1713 int last_media_present
;
1715 if (s
->type
!= FTYPE_FD
)
1717 last_media_present
= (s
->fd
>= 0);
1719 (get_clock() - s
->fd_open_time
) >= FD_OPEN_TIMEOUT
) {
1723 printf("Floppy closed\n");
1727 if (s
->fd_got_error
&&
1728 (get_clock() - s
->fd_error_time
) < FD_OPEN_TIMEOUT
) {
1730 printf("No floppy (open delayed)\n");
1734 s
->fd
= qemu_open(bs
->filename
, s
->open_flags
& ~O_NONBLOCK
);
1736 s
->fd_error_time
= get_clock();
1737 s
->fd_got_error
= 1;
1738 if (last_media_present
)
1739 s
->fd_media_changed
= 1;
1741 printf("No floppy\n");
1746 printf("Floppy opened\n");
1749 if (!last_media_present
)
1750 s
->fd_media_changed
= 1;
1751 s
->fd_open_time
= get_clock();
1752 s
->fd_got_error
= 0;
1756 static int hdev_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
1758 BDRVRawState
*s
= bs
->opaque
;
1760 return ioctl(s
->fd
, req
, buf
);
1763 static BlockDriverAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
1764 unsigned long int req
, void *buf
,
1765 BlockDriverCompletionFunc
*cb
, void *opaque
)
1767 BDRVRawState
*s
= bs
->opaque
;
1768 RawPosixAIOData
*acb
;
1771 if (fd_open(bs
) < 0)
1774 acb
= g_slice_new(RawPosixAIOData
);
1776 acb
->aio_type
= QEMU_AIO_IOCTL
;
1777 acb
->aio_fildes
= s
->fd
;
1778 acb
->aio_offset
= 0;
1779 acb
->aio_ioctl_buf
= buf
;
1780 acb
->aio_ioctl_cmd
= req
;
1781 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1782 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1785 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1786 static int fd_open(BlockDriverState
*bs
)
1788 BDRVRawState
*s
= bs
->opaque
;
1790 /* this is just to ensure s->fd is sane (its called by io ops) */
1795 #else /* !linux && !FreeBSD */
1797 static int fd_open(BlockDriverState
*bs
)
1802 #endif /* !linux && !FreeBSD */
1804 static coroutine_fn BlockDriverAIOCB
*hdev_aio_discard(BlockDriverState
*bs
,
1805 int64_t sector_num
, int nb_sectors
,
1806 BlockDriverCompletionFunc
*cb
, void *opaque
)
1808 BDRVRawState
*s
= bs
->opaque
;
1810 if (fd_open(bs
) < 0) {
1813 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1814 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1817 static coroutine_fn
int hdev_co_write_zeroes(BlockDriverState
*bs
,
1818 int64_t sector_num
, int nb_sectors
, BdrvRequestFlags flags
)
1820 BDRVRawState
*s
= bs
->opaque
;
1827 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1828 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1829 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
1830 } else if (s
->discard_zeroes
) {
1831 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1832 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1837 static int hdev_create(const char *filename
, QemuOpts
*opts
,
1842 struct stat stat_buf
;
1843 int64_t total_size
= 0;
1846 /* This function is used by all three protocol block drivers and therefore
1847 * any of these three prefixes may be given.
1848 * The return value has to be stored somewhere, otherwise this is an error
1849 * due to -Werror=unused-value. */
1851 strstart(filename
, "host_device:", &filename
) ||
1852 strstart(filename
, "host_cdrom:" , &filename
) ||
1853 strstart(filename
, "host_floppy:", &filename
);
1857 /* Read out options */
1859 qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0) / BDRV_SECTOR_SIZE
;
1861 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
1864 error_setg_errno(errp
, -ret
, "Could not open device");
1868 if (fstat(fd
, &stat_buf
) < 0) {
1870 error_setg_errno(errp
, -ret
, "Could not stat device");
1871 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
1873 "The given file is neither a block nor a character device");
1875 } else if (lseek(fd
, 0, SEEK_END
) < total_size
* BDRV_SECTOR_SIZE
) {
1876 error_setg(errp
, "Device is too small");
1884 static BlockDriver bdrv_host_device
= {
1885 .format_name
= "host_device",
1886 .protocol_name
= "host_device",
1887 .instance_size
= sizeof(BDRVRawState
),
1888 .bdrv_needs_filename
= true,
1889 .bdrv_probe_device
= hdev_probe_device
,
1890 .bdrv_parse_filename
= hdev_parse_filename
,
1891 .bdrv_file_open
= hdev_open
,
1892 .bdrv_close
= raw_close
,
1893 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1894 .bdrv_reopen_commit
= raw_reopen_commit
,
1895 .bdrv_reopen_abort
= raw_reopen_abort
,
1896 .bdrv_create
= hdev_create
,
1897 .create_opts
= &raw_create_opts
,
1898 .bdrv_co_write_zeroes
= hdev_co_write_zeroes
,
1900 .bdrv_aio_readv
= raw_aio_readv
,
1901 .bdrv_aio_writev
= raw_aio_writev
,
1902 .bdrv_aio_flush
= raw_aio_flush
,
1903 .bdrv_aio_discard
= hdev_aio_discard
,
1904 .bdrv_refresh_limits
= raw_refresh_limits
,
1906 .bdrv_truncate
= raw_truncate
,
1907 .bdrv_getlength
= raw_getlength
,
1908 .bdrv_get_info
= raw_get_info
,
1909 .bdrv_get_allocated_file_size
1910 = raw_get_allocated_file_size
,
1912 .bdrv_detach_aio_context
= raw_detach_aio_context
,
1913 .bdrv_attach_aio_context
= raw_attach_aio_context
,
1915 /* generic scsi device */
1917 .bdrv_ioctl
= hdev_ioctl
,
1918 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
1923 static void floppy_parse_filename(const char *filename
, QDict
*options
,
1926 /* The prefix is optional, just as for "file". */
1927 strstart(filename
, "host_floppy:", &filename
);
1929 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
1932 static int floppy_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1935 BDRVRawState
*s
= bs
->opaque
;
1936 Error
*local_err
= NULL
;
1941 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1942 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
1945 error_propagate(errp
, local_err
);
1950 /* close fd so that we can reopen it as needed */
1953 s
->fd_media_changed
= 1;
1958 static int floppy_probe_device(const char *filename
)
1962 struct floppy_struct fdparam
;
1965 if (strstart(filename
, "/dev/fd", NULL
) &&
1966 !strstart(filename
, "/dev/fdset/", NULL
)) {
1970 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
1974 ret
= fstat(fd
, &st
);
1975 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
1979 /* Attempt to detect via a floppy specific ioctl */
1980 ret
= ioctl(fd
, FDGETPRM
, &fdparam
);
1991 static int floppy_is_inserted(BlockDriverState
*bs
)
1993 return fd_open(bs
) >= 0;
1996 static int floppy_media_changed(BlockDriverState
*bs
)
1998 BDRVRawState
*s
= bs
->opaque
;
2002 * XXX: we do not have a true media changed indication.
2003 * It does not work if the floppy is changed without trying to read it.
2006 ret
= s
->fd_media_changed
;
2007 s
->fd_media_changed
= 0;
2009 printf("Floppy changed=%d\n", ret
);
2014 static void floppy_eject(BlockDriverState
*bs
, bool eject_flag
)
2016 BDRVRawState
*s
= bs
->opaque
;
2023 fd
= qemu_open(bs
->filename
, s
->open_flags
| O_NONBLOCK
);
2025 if (ioctl(fd
, FDEJECT
, 0) < 0)
2031 static BlockDriver bdrv_host_floppy
= {
2032 .format_name
= "host_floppy",
2033 .protocol_name
= "host_floppy",
2034 .instance_size
= sizeof(BDRVRawState
),
2035 .bdrv_needs_filename
= true,
2036 .bdrv_probe_device
= floppy_probe_device
,
2037 .bdrv_parse_filename
= floppy_parse_filename
,
2038 .bdrv_file_open
= floppy_open
,
2039 .bdrv_close
= raw_close
,
2040 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2041 .bdrv_reopen_commit
= raw_reopen_commit
,
2042 .bdrv_reopen_abort
= raw_reopen_abort
,
2043 .bdrv_create
= hdev_create
,
2044 .create_opts
= &raw_create_opts
,
2046 .bdrv_aio_readv
= raw_aio_readv
,
2047 .bdrv_aio_writev
= raw_aio_writev
,
2048 .bdrv_aio_flush
= raw_aio_flush
,
2049 .bdrv_refresh_limits
= raw_refresh_limits
,
2051 .bdrv_truncate
= raw_truncate
,
2052 .bdrv_getlength
= raw_getlength
,
2053 .has_variable_length
= true,
2054 .bdrv_get_allocated_file_size
2055 = raw_get_allocated_file_size
,
2057 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2058 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2060 /* removable device support */
2061 .bdrv_is_inserted
= floppy_is_inserted
,
2062 .bdrv_media_changed
= floppy_media_changed
,
2063 .bdrv_eject
= floppy_eject
,
2067 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2068 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2071 /* The prefix is optional, just as for "file". */
2072 strstart(filename
, "host_cdrom:", &filename
);
2074 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2079 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2082 BDRVRawState
*s
= bs
->opaque
;
2083 Error
*local_err
= NULL
;
2088 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2089 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2091 error_propagate(errp
, local_err
);
2096 static int cdrom_probe_device(const char *filename
)
2102 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2106 ret
= fstat(fd
, &st
);
2107 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2111 /* Attempt to detect via a CDROM specific ioctl */
2112 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2122 static int cdrom_is_inserted(BlockDriverState
*bs
)
2124 BDRVRawState
*s
= bs
->opaque
;
2127 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2128 if (ret
== CDS_DISC_OK
)
2133 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2135 BDRVRawState
*s
= bs
->opaque
;
2138 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2139 perror("CDROMEJECT");
2141 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2142 perror("CDROMEJECT");
2146 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2148 BDRVRawState
*s
= bs
->opaque
;
2150 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2152 * Note: an error can happen if the distribution automatically
2155 /* perror("CDROM_LOCKDOOR"); */
2159 static BlockDriver bdrv_host_cdrom
= {
2160 .format_name
= "host_cdrom",
2161 .protocol_name
= "host_cdrom",
2162 .instance_size
= sizeof(BDRVRawState
),
2163 .bdrv_needs_filename
= true,
2164 .bdrv_probe_device
= cdrom_probe_device
,
2165 .bdrv_parse_filename
= cdrom_parse_filename
,
2166 .bdrv_file_open
= cdrom_open
,
2167 .bdrv_close
= raw_close
,
2168 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2169 .bdrv_reopen_commit
= raw_reopen_commit
,
2170 .bdrv_reopen_abort
= raw_reopen_abort
,
2171 .bdrv_create
= hdev_create
,
2172 .create_opts
= &raw_create_opts
,
2174 .bdrv_aio_readv
= raw_aio_readv
,
2175 .bdrv_aio_writev
= raw_aio_writev
,
2176 .bdrv_aio_flush
= raw_aio_flush
,
2177 .bdrv_refresh_limits
= raw_refresh_limits
,
2179 .bdrv_truncate
= raw_truncate
,
2180 .bdrv_getlength
= raw_getlength
,
2181 .has_variable_length
= true,
2182 .bdrv_get_allocated_file_size
2183 = raw_get_allocated_file_size
,
2185 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2186 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2188 /* removable device support */
2189 .bdrv_is_inserted
= cdrom_is_inserted
,
2190 .bdrv_eject
= cdrom_eject
,
2191 .bdrv_lock_medium
= cdrom_lock_medium
,
2193 /* generic scsi device */
2194 .bdrv_ioctl
= hdev_ioctl
,
2195 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2197 #endif /* __linux__ */
2199 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2200 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2203 BDRVRawState
*s
= bs
->opaque
;
2204 Error
*local_err
= NULL
;
2209 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2212 error_propagate(errp
, local_err
);
2217 /* make sure the door isn't locked at this time */
2218 ioctl(s
->fd
, CDIOCALLOW
);
2222 static int cdrom_probe_device(const char *filename
)
2224 if (strstart(filename
, "/dev/cd", NULL
) ||
2225 strstart(filename
, "/dev/acd", NULL
))
2230 static int cdrom_reopen(BlockDriverState
*bs
)
2232 BDRVRawState
*s
= bs
->opaque
;
2236 * Force reread of possibly changed/newly loaded disc,
2237 * FreeBSD seems to not notice sometimes...
2241 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
2248 /* make sure the door isn't locked at this time */
2249 ioctl(s
->fd
, CDIOCALLOW
);
2253 static int cdrom_is_inserted(BlockDriverState
*bs
)
2255 return raw_getlength(bs
) > 0;
2258 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2260 BDRVRawState
*s
= bs
->opaque
;
2265 (void) ioctl(s
->fd
, CDIOCALLOW
);
2268 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
2269 perror("CDIOCEJECT");
2271 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
2272 perror("CDIOCCLOSE");
2278 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2280 BDRVRawState
*s
= bs
->opaque
;
2284 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
2286 * Note: an error can happen if the distribution automatically
2289 /* perror("CDROM_LOCKDOOR"); */
2293 static BlockDriver bdrv_host_cdrom
= {
2294 .format_name
= "host_cdrom",
2295 .protocol_name
= "host_cdrom",
2296 .instance_size
= sizeof(BDRVRawState
),
2297 .bdrv_needs_filename
= true,
2298 .bdrv_probe_device
= cdrom_probe_device
,
2299 .bdrv_parse_filename
= cdrom_parse_filename
,
2300 .bdrv_file_open
= cdrom_open
,
2301 .bdrv_close
= raw_close
,
2302 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2303 .bdrv_reopen_commit
= raw_reopen_commit
,
2304 .bdrv_reopen_abort
= raw_reopen_abort
,
2305 .bdrv_create
= hdev_create
,
2306 .create_opts
= &raw_create_opts
,
2308 .bdrv_aio_readv
= raw_aio_readv
,
2309 .bdrv_aio_writev
= raw_aio_writev
,
2310 .bdrv_aio_flush
= raw_aio_flush
,
2311 .bdrv_refresh_limits
= raw_refresh_limits
,
2313 .bdrv_truncate
= raw_truncate
,
2314 .bdrv_getlength
= raw_getlength
,
2315 .has_variable_length
= true,
2316 .bdrv_get_allocated_file_size
2317 = raw_get_allocated_file_size
,
2319 .bdrv_detach_aio_context
= raw_detach_aio_context
,
2320 .bdrv_attach_aio_context
= raw_attach_aio_context
,
2322 /* removable device support */
2323 .bdrv_is_inserted
= cdrom_is_inserted
,
2324 .bdrv_eject
= cdrom_eject
,
2325 .bdrv_lock_medium
= cdrom_lock_medium
,
2327 #endif /* __FreeBSD__ */
2329 static void bdrv_file_init(void)
2332 * Register all the drivers. Note that order is important, the driver
2333 * registered last will get probed first.
2335 bdrv_register(&bdrv_file
);
2336 bdrv_register(&bdrv_host_device
);
2338 bdrv_register(&bdrv_host_floppy
);
2339 bdrv_register(&bdrv_host_cdrom
);
2341 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2342 bdrv_register(&bdrv_host_cdrom
);
2346 block_init(bdrv_file_init
);