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
= NULL
;
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
)) {
449 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
456 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
459 BDRVRawState
*s
= bs
->opaque
;
460 Error
*local_err
= NULL
;
463 s
->type
= FTYPE_FILE
;
464 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
466 error_propagate(errp
, local_err
);
471 static int raw_reopen_prepare(BDRVReopenState
*state
,
472 BlockReopenQueue
*queue
, Error
**errp
)
475 BDRVRawReopenState
*raw_s
;
478 assert(state
!= NULL
);
479 assert(state
->bs
!= NULL
);
481 s
= state
->bs
->opaque
;
483 state
->opaque
= g_malloc0(sizeof(BDRVRawReopenState
));
484 raw_s
= state
->opaque
;
486 #ifdef CONFIG_LINUX_AIO
487 raw_s
->use_aio
= s
->use_aio
;
489 /* we can use s->aio_ctx instead of a copy, because the use_aio flag is
490 * valid in the 'false' condition even if aio_ctx is set, and raw_set_aio()
491 * won't override aio_ctx if aio_ctx is non-NULL */
492 if (raw_set_aio(&s
->aio_ctx
, &raw_s
->use_aio
, state
->flags
)) {
493 error_setg(errp
, "Could not set AIO state");
498 if (s
->type
== FTYPE_FD
|| s
->type
== FTYPE_CD
) {
499 raw_s
->open_flags
|= O_NONBLOCK
;
502 raw_parse_flags(state
->flags
, &raw_s
->open_flags
);
506 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
508 fcntl_flags
|= O_NOATIME
;
512 /* Not all operating systems have O_ASYNC, and those that don't
513 * will not let us track the state into raw_s->open_flags (typically
514 * you achieve the same effect with an ioctl, for example I_SETSIG
515 * on Solaris). But we do not use O_ASYNC, so that's fine.
517 assert((s
->open_flags
& O_ASYNC
) == 0);
520 if ((raw_s
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
521 /* dup the original fd */
522 /* TODO: use qemu fcntl wrapper */
523 #ifdef F_DUPFD_CLOEXEC
524 raw_s
->fd
= fcntl(s
->fd
, F_DUPFD_CLOEXEC
, 0);
526 raw_s
->fd
= dup(s
->fd
);
527 if (raw_s
->fd
!= -1) {
528 qemu_set_cloexec(raw_s
->fd
);
531 if (raw_s
->fd
>= 0) {
532 ret
= fcntl_setfl(raw_s
->fd
, raw_s
->open_flags
);
534 qemu_close(raw_s
->fd
);
540 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
541 if (raw_s
->fd
== -1) {
542 assert(!(raw_s
->open_flags
& O_CREAT
));
543 raw_s
->fd
= qemu_open(state
->bs
->filename
, raw_s
->open_flags
);
544 if (raw_s
->fd
== -1) {
545 error_setg_errno(errp
, errno
, "Could not reopen file");
552 static void raw_reopen_commit(BDRVReopenState
*state
)
554 BDRVRawReopenState
*raw_s
= state
->opaque
;
555 BDRVRawState
*s
= state
->bs
->opaque
;
557 s
->open_flags
= raw_s
->open_flags
;
561 #ifdef CONFIG_LINUX_AIO
562 s
->use_aio
= raw_s
->use_aio
;
565 g_free(state
->opaque
);
566 state
->opaque
= NULL
;
570 static void raw_reopen_abort(BDRVReopenState
*state
)
572 BDRVRawReopenState
*raw_s
= state
->opaque
;
574 /* nothing to do if NULL, we didn't get far enough */
579 if (raw_s
->fd
>= 0) {
580 qemu_close(raw_s
->fd
);
583 g_free(state
->opaque
);
584 state
->opaque
= NULL
;
587 static int raw_refresh_limits(BlockDriverState
*bs
)
589 BDRVRawState
*s
= bs
->opaque
;
591 raw_probe_alignment(bs
);
592 bs
->bl
.opt_mem_alignment
= s
->buf_align
;
597 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
601 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
609 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
613 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
622 static bool preadv_present
= true;
625 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
627 return preadv(fd
, iov
, nr_iov
, offset
);
631 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
633 return pwritev(fd
, iov
, nr_iov
, offset
);
638 static bool preadv_present
= false;
641 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
647 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
654 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
659 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
660 len
= qemu_pwritev(aiocb
->aio_fildes
,
665 len
= qemu_preadv(aiocb
->aio_fildes
,
669 } while (len
== -1 && errno
== EINTR
);
678 * Read/writes the data to/from a given linear buffer.
680 * Returns the number of bytes handles or -errno in case of an error. Short
681 * reads are only returned if the end of the file is reached.
683 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
688 while (offset
< aiocb
->aio_nbytes
) {
689 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
690 len
= pwrite(aiocb
->aio_fildes
,
691 (const char *)buf
+ offset
,
692 aiocb
->aio_nbytes
- offset
,
693 aiocb
->aio_offset
+ offset
);
695 len
= pread(aiocb
->aio_fildes
,
697 aiocb
->aio_nbytes
- offset
,
698 aiocb
->aio_offset
+ offset
);
700 if (len
== -1 && errno
== EINTR
) {
702 } else if (len
== -1) {
705 } else if (len
== 0) {
714 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
719 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
721 * If there is just a single buffer, and it is properly aligned
722 * we can just use plain pread/pwrite without any problems.
724 if (aiocb
->aio_niov
== 1) {
725 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
728 * We have more than one iovec, and all are properly aligned.
730 * Try preadv/pwritev first and fall back to linearizing the
731 * buffer if it's not supported.
733 if (preadv_present
) {
734 nbytes
= handle_aiocb_rw_vector(aiocb
);
735 if (nbytes
== aiocb
->aio_nbytes
||
736 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
739 preadv_present
= false;
743 * XXX(hch): short read/write. no easy way to handle the reminder
744 * using these interfaces. For now retry using plain
750 * Ok, we have to do it the hard way, copy all segments into
751 * a single aligned buffer.
753 buf
= qemu_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
754 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
758 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
759 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
760 p
+= aiocb
->aio_iov
[i
].iov_len
;
764 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
765 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
767 size_t count
= aiocb
->aio_nbytes
, copy
;
770 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
772 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
773 copy
= aiocb
->aio_iov
[i
].iov_len
;
775 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
786 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
788 struct xfs_flock64 fl
;
790 memset(&fl
, 0, sizeof(fl
));
791 fl
.l_whence
= SEEK_SET
;
795 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
796 DEBUG_BLOCK_PRINT("cannot write zero range (%s)\n", strerror(errno
));
803 static int xfs_discard(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
805 struct xfs_flock64 fl
;
807 memset(&fl
, 0, sizeof(fl
));
808 fl
.l_whence
= SEEK_SET
;
812 if (xfsctl(NULL
, s
->fd
, XFS_IOC_UNRESVSP64
, &fl
) < 0) {
813 DEBUG_BLOCK_PRINT("cannot punch hole (%s)\n", strerror(errno
));
821 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
823 int ret
= -EOPNOTSUPP
;
824 BDRVRawState
*s
= aiocb
->bs
->opaque
;
826 if (s
->has_write_zeroes
== 0) {
830 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
833 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
834 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
837 } while (errno
== EINTR
);
844 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
849 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
851 s
->has_write_zeroes
= false;
857 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
859 int ret
= -EOPNOTSUPP
;
860 BDRVRawState
*s
= aiocb
->bs
->opaque
;
862 if (!s
->has_discard
) {
866 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
869 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
870 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
873 } while (errno
== EINTR
);
880 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
884 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
886 if (fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
887 aiocb
->aio_offset
, aiocb
->aio_nbytes
) == 0) {
890 } while (errno
== EINTR
);
896 if (ret
== -ENODEV
|| ret
== -ENOSYS
|| ret
== -EOPNOTSUPP
||
898 s
->has_discard
= false;
904 static int aio_worker(void *arg
)
906 RawPosixAIOData
*aiocb
= arg
;
909 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
911 ret
= handle_aiocb_rw(aiocb
);
912 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
&& aiocb
->bs
->growable
) {
913 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
914 0, aiocb
->aio_nbytes
- ret
);
916 ret
= aiocb
->aio_nbytes
;
918 if (ret
== aiocb
->aio_nbytes
) {
920 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
925 ret
= handle_aiocb_rw(aiocb
);
926 if (ret
== aiocb
->aio_nbytes
) {
928 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
933 ret
= handle_aiocb_flush(aiocb
);
936 ret
= handle_aiocb_ioctl(aiocb
);
938 case QEMU_AIO_DISCARD
:
939 ret
= handle_aiocb_discard(aiocb
);
941 case QEMU_AIO_WRITE_ZEROES
:
942 ret
= handle_aiocb_write_zeroes(aiocb
);
945 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
950 g_slice_free(RawPosixAIOData
, aiocb
);
954 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
955 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
958 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
962 acb
->aio_type
= type
;
963 acb
->aio_fildes
= fd
;
966 acb
->aio_iov
= qiov
->iov
;
967 acb
->aio_niov
= qiov
->niov
;
969 acb
->aio_nbytes
= nb_sectors
* 512;
970 acb
->aio_offset
= sector_num
* 512;
972 trace_paio_submit_co(sector_num
, nb_sectors
, type
);
973 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
974 return thread_pool_submit_co(pool
, aio_worker
, acb
);
977 static BlockDriverAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
978 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
979 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
981 RawPosixAIOData
*acb
= g_slice_new(RawPosixAIOData
);
985 acb
->aio_type
= type
;
986 acb
->aio_fildes
= fd
;
989 acb
->aio_iov
= qiov
->iov
;
990 acb
->aio_niov
= qiov
->niov
;
992 acb
->aio_nbytes
= nb_sectors
* 512;
993 acb
->aio_offset
= sector_num
* 512;
995 trace_paio_submit(acb
, opaque
, sector_num
, nb_sectors
, type
);
996 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
997 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1000 static BlockDriverAIOCB
*raw_aio_submit(BlockDriverState
*bs
,
1001 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1002 BlockDriverCompletionFunc
*cb
, void *opaque
, int type
)
1004 BDRVRawState
*s
= bs
->opaque
;
1006 if (fd_open(bs
) < 0)
1010 * If O_DIRECT is used the buffer needs to be aligned on a sector
1011 * boundary. Check if this is the case or tell the low-level
1012 * driver that it needs to copy the buffer.
1014 if ((bs
->open_flags
& BDRV_O_NOCACHE
)) {
1015 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1016 type
|= QEMU_AIO_MISALIGNED
;
1017 #ifdef CONFIG_LINUX_AIO
1018 } else if (s
->use_aio
) {
1019 return laio_submit(bs
, s
->aio_ctx
, s
->fd
, sector_num
, qiov
,
1020 nb_sectors
, cb
, opaque
, type
);
1025 return paio_submit(bs
, s
->fd
, sector_num
, qiov
, nb_sectors
,
1029 static BlockDriverAIOCB
*raw_aio_readv(BlockDriverState
*bs
,
1030 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1031 BlockDriverCompletionFunc
*cb
, void *opaque
)
1033 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1034 cb
, opaque
, QEMU_AIO_READ
);
1037 static BlockDriverAIOCB
*raw_aio_writev(BlockDriverState
*bs
,
1038 int64_t sector_num
, QEMUIOVector
*qiov
, int nb_sectors
,
1039 BlockDriverCompletionFunc
*cb
, void *opaque
)
1041 return raw_aio_submit(bs
, sector_num
, qiov
, nb_sectors
,
1042 cb
, opaque
, QEMU_AIO_WRITE
);
1045 static BlockDriverAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1046 BlockDriverCompletionFunc
*cb
, void *opaque
)
1048 BDRVRawState
*s
= bs
->opaque
;
1050 if (fd_open(bs
) < 0)
1053 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1056 static void raw_close(BlockDriverState
*bs
)
1058 BDRVRawState
*s
= bs
->opaque
;
1065 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
)
1067 BDRVRawState
*s
= bs
->opaque
;
1070 if (fstat(s
->fd
, &st
)) {
1074 if (S_ISREG(st
.st_mode
)) {
1075 if (ftruncate(s
->fd
, offset
) < 0) {
1078 } else if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1079 if (offset
> raw_getlength(bs
)) {
1090 static int64_t raw_getlength(BlockDriverState
*bs
)
1092 BDRVRawState
*s
= bs
->opaque
;
1098 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1099 struct disklabel dl
;
1101 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1103 return (uint64_t)dl
.d_secsize
*
1104 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1108 #elif defined(__NetBSD__)
1109 static int64_t raw_getlength(BlockDriverState
*bs
)
1111 BDRVRawState
*s
= bs
->opaque
;
1117 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1118 struct dkwedge_info dkw
;
1120 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1121 return dkw
.dkw_size
* 512;
1123 struct disklabel dl
;
1125 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1127 return (uint64_t)dl
.d_secsize
*
1128 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1133 #elif defined(__sun__)
1134 static int64_t raw_getlength(BlockDriverState
*bs
)
1136 BDRVRawState
*s
= bs
->opaque
;
1137 struct dk_minfo minfo
;
1146 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1148 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1150 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1154 * There are reports that lseek on some devices fails, but
1155 * irc discussion said that contingency on contingency was overkill.
1157 return lseek(s
->fd
, 0, SEEK_END
);
1159 #elif defined(CONFIG_BSD)
1160 static int64_t raw_getlength(BlockDriverState
*bs
)
1162 BDRVRawState
*s
= bs
->opaque
;
1166 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1175 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1178 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1179 #ifdef DIOCGMEDIASIZE
1180 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1181 #elif defined(DIOCGPART)
1184 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1185 size
= pi
.media_size
;
1191 #if defined(__APPLE__) && defined(__MACH__)
1192 size
= LONG_LONG_MAX
;
1194 size
= lseek(fd
, 0LL, SEEK_END
);
1196 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1199 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1200 if (size
== 2048LL * (unsigned)-1)
1202 /* XXX no disc? maybe we need to reopen... */
1203 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1210 size
= lseek(fd
, 0, SEEK_END
);
1215 static int64_t raw_getlength(BlockDriverState
*bs
)
1217 BDRVRawState
*s
= bs
->opaque
;
1225 return lseek(s
->fd
, 0, SEEK_END
);
1229 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
1232 BDRVRawState
*s
= bs
->opaque
;
1234 if (fstat(s
->fd
, &st
) < 0) {
1237 return (int64_t)st
.st_blocks
* 512;
1240 static int raw_create(const char *filename
, QEMUOptionParameter
*options
,
1245 int64_t total_size
= 0;
1247 strstart(filename
, "file:", &filename
);
1249 /* Read out options */
1250 while (options
&& options
->name
) {
1251 if (!strcmp(options
->name
, BLOCK_OPT_SIZE
)) {
1252 total_size
= options
->value
.n
/ BDRV_SECTOR_SIZE
;
1257 fd
= qemu_open(filename
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
,
1261 error_setg_errno(errp
, -result
, "Could not create file");
1263 if (ftruncate(fd
, total_size
* BDRV_SECTOR_SIZE
) != 0) {
1265 error_setg_errno(errp
, -result
, "Could not resize file");
1267 if (qemu_close(fd
) != 0) {
1269 error_setg_errno(errp
, -result
, "Could not close the new file");
1276 * Returns true iff the specified sector is present in the disk image. Drivers
1277 * not implementing the functionality are assumed to not support backing files,
1278 * hence all their sectors are reported as allocated.
1280 * If 'sector_num' is beyond the end of the disk image the return value is 0
1281 * and 'pnum' is set to 0.
1283 * 'pnum' is set to the number of sectors (including and immediately following
1284 * the specified sector) that are known to be in the same
1285 * allocated/unallocated state.
1287 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1288 * beyond the end of the disk image it will be clamped.
1290 static int64_t coroutine_fn
raw_co_get_block_status(BlockDriverState
*bs
,
1292 int nb_sectors
, int *pnum
)
1294 off_t start
, data
, hole
;
1302 start
= sector_num
* BDRV_SECTOR_SIZE
;
1303 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
| start
;
1305 #ifdef CONFIG_FIEMAP
1307 BDRVRawState
*s
= bs
->opaque
;
1310 struct fiemap_extent fe
;
1313 f
.fm
.fm_start
= start
;
1314 f
.fm
.fm_length
= (int64_t)nb_sectors
* BDRV_SECTOR_SIZE
;
1316 f
.fm
.fm_extent_count
= 1;
1317 f
.fm
.fm_reserved
= 0;
1318 if (ioctl(s
->fd
, FS_IOC_FIEMAP
, &f
) == -1) {
1319 /* Assume everything is allocated. */
1324 if (f
.fm
.fm_mapped_extents
== 0) {
1325 /* No extents found, data is beyond f.fm.fm_start + f.fm.fm_length.
1326 * f.fm.fm_start + f.fm.fm_length must be clamped to the file size!
1328 off_t length
= lseek(s
->fd
, 0, SEEK_END
);
1329 hole
= f
.fm
.fm_start
;
1330 data
= MIN(f
.fm
.fm_start
+ f
.fm
.fm_length
, length
);
1332 data
= f
.fe
.fe_logical
;
1333 hole
= f
.fe
.fe_logical
+ f
.fe
.fe_length
;
1334 if (f
.fe
.fe_flags
& FIEMAP_EXTENT_UNWRITTEN
) {
1335 ret
|= BDRV_BLOCK_ZERO
;
1339 #elif defined SEEK_HOLE && defined SEEK_DATA
1341 BDRVRawState
*s
= bs
->opaque
;
1343 hole
= lseek(s
->fd
, start
, SEEK_HOLE
);
1345 /* -ENXIO indicates that sector_num was past the end of the file.
1346 * There is a virtual hole there. */
1347 assert(errno
!= -ENXIO
);
1349 /* Most likely EINVAL. Assume everything is allocated. */
1357 /* On a hole. We need another syscall to find its end. */
1358 data
= lseek(s
->fd
, start
, SEEK_DATA
);
1360 data
= lseek(s
->fd
, 0, SEEK_END
);
1365 hole
= start
+ nb_sectors
* BDRV_SECTOR_SIZE
;
1368 if (data
<= start
) {
1369 /* On a data extent, compute sectors to the end of the extent. */
1370 *pnum
= MIN(nb_sectors
, (hole
- start
) / BDRV_SECTOR_SIZE
);
1372 /* On a hole, compute sectors to the beginning of the next extent. */
1373 *pnum
= MIN(nb_sectors
, (data
- start
) / BDRV_SECTOR_SIZE
);
1374 ret
&= ~BDRV_BLOCK_DATA
;
1375 ret
|= BDRV_BLOCK_ZERO
;
1381 static coroutine_fn BlockDriverAIOCB
*raw_aio_discard(BlockDriverState
*bs
,
1382 int64_t sector_num
, int nb_sectors
,
1383 BlockDriverCompletionFunc
*cb
, void *opaque
)
1385 BDRVRawState
*s
= bs
->opaque
;
1387 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1388 cb
, opaque
, QEMU_AIO_DISCARD
);
1391 static int coroutine_fn
raw_co_write_zeroes(
1392 BlockDriverState
*bs
, int64_t sector_num
,
1393 int nb_sectors
, BdrvRequestFlags flags
)
1395 BDRVRawState
*s
= bs
->opaque
;
1397 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1398 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1399 QEMU_AIO_WRITE_ZEROES
);
1400 } else if (s
->discard_zeroes
) {
1401 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1407 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
1409 BDRVRawState
*s
= bs
->opaque
;
1411 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
1412 bdi
->can_write_zeroes_with_unmap
= s
->discard_zeroes
;
1416 static QEMUOptionParameter raw_create_options
[] = {
1418 .name
= BLOCK_OPT_SIZE
,
1420 .help
= "Virtual disk size"
1425 static BlockDriver bdrv_file
= {
1426 .format_name
= "file",
1427 .protocol_name
= "file",
1428 .instance_size
= sizeof(BDRVRawState
),
1429 .bdrv_needs_filename
= true,
1430 .bdrv_probe
= NULL
, /* no probe for protocols */
1431 .bdrv_parse_filename
= raw_parse_filename
,
1432 .bdrv_file_open
= raw_open
,
1433 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1434 .bdrv_reopen_commit
= raw_reopen_commit
,
1435 .bdrv_reopen_abort
= raw_reopen_abort
,
1436 .bdrv_close
= raw_close
,
1437 .bdrv_create
= raw_create
,
1438 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
1439 .bdrv_co_get_block_status
= raw_co_get_block_status
,
1440 .bdrv_co_write_zeroes
= raw_co_write_zeroes
,
1442 .bdrv_aio_readv
= raw_aio_readv
,
1443 .bdrv_aio_writev
= raw_aio_writev
,
1444 .bdrv_aio_flush
= raw_aio_flush
,
1445 .bdrv_aio_discard
= raw_aio_discard
,
1446 .bdrv_refresh_limits
= raw_refresh_limits
,
1448 .bdrv_truncate
= raw_truncate
,
1449 .bdrv_getlength
= raw_getlength
,
1450 .bdrv_get_info
= raw_get_info
,
1451 .bdrv_get_allocated_file_size
1452 = raw_get_allocated_file_size
,
1454 .create_options
= raw_create_options
,
1457 /***********************************************/
1460 #if defined(__APPLE__) && defined(__MACH__)
1461 static kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
);
1462 static kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
);
1464 kern_return_t
FindEjectableCDMedia( io_iterator_t
*mediaIterator
)
1466 kern_return_t kernResult
;
1467 mach_port_t masterPort
;
1468 CFMutableDictionaryRef classesToMatch
;
1470 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
1471 if ( KERN_SUCCESS
!= kernResult
) {
1472 printf( "IOMasterPort returned %d\n", kernResult
);
1475 classesToMatch
= IOServiceMatching( kIOCDMediaClass
);
1476 if ( classesToMatch
== NULL
) {
1477 printf( "IOServiceMatching returned a NULL dictionary.\n" );
1479 CFDictionarySetValue( classesToMatch
, CFSTR( kIOMediaEjectableKey
), kCFBooleanTrue
);
1481 kernResult
= IOServiceGetMatchingServices( masterPort
, classesToMatch
, mediaIterator
);
1482 if ( KERN_SUCCESS
!= kernResult
)
1484 printf( "IOServiceGetMatchingServices returned %d\n", kernResult
);
1490 kern_return_t
GetBSDPath( io_iterator_t mediaIterator
, char *bsdPath
, CFIndex maxPathSize
)
1492 io_object_t nextMedia
;
1493 kern_return_t kernResult
= KERN_FAILURE
;
1495 nextMedia
= IOIteratorNext( mediaIterator
);
1498 CFTypeRef bsdPathAsCFString
;
1499 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
1500 if ( bsdPathAsCFString
) {
1501 size_t devPathLength
;
1502 strcpy( bsdPath
, _PATH_DEV
);
1503 strcat( bsdPath
, "r" );
1504 devPathLength
= strlen( bsdPath
);
1505 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
1506 kernResult
= KERN_SUCCESS
;
1508 CFRelease( bsdPathAsCFString
);
1510 IOObjectRelease( nextMedia
);
1518 static int hdev_probe_device(const char *filename
)
1522 /* allow a dedicated CD-ROM driver to match with a higher priority */
1523 if (strstart(filename
, "/dev/cdrom", NULL
))
1526 if (stat(filename
, &st
) >= 0 &&
1527 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
1534 static int check_hdev_writable(BDRVRawState
*s
)
1536 #if defined(BLKROGET)
1537 /* Linux block devices can be configured "read-only" using blockdev(8).
1538 * This is independent of device node permissions and therefore open(2)
1539 * with O_RDWR succeeds. Actual writes fail with EPERM.
1541 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
1542 * check for read-only block devices so that Linux block devices behave
1548 if (fstat(s
->fd
, &st
)) {
1552 if (!S_ISBLK(st
.st_mode
)) {
1556 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
1563 #endif /* defined(BLKROGET) */
1567 static void hdev_parse_filename(const char *filename
, QDict
*options
,
1570 /* The prefix is optional, just as for "file". */
1571 strstart(filename
, "host_device:", &filename
);
1573 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
1576 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1579 BDRVRawState
*s
= bs
->opaque
;
1580 Error
*local_err
= NULL
;
1582 const char *filename
= qdict_get_str(options
, "filename");
1584 #if defined(__APPLE__) && defined(__MACH__)
1585 if (strstart(filename
, "/dev/cdrom", NULL
)) {
1586 kern_return_t kernResult
;
1587 io_iterator_t mediaIterator
;
1588 char bsdPath
[ MAXPATHLEN
];
1591 kernResult
= FindEjectableCDMedia( &mediaIterator
);
1592 kernResult
= GetBSDPath( mediaIterator
, bsdPath
, sizeof( bsdPath
) );
1594 if ( bsdPath
[ 0 ] != '\0' ) {
1595 strcat(bsdPath
,"s0");
1596 /* some CDs don't have a partition 0 */
1597 fd
= qemu_open(bsdPath
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
1599 bsdPath
[strlen(bsdPath
)-1] = '1';
1604 qdict_put(options
, "filename", qstring_from_str(filename
));
1607 if ( mediaIterator
)
1608 IOObjectRelease( mediaIterator
);
1612 s
->type
= FTYPE_FILE
;
1613 #if defined(__linux__)
1615 char resolved_path
[ MAXPATHLEN
], *temp
;
1617 temp
= realpath(filename
, resolved_path
);
1618 if (temp
&& strstart(temp
, "/dev/sg", NULL
)) {
1624 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
1627 error_propagate(errp
, local_err
);
1632 if (flags
& BDRV_O_RDWR
) {
1633 ret
= check_hdev_writable(s
);
1636 error_setg_errno(errp
, -ret
, "The device is not writable");
1644 #if defined(__linux__)
1645 /* Note: we do not have a reliable method to detect if the floppy is
1646 present. The current method is to try to open the floppy at every
1647 I/O and to keep it opened during a few hundreds of ms. */
1648 static int fd_open(BlockDriverState
*bs
)
1650 BDRVRawState
*s
= bs
->opaque
;
1651 int last_media_present
;
1653 if (s
->type
!= FTYPE_FD
)
1655 last_media_present
= (s
->fd
>= 0);
1657 (get_clock() - s
->fd_open_time
) >= FD_OPEN_TIMEOUT
) {
1661 printf("Floppy closed\n");
1665 if (s
->fd_got_error
&&
1666 (get_clock() - s
->fd_error_time
) < FD_OPEN_TIMEOUT
) {
1668 printf("No floppy (open delayed)\n");
1672 s
->fd
= qemu_open(bs
->filename
, s
->open_flags
& ~O_NONBLOCK
);
1674 s
->fd_error_time
= get_clock();
1675 s
->fd_got_error
= 1;
1676 if (last_media_present
)
1677 s
->fd_media_changed
= 1;
1679 printf("No floppy\n");
1684 printf("Floppy opened\n");
1687 if (!last_media_present
)
1688 s
->fd_media_changed
= 1;
1689 s
->fd_open_time
= get_clock();
1690 s
->fd_got_error
= 0;
1694 static int hdev_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
1696 BDRVRawState
*s
= bs
->opaque
;
1698 return ioctl(s
->fd
, req
, buf
);
1701 static BlockDriverAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
1702 unsigned long int req
, void *buf
,
1703 BlockDriverCompletionFunc
*cb
, void *opaque
)
1705 BDRVRawState
*s
= bs
->opaque
;
1706 RawPosixAIOData
*acb
;
1709 if (fd_open(bs
) < 0)
1712 acb
= g_slice_new(RawPosixAIOData
);
1714 acb
->aio_type
= QEMU_AIO_IOCTL
;
1715 acb
->aio_fildes
= s
->fd
;
1716 acb
->aio_offset
= 0;
1717 acb
->aio_ioctl_buf
= buf
;
1718 acb
->aio_ioctl_cmd
= req
;
1719 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1720 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1723 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1724 static int fd_open(BlockDriverState
*bs
)
1726 BDRVRawState
*s
= bs
->opaque
;
1728 /* this is just to ensure s->fd is sane (its called by io ops) */
1733 #else /* !linux && !FreeBSD */
1735 static int fd_open(BlockDriverState
*bs
)
1740 #endif /* !linux && !FreeBSD */
1742 static coroutine_fn BlockDriverAIOCB
*hdev_aio_discard(BlockDriverState
*bs
,
1743 int64_t sector_num
, int nb_sectors
,
1744 BlockDriverCompletionFunc
*cb
, void *opaque
)
1746 BDRVRawState
*s
= bs
->opaque
;
1748 if (fd_open(bs
) < 0) {
1751 return paio_submit(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1752 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1755 static coroutine_fn
int hdev_co_write_zeroes(BlockDriverState
*bs
,
1756 int64_t sector_num
, int nb_sectors
, BdrvRequestFlags flags
)
1758 BDRVRawState
*s
= bs
->opaque
;
1765 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1766 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1767 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
1768 } else if (s
->discard_zeroes
) {
1769 return paio_submit_co(bs
, s
->fd
, sector_num
, NULL
, nb_sectors
,
1770 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
1775 static int hdev_create(const char *filename
, QEMUOptionParameter
*options
,
1780 struct stat stat_buf
;
1781 int64_t total_size
= 0;
1784 /* This function is used by all three protocol block drivers and therefore
1785 * any of these three prefixes may be given.
1786 * The return value has to be stored somewhere, otherwise this is an error
1787 * due to -Werror=unused-value. */
1789 strstart(filename
, "host_device:", &filename
) ||
1790 strstart(filename
, "host_cdrom:" , &filename
) ||
1791 strstart(filename
, "host_floppy:", &filename
);
1795 /* Read out options */
1796 while (options
&& options
->name
) {
1797 if (!strcmp(options
->name
, "size")) {
1798 total_size
= options
->value
.n
/ BDRV_SECTOR_SIZE
;
1803 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
1806 error_setg_errno(errp
, -ret
, "Could not open device");
1810 if (fstat(fd
, &stat_buf
) < 0) {
1812 error_setg_errno(errp
, -ret
, "Could not stat device");
1813 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
1815 "The given file is neither a block nor a character device");
1817 } else if (lseek(fd
, 0, SEEK_END
) < total_size
* BDRV_SECTOR_SIZE
) {
1818 error_setg(errp
, "Device is too small");
1826 static BlockDriver bdrv_host_device
= {
1827 .format_name
= "host_device",
1828 .protocol_name
= "host_device",
1829 .instance_size
= sizeof(BDRVRawState
),
1830 .bdrv_needs_filename
= true,
1831 .bdrv_probe_device
= hdev_probe_device
,
1832 .bdrv_parse_filename
= hdev_parse_filename
,
1833 .bdrv_file_open
= hdev_open
,
1834 .bdrv_close
= raw_close
,
1835 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1836 .bdrv_reopen_commit
= raw_reopen_commit
,
1837 .bdrv_reopen_abort
= raw_reopen_abort
,
1838 .bdrv_create
= hdev_create
,
1839 .create_options
= raw_create_options
,
1840 .bdrv_co_write_zeroes
= hdev_co_write_zeroes
,
1842 .bdrv_aio_readv
= raw_aio_readv
,
1843 .bdrv_aio_writev
= raw_aio_writev
,
1844 .bdrv_aio_flush
= raw_aio_flush
,
1845 .bdrv_aio_discard
= hdev_aio_discard
,
1846 .bdrv_refresh_limits
= raw_refresh_limits
,
1848 .bdrv_truncate
= raw_truncate
,
1849 .bdrv_getlength
= raw_getlength
,
1850 .bdrv_get_info
= raw_get_info
,
1851 .bdrv_get_allocated_file_size
1852 = raw_get_allocated_file_size
,
1854 /* generic scsi device */
1856 .bdrv_ioctl
= hdev_ioctl
,
1857 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
1862 static void floppy_parse_filename(const char *filename
, QDict
*options
,
1865 /* The prefix is optional, just as for "file". */
1866 strstart(filename
, "host_floppy:", &filename
);
1868 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
1871 static int floppy_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1874 BDRVRawState
*s
= bs
->opaque
;
1875 Error
*local_err
= NULL
;
1880 /* open will not fail even if no floppy is inserted, so add O_NONBLOCK */
1881 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
1884 error_propagate(errp
, local_err
);
1889 /* close fd so that we can reopen it as needed */
1892 s
->fd_media_changed
= 1;
1897 static int floppy_probe_device(const char *filename
)
1901 struct floppy_struct fdparam
;
1904 if (strstart(filename
, "/dev/fd", NULL
) &&
1905 !strstart(filename
, "/dev/fdset/", NULL
)) {
1909 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
1913 ret
= fstat(fd
, &st
);
1914 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
1918 /* Attempt to detect via a floppy specific ioctl */
1919 ret
= ioctl(fd
, FDGETPRM
, &fdparam
);
1930 static int floppy_is_inserted(BlockDriverState
*bs
)
1932 return fd_open(bs
) >= 0;
1935 static int floppy_media_changed(BlockDriverState
*bs
)
1937 BDRVRawState
*s
= bs
->opaque
;
1941 * XXX: we do not have a true media changed indication.
1942 * It does not work if the floppy is changed without trying to read it.
1945 ret
= s
->fd_media_changed
;
1946 s
->fd_media_changed
= 0;
1948 printf("Floppy changed=%d\n", ret
);
1953 static void floppy_eject(BlockDriverState
*bs
, bool eject_flag
)
1955 BDRVRawState
*s
= bs
->opaque
;
1962 fd
= qemu_open(bs
->filename
, s
->open_flags
| O_NONBLOCK
);
1964 if (ioctl(fd
, FDEJECT
, 0) < 0)
1970 static BlockDriver bdrv_host_floppy
= {
1971 .format_name
= "host_floppy",
1972 .protocol_name
= "host_floppy",
1973 .instance_size
= sizeof(BDRVRawState
),
1974 .bdrv_needs_filename
= true,
1975 .bdrv_probe_device
= floppy_probe_device
,
1976 .bdrv_parse_filename
= floppy_parse_filename
,
1977 .bdrv_file_open
= floppy_open
,
1978 .bdrv_close
= raw_close
,
1979 .bdrv_reopen_prepare
= raw_reopen_prepare
,
1980 .bdrv_reopen_commit
= raw_reopen_commit
,
1981 .bdrv_reopen_abort
= raw_reopen_abort
,
1982 .bdrv_create
= hdev_create
,
1983 .create_options
= raw_create_options
,
1985 .bdrv_aio_readv
= raw_aio_readv
,
1986 .bdrv_aio_writev
= raw_aio_writev
,
1987 .bdrv_aio_flush
= raw_aio_flush
,
1988 .bdrv_refresh_limits
= raw_refresh_limits
,
1990 .bdrv_truncate
= raw_truncate
,
1991 .bdrv_getlength
= raw_getlength
,
1992 .has_variable_length
= true,
1993 .bdrv_get_allocated_file_size
1994 = raw_get_allocated_file_size
,
1996 /* removable device support */
1997 .bdrv_is_inserted
= floppy_is_inserted
,
1998 .bdrv_media_changed
= floppy_media_changed
,
1999 .bdrv_eject
= floppy_eject
,
2003 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2004 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2007 /* The prefix is optional, just as for "file". */
2008 strstart(filename
, "host_cdrom:", &filename
);
2010 qdict_put_obj(options
, "filename", QOBJECT(qstring_from_str(filename
)));
2015 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2018 BDRVRawState
*s
= bs
->opaque
;
2019 Error
*local_err
= NULL
;
2024 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2025 ret
= raw_open_common(bs
, options
, flags
, O_NONBLOCK
, &local_err
);
2027 error_propagate(errp
, local_err
);
2032 static int cdrom_probe_device(const char *filename
)
2038 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2042 ret
= fstat(fd
, &st
);
2043 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2047 /* Attempt to detect via a CDROM specific ioctl */
2048 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2058 static int cdrom_is_inserted(BlockDriverState
*bs
)
2060 BDRVRawState
*s
= bs
->opaque
;
2063 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2064 if (ret
== CDS_DISC_OK
)
2069 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2071 BDRVRawState
*s
= bs
->opaque
;
2074 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2075 perror("CDROMEJECT");
2077 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2078 perror("CDROMEJECT");
2082 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2084 BDRVRawState
*s
= bs
->opaque
;
2086 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2088 * Note: an error can happen if the distribution automatically
2091 /* perror("CDROM_LOCKDOOR"); */
2095 static BlockDriver bdrv_host_cdrom
= {
2096 .format_name
= "host_cdrom",
2097 .protocol_name
= "host_cdrom",
2098 .instance_size
= sizeof(BDRVRawState
),
2099 .bdrv_needs_filename
= true,
2100 .bdrv_probe_device
= cdrom_probe_device
,
2101 .bdrv_parse_filename
= cdrom_parse_filename
,
2102 .bdrv_file_open
= cdrom_open
,
2103 .bdrv_close
= raw_close
,
2104 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2105 .bdrv_reopen_commit
= raw_reopen_commit
,
2106 .bdrv_reopen_abort
= raw_reopen_abort
,
2107 .bdrv_create
= hdev_create
,
2108 .create_options
= raw_create_options
,
2110 .bdrv_aio_readv
= raw_aio_readv
,
2111 .bdrv_aio_writev
= raw_aio_writev
,
2112 .bdrv_aio_flush
= raw_aio_flush
,
2113 .bdrv_refresh_limits
= raw_refresh_limits
,
2115 .bdrv_truncate
= raw_truncate
,
2116 .bdrv_getlength
= raw_getlength
,
2117 .has_variable_length
= true,
2118 .bdrv_get_allocated_file_size
2119 = raw_get_allocated_file_size
,
2121 /* removable device support */
2122 .bdrv_is_inserted
= cdrom_is_inserted
,
2123 .bdrv_eject
= cdrom_eject
,
2124 .bdrv_lock_medium
= cdrom_lock_medium
,
2126 /* generic scsi device */
2127 .bdrv_ioctl
= hdev_ioctl
,
2128 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2130 #endif /* __linux__ */
2132 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2133 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2136 BDRVRawState
*s
= bs
->opaque
;
2137 Error
*local_err
= NULL
;
2142 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2145 error_propagate(errp
, local_err
);
2150 /* make sure the door isn't locked at this time */
2151 ioctl(s
->fd
, CDIOCALLOW
);
2155 static int cdrom_probe_device(const char *filename
)
2157 if (strstart(filename
, "/dev/cd", NULL
) ||
2158 strstart(filename
, "/dev/acd", NULL
))
2163 static int cdrom_reopen(BlockDriverState
*bs
)
2165 BDRVRawState
*s
= bs
->opaque
;
2169 * Force reread of possibly changed/newly loaded disc,
2170 * FreeBSD seems to not notice sometimes...
2174 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
2181 /* make sure the door isn't locked at this time */
2182 ioctl(s
->fd
, CDIOCALLOW
);
2186 static int cdrom_is_inserted(BlockDriverState
*bs
)
2188 return raw_getlength(bs
) > 0;
2191 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2193 BDRVRawState
*s
= bs
->opaque
;
2198 (void) ioctl(s
->fd
, CDIOCALLOW
);
2201 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
2202 perror("CDIOCEJECT");
2204 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
2205 perror("CDIOCCLOSE");
2211 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2213 BDRVRawState
*s
= bs
->opaque
;
2217 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
2219 * Note: an error can happen if the distribution automatically
2222 /* perror("CDROM_LOCKDOOR"); */
2226 static BlockDriver bdrv_host_cdrom
= {
2227 .format_name
= "host_cdrom",
2228 .protocol_name
= "host_cdrom",
2229 .instance_size
= sizeof(BDRVRawState
),
2230 .bdrv_needs_filename
= true,
2231 .bdrv_probe_device
= cdrom_probe_device
,
2232 .bdrv_parse_filename
= cdrom_parse_filename
,
2233 .bdrv_file_open
= cdrom_open
,
2234 .bdrv_close
= raw_close
,
2235 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2236 .bdrv_reopen_commit
= raw_reopen_commit
,
2237 .bdrv_reopen_abort
= raw_reopen_abort
,
2238 .bdrv_create
= hdev_create
,
2239 .create_options
= raw_create_options
,
2241 .bdrv_aio_readv
= raw_aio_readv
,
2242 .bdrv_aio_writev
= raw_aio_writev
,
2243 .bdrv_aio_flush
= raw_aio_flush
,
2244 .bdrv_refresh_limits
= raw_refresh_limits
,
2246 .bdrv_truncate
= raw_truncate
,
2247 .bdrv_getlength
= raw_getlength
,
2248 .has_variable_length
= true,
2249 .bdrv_get_allocated_file_size
2250 = raw_get_allocated_file_size
,
2252 /* removable device support */
2253 .bdrv_is_inserted
= cdrom_is_inserted
,
2254 .bdrv_eject
= cdrom_eject
,
2255 .bdrv_lock_medium
= cdrom_lock_medium
,
2257 #endif /* __FreeBSD__ */
2259 #ifdef CONFIG_LINUX_AIO
2261 * Return the file descriptor for Linux AIO
2263 * This function is a layering violation and should be removed when it becomes
2264 * possible to call the block layer outside the global mutex. It allows the
2265 * caller to hijack the file descriptor so I/O can be performed outside the
2268 int raw_get_aio_fd(BlockDriverState
*bs
)
2276 if (bs
->drv
== bdrv_find_format("raw")) {
2280 /* raw-posix has several protocols so just check for raw_aio_readv */
2281 if (bs
->drv
->bdrv_aio_readv
!= raw_aio_readv
) {
2291 #endif /* CONFIG_LINUX_AIO */
2293 static void bdrv_file_init(void)
2296 * Register all the drivers. Note that order is important, the driver
2297 * registered last will get probed first.
2299 bdrv_register(&bdrv_file
);
2300 bdrv_register(&bdrv_host_device
);
2302 bdrv_register(&bdrv_host_floppy
);
2303 bdrv_register(&bdrv_host_cdrom
);
2305 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2306 bdrv_register(&bdrv_host_cdrom
);
2310 block_init(bdrv_file_init
);