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/osdep.h"
25 #include "qapi/error.h"
26 #include "qemu/cutils.h"
27 #include "qemu/error-report.h"
28 #include "block/block_int.h"
29 #include "qemu/module.h"
31 #include "block/thread-pool.h"
33 #include "block/raw-aio.h"
34 #include "qapi/util.h"
35 #include "qapi/qmp/qstring.h"
37 #if defined(__APPLE__) && (__MACH__)
39 #include <sys/param.h>
40 #include <IOKit/IOKitLib.h>
41 #include <IOKit/IOBSD.h>
42 #include <IOKit/storage/IOMediaBSDClient.h>
43 #include <IOKit/storage/IOMedia.h>
44 #include <IOKit/storage/IOCDMedia.h>
45 //#include <IOKit/storage/IOCDTypes.h>
46 #include <IOKit/storage/IODVDMedia.h>
47 #include <CoreFoundation/CoreFoundation.h>
51 #define _POSIX_PTHREAD_SEMANTICS 1
55 #include <sys/ioctl.h>
56 #include <sys/param.h>
57 #include <linux/cdrom.h>
60 #include <linux/hdreg.h>
66 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
69 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
70 #include <linux/falloc.h>
72 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
78 #include <sys/ioctl.h>
79 #include <sys/disklabel.h>
84 #include <sys/ioctl.h>
85 #include <sys/disklabel.h>
91 #include <sys/ioctl.h>
92 #include <sys/diskslice.h>
102 # define DEBUG_BLOCK_PRINT 1
104 # define DEBUG_BLOCK_PRINT 0
106 #define DPRINTF(fmt, ...) \
108 if (DEBUG_BLOCK_PRINT) { \
109 printf(fmt, ## __VA_ARGS__); \
113 /* OS X does not have O_DSYNC */
116 #define O_DSYNC O_SYNC
117 #elif defined(O_FSYNC)
118 #define O_DSYNC O_FSYNC
122 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
124 #define O_DIRECT O_DSYNC
130 #define MAX_BLOCKSIZE 4096
132 /* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
133 * leaving a few more bytes for its future use. */
134 #define RAW_LOCK_PERM_BASE 100
135 #define RAW_LOCK_SHARED_BASE 200
137 typedef struct BDRVRawState
{
145 /* The current permissions. */
147 uint64_t shared_perm
;
153 bool has_write_zeroes
:1;
154 bool discard_zeroes
:1;
155 bool use_linux_aio
:1;
156 bool page_cache_inconsistent
:1;
158 bool needs_alignment
;
161 typedef struct BDRVRawReopenState
{
164 } BDRVRawReopenState
;
166 static int fd_open(BlockDriverState
*bs
);
167 static int64_t raw_getlength(BlockDriverState
*bs
);
169 typedef struct RawPosixAIOData
{
170 BlockDriverState
*bs
;
173 struct iovec
*aio_iov
;
178 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
183 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
184 static int cdrom_reopen(BlockDriverState
*bs
);
187 #if defined(__NetBSD__)
188 static int raw_normalize_devicepath(const char **filename
)
190 static char namebuf
[PATH_MAX
];
191 const char *dp
, *fname
;
195 dp
= strrchr(fname
, '/');
196 if (lstat(fname
, &sb
) < 0) {
197 fprintf(stderr
, "%s: stat failed: %s\n",
198 fname
, strerror(errno
));
202 if (!S_ISBLK(sb
.st_mode
)) {
207 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
209 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
210 (int)(dp
- fname
), fname
, dp
+ 1);
212 fprintf(stderr
, "%s is a block device", fname
);
214 fprintf(stderr
, ", using %s\n", *filename
);
219 static int raw_normalize_devicepath(const char **filename
)
226 * Get logical block size via ioctl. On success store it in @sector_size_p.
228 static int probe_logical_blocksize(int fd
, unsigned int *sector_size_p
)
230 unsigned int sector_size
;
231 bool success
= false;
235 static const unsigned long ioctl_list
[] = {
239 #ifdef DKIOCGETBLOCKSIZE
242 #ifdef DIOCGSECTORSIZE
247 /* Try a few ioctls to get the right size */
248 for (i
= 0; i
< (int)ARRAY_SIZE(ioctl_list
); i
++) {
249 if (ioctl(fd
, ioctl_list
[i
], §or_size
) >= 0) {
250 *sector_size_p
= sector_size
;
255 return success
? 0 : -errno
;
259 * Get physical block size of @fd.
260 * On success, store it in @blk_size and return 0.
261 * On failure, return -errno.
263 static int probe_physical_blocksize(int fd
, unsigned int *blk_size
)
266 if (ioctl(fd
, BLKPBSZGET
, blk_size
) < 0) {
275 /* Check if read is allowed with given memory buffer and length.
277 * This function is used to check O_DIRECT memory buffer and request alignment.
279 static bool raw_is_io_aligned(int fd
, void *buf
, size_t len
)
281 ssize_t ret
= pread(fd
, buf
, len
, 0);
288 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
289 * other errors (e.g. real I/O error), which could happen on a failed
290 * drive, since we only care about probing alignment.
292 if (errno
!= EINVAL
) {
300 static void raw_probe_alignment(BlockDriverState
*bs
, int fd
, Error
**errp
)
302 BDRVRawState
*s
= bs
->opaque
;
304 size_t max_align
= MAX(MAX_BLOCKSIZE
, getpagesize());
306 /* For SCSI generic devices the alignment is not really used.
307 With buffered I/O, we don't have any restrictions. */
308 if (bdrv_is_sg(bs
) || !s
->needs_alignment
) {
309 bs
->bl
.request_alignment
= 1;
314 bs
->bl
.request_alignment
= 0;
316 /* Let's try to use the logical blocksize for the alignment. */
317 if (probe_logical_blocksize(fd
, &bs
->bl
.request_alignment
) < 0) {
318 bs
->bl
.request_alignment
= 0;
323 if (xfsctl(NULL
, fd
, XFS_IOC_DIOINFO
, &da
) >= 0) {
324 bs
->bl
.request_alignment
= da
.d_miniosz
;
325 /* The kernel returns wrong information for d_mem */
326 /* s->buf_align = da.d_mem; */
331 /* If we could not get the sizes so far, we can only guess them */
334 buf
= qemu_memalign(max_align
, 2 * max_align
);
335 for (align
= 512; align
<= max_align
; align
<<= 1) {
336 if (raw_is_io_aligned(fd
, buf
+ align
, max_align
)) {
337 s
->buf_align
= align
;
344 if (!bs
->bl
.request_alignment
) {
346 buf
= qemu_memalign(s
->buf_align
, max_align
);
347 for (align
= 512; align
<= max_align
; align
<<= 1) {
348 if (raw_is_io_aligned(fd
, buf
, align
)) {
349 bs
->bl
.request_alignment
= align
;
356 if (!s
->buf_align
|| !bs
->bl
.request_alignment
) {
357 error_setg(errp
, "Could not find working O_DIRECT alignment");
358 error_append_hint(errp
, "Try cache.direct=off\n");
362 static void raw_parse_flags(int bdrv_flags
, int *open_flags
)
364 assert(open_flags
!= NULL
);
366 *open_flags
|= O_BINARY
;
367 *open_flags
&= ~O_ACCMODE
;
368 if (bdrv_flags
& BDRV_O_RDWR
) {
369 *open_flags
|= O_RDWR
;
371 *open_flags
|= O_RDONLY
;
374 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
375 * and O_DIRECT for no caching. */
376 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
377 *open_flags
|= O_DIRECT
;
381 static void raw_parse_filename(const char *filename
, QDict
*options
,
384 bdrv_parse_filename_strip_prefix(filename
, "file:", options
);
387 static QemuOptsList raw_runtime_opts
= {
389 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
393 .type
= QEMU_OPT_STRING
,
394 .help
= "File name of the image",
398 .type
= QEMU_OPT_STRING
,
399 .help
= "host AIO implementation (threads, native)",
403 .type
= QEMU_OPT_STRING
,
404 .help
= "file locking mode (on/off/auto, default: auto)",
406 { /* end of list */ }
410 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
411 int bdrv_flags
, int open_flags
, Error
**errp
)
413 BDRVRawState
*s
= bs
->opaque
;
415 Error
*local_err
= NULL
;
416 const char *filename
= NULL
;
417 BlockdevAioOptions aio
, aio_default
;
422 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
423 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
425 error_propagate(errp
, local_err
);
430 filename
= qemu_opt_get(opts
, "filename");
432 ret
= raw_normalize_devicepath(&filename
);
434 error_setg_errno(errp
, -ret
, "Could not normalize device path");
438 aio_default
= (bdrv_flags
& BDRV_O_NATIVE_AIO
)
439 ? BLOCKDEV_AIO_OPTIONS_NATIVE
440 : BLOCKDEV_AIO_OPTIONS_THREADS
;
441 aio
= qapi_enum_parse(BlockdevAioOptions_lookup
, qemu_opt_get(opts
, "aio"),
442 BLOCKDEV_AIO_OPTIONS__MAX
, aio_default
, &local_err
);
444 error_propagate(errp
, local_err
);
448 s
->use_linux_aio
= (aio
== BLOCKDEV_AIO_OPTIONS_NATIVE
);
450 locking
= qapi_enum_parse(OnOffAuto_lookup
, qemu_opt_get(opts
, "locking"),
451 ON_OFF_AUTO__MAX
, ON_OFF_AUTO_AUTO
, &local_err
);
453 error_propagate(errp
, local_err
);
462 "File lock requested but OFD locking syscall is unavailable, "
463 "falling back to POSIX file locks.\n"
464 "Due to the implementation, locks can be lost unexpectedly.\n");
467 case ON_OFF_AUTO_OFF
:
470 case ON_OFF_AUTO_AUTO
:
481 s
->open_flags
= open_flags
;
482 raw_parse_flags(bdrv_flags
, &s
->open_flags
);
485 fd
= qemu_open(filename
, s
->open_flags
, 0644);
488 error_setg_errno(errp
, errno
, "Could not open '%s'", filename
);
498 fd
= qemu_open(filename
, s
->open_flags
);
501 error_setg_errno(errp
, errno
, "Could not open '%s' for locking",
509 s
->shared_perm
= BLK_PERM_ALL
;
511 #ifdef CONFIG_LINUX_AIO
512 /* Currently Linux does AIO only for files opened with O_DIRECT */
513 if (s
->use_linux_aio
&& !(s
->open_flags
& O_DIRECT
)) {
514 error_setg(errp
, "aio=native was specified, but it requires "
515 "cache.direct=on, which was not specified.");
520 if (s
->use_linux_aio
) {
521 error_setg(errp
, "aio=native was specified, but is not supported "
526 #endif /* !defined(CONFIG_LINUX_AIO) */
528 s
->has_discard
= true;
529 s
->has_write_zeroes
= true;
530 bs
->supported_zero_flags
= BDRV_REQ_MAY_UNMAP
;
531 if ((bs
->open_flags
& BDRV_O_NOCACHE
) != 0) {
532 s
->needs_alignment
= true;
535 if (fstat(s
->fd
, &st
) < 0) {
537 error_setg_errno(errp
, errno
, "Could not stat file");
540 if (S_ISREG(st
.st_mode
)) {
541 s
->discard_zeroes
= true;
542 s
->has_fallocate
= true;
544 if (S_ISBLK(st
.st_mode
)) {
545 #ifdef BLKDISCARDZEROES
547 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
548 s
->discard_zeroes
= true;
552 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
553 * not rely on the contents of discarded blocks unless using O_DIRECT.
554 * Same for BLKZEROOUT.
556 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
557 s
->discard_zeroes
= false;
558 s
->has_write_zeroes
= false;
563 if (S_ISCHR(st
.st_mode
)) {
565 * The file is a char device (disk), which on FreeBSD isn't behind
566 * a pager, so force all requests to be aligned. This is needed
567 * so QEMU makes sure all IO operations on the device are aligned
568 * to sector size, or else FreeBSD will reject them with EINVAL.
570 s
->needs_alignment
= true;
575 if (platform_test_xfs_fd(s
->fd
)) {
582 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
589 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
592 BDRVRawState
*s
= bs
->opaque
;
594 s
->type
= FTYPE_FILE
;
595 return raw_open_common(bs
, options
, flags
, 0, errp
);
604 #define PERM_FOREACH(i) \
605 for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
607 /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
608 * file; if @unlock == true, also unlock the unneeded bytes.
609 * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
611 static int raw_apply_lock_bytes(BDRVRawState
*s
,
612 uint64_t perm_lock_bits
,
613 uint64_t shared_perm_lock_bits
,
614 bool unlock
, Error
**errp
)
620 int off
= RAW_LOCK_PERM_BASE
+ i
;
621 if (perm_lock_bits
& (1ULL << i
)) {
622 ret
= qemu_lock_fd(s
->lock_fd
, off
, 1, false);
624 error_setg(errp
, "Failed to lock byte %d", off
);
628 ret
= qemu_unlock_fd(s
->lock_fd
, off
, 1);
630 error_setg(errp
, "Failed to unlock byte %d", off
);
636 int off
= RAW_LOCK_SHARED_BASE
+ i
;
637 if (shared_perm_lock_bits
& (1ULL << i
)) {
638 ret
= qemu_lock_fd(s
->lock_fd
, off
, 1, false);
640 error_setg(errp
, "Failed to lock byte %d", off
);
644 ret
= qemu_unlock_fd(s
->lock_fd
, off
, 1);
646 error_setg(errp
, "Failed to unlock byte %d", off
);
654 /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
655 static int raw_check_lock_bytes(BDRVRawState
*s
,
656 uint64_t perm
, uint64_t shared_perm
,
663 int off
= RAW_LOCK_SHARED_BASE
+ i
;
664 uint64_t p
= 1ULL << i
;
666 ret
= qemu_lock_fd_test(s
->lock_fd
, off
, 1, true);
668 char *perm_name
= bdrv_perm_names(p
);
670 "Failed to get \"%s\" lock",
673 error_append_hint(errp
,
674 "Is another process using the image?\n");
680 int off
= RAW_LOCK_PERM_BASE
+ i
;
681 uint64_t p
= 1ULL << i
;
682 if (!(shared_perm
& p
)) {
683 ret
= qemu_lock_fd_test(s
->lock_fd
, off
, 1, true);
685 char *perm_name
= bdrv_perm_names(p
);
687 "Failed to get shared \"%s\" lock",
690 error_append_hint(errp
,
691 "Is another process using the image?\n");
699 static int raw_handle_perm_lock(BlockDriverState
*bs
,
701 uint64_t new_perm
, uint64_t new_shared
,
704 BDRVRawState
*s
= bs
->opaque
;
706 Error
*local_err
= NULL
;
712 if (bdrv_get_flags(bs
) & BDRV_O_INACTIVE
) {
716 assert(s
->lock_fd
> 0);
720 ret
= raw_apply_lock_bytes(s
, s
->perm
| new_perm
,
721 ~s
->shared_perm
| ~new_shared
,
724 ret
= raw_check_lock_bytes(s
, new_perm
, new_shared
, errp
);
730 /* fall through to unlock bytes. */
732 raw_apply_lock_bytes(s
, s
->perm
, ~s
->shared_perm
, true, &local_err
);
734 /* Theoretically the above call only unlocks bytes and it cannot
735 * fail. Something weird happened, report it.
737 error_report_err(local_err
);
741 raw_apply_lock_bytes(s
, new_perm
, ~new_shared
, true, &local_err
);
743 /* Theoretically the above call only unlocks bytes and it cannot
744 * fail. Something weird happened, report it.
746 error_report_err(local_err
);
753 static int raw_reopen_prepare(BDRVReopenState
*state
,
754 BlockReopenQueue
*queue
, Error
**errp
)
757 BDRVRawReopenState
*rs
;
759 Error
*local_err
= NULL
;
761 assert(state
!= NULL
);
762 assert(state
->bs
!= NULL
);
764 s
= state
->bs
->opaque
;
766 state
->opaque
= g_new0(BDRVRawReopenState
, 1);
769 if (s
->type
== FTYPE_CD
) {
770 rs
->open_flags
|= O_NONBLOCK
;
773 raw_parse_flags(state
->flags
, &rs
->open_flags
);
777 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
779 fcntl_flags
|= O_NOATIME
;
783 /* Not all operating systems have O_ASYNC, and those that don't
784 * will not let us track the state into rs->open_flags (typically
785 * you achieve the same effect with an ioctl, for example I_SETSIG
786 * on Solaris). But we do not use O_ASYNC, so that's fine.
788 assert((s
->open_flags
& O_ASYNC
) == 0);
791 if ((rs
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
792 /* dup the original fd */
793 rs
->fd
= qemu_dup(s
->fd
);
795 ret
= fcntl_setfl(rs
->fd
, rs
->open_flags
);
803 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
805 const char *normalized_filename
= state
->bs
->filename
;
806 ret
= raw_normalize_devicepath(&normalized_filename
);
808 error_setg_errno(errp
, -ret
, "Could not normalize device path");
810 assert(!(rs
->open_flags
& O_CREAT
));
811 rs
->fd
= qemu_open(normalized_filename
, rs
->open_flags
);
813 error_setg_errno(errp
, errno
, "Could not reopen file");
819 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
820 * alignment with the new fd. */
822 raw_probe_alignment(state
->bs
, rs
->fd
, &local_err
);
826 error_propagate(errp
, local_err
);
834 static void raw_reopen_commit(BDRVReopenState
*state
)
836 BDRVRawReopenState
*rs
= state
->opaque
;
837 BDRVRawState
*s
= state
->bs
->opaque
;
839 s
->open_flags
= rs
->open_flags
;
844 g_free(state
->opaque
);
845 state
->opaque
= NULL
;
849 static void raw_reopen_abort(BDRVReopenState
*state
)
851 BDRVRawReopenState
*rs
= state
->opaque
;
853 /* nothing to do if NULL, we didn't get far enough */
862 g_free(state
->opaque
);
863 state
->opaque
= NULL
;
866 static int hdev_get_max_transfer_length(BlockDriverState
*bs
, int fd
)
870 short max_sectors
= 0;
871 if (bs
->sg
&& ioctl(fd
, BLKSECTGET
, &max_bytes
) == 0) {
873 } else if (!bs
->sg
&& ioctl(fd
, BLKSECTGET
, &max_sectors
) == 0) {
874 return max_sectors
<< BDRV_SECTOR_BITS
;
883 static int hdev_get_max_segments(const struct stat
*st
)
893 sysfspath
= g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
894 major(st
->st_rdev
), minor(st
->st_rdev
));
895 fd
= open(sysfspath
, O_RDONLY
);
901 ret
= read(fd
, buf
, sizeof(buf
) - 1);
902 } while (ret
== -1 && errno
== EINTR
);
906 } else if (ret
== 0) {
911 /* The file is ended with '\n', pass 'end' to accept that. */
912 ret
= qemu_strtol(buf
, &end
, 10, &max_segments
);
913 if (ret
== 0 && end
&& *end
== '\n') {
928 static void raw_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
930 BDRVRawState
*s
= bs
->opaque
;
933 if (!fstat(s
->fd
, &st
)) {
934 if (S_ISBLK(st
.st_mode
) || S_ISCHR(st
.st_mode
)) {
935 int ret
= hdev_get_max_transfer_length(bs
, s
->fd
);
936 if (ret
> 0 && ret
<= BDRV_REQUEST_MAX_BYTES
) {
937 bs
->bl
.max_transfer
= pow2floor(ret
);
939 ret
= hdev_get_max_segments(&st
);
941 bs
->bl
.max_transfer
= MIN(bs
->bl
.max_transfer
,
942 ret
* getpagesize());
947 raw_probe_alignment(bs
, s
->fd
, errp
);
948 bs
->bl
.min_mem_alignment
= s
->buf_align
;
949 bs
->bl
.opt_mem_alignment
= MAX(s
->buf_align
, getpagesize());
952 static int check_for_dasd(int fd
)
955 struct dasd_information2_t info
= {0};
957 return ioctl(fd
, BIODASDINFO2
, &info
);
964 * Try to get @bs's logical and physical block size.
965 * On success, store them in @bsz and return zero.
966 * On failure, return negative errno.
968 static int hdev_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
970 BDRVRawState
*s
= bs
->opaque
;
973 /* If DASD, get blocksizes */
974 if (check_for_dasd(s
->fd
) < 0) {
977 ret
= probe_logical_blocksize(s
->fd
, &bsz
->log
);
981 return probe_physical_blocksize(s
->fd
, &bsz
->phys
);
985 * Try to get @bs's geometry: cyls, heads, sectors.
986 * On success, store them in @geo and return 0.
987 * On failure return -errno.
988 * (Allows block driver to assign default geometry values that guest sees)
991 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
993 BDRVRawState
*s
= bs
->opaque
;
994 struct hd_geometry ioctl_geo
= {0};
996 /* If DASD, get its geometry */
997 if (check_for_dasd(s
->fd
) < 0) {
1000 if (ioctl(s
->fd
, HDIO_GETGEO
, &ioctl_geo
) < 0) {
1003 /* HDIO_GETGEO may return success even though geo contains zeros
1004 (e.g. certain multipath setups) */
1005 if (!ioctl_geo
.heads
|| !ioctl_geo
.sectors
|| !ioctl_geo
.cylinders
) {
1008 /* Do not return a geometry for partition */
1009 if (ioctl_geo
.start
!= 0) {
1012 geo
->heads
= ioctl_geo
.heads
;
1013 geo
->sectors
= ioctl_geo
.sectors
;
1014 geo
->cylinders
= ioctl_geo
.cylinders
;
1018 #else /* __linux__ */
1019 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
1025 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
1029 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
1037 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
1039 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1042 if (s
->page_cache_inconsistent
) {
1046 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
1048 /* There is no clear definition of the semantics of a failing fsync(),
1049 * so we may have to assume the worst. The sad truth is that this
1050 * assumption is correct for Linux. Some pages are now probably marked
1051 * clean in the page cache even though they are inconsistent with the
1052 * on-disk contents. The next fdatasync() call would succeed, but no
1053 * further writeback attempt will be made. We can't get back to a state
1054 * in which we know what is on disk (we would have to rewrite
1055 * everything that was touched since the last fdatasync() at least), so
1056 * make bdrv_flush() fail permanently. Given that the behaviour isn't
1057 * really defined, I have little hope that other OSes are doing better.
1059 * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1061 if ((s
->open_flags
& O_DIRECT
) == 0) {
1062 s
->page_cache_inconsistent
= true;
1069 #ifdef CONFIG_PREADV
1071 static bool preadv_present
= true;
1074 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1076 return preadv(fd
, iov
, nr_iov
, offset
);
1080 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1082 return pwritev(fd
, iov
, nr_iov
, offset
);
1087 static bool preadv_present
= false;
1090 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1096 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1103 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
1108 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
1109 len
= qemu_pwritev(aiocb
->aio_fildes
,
1114 len
= qemu_preadv(aiocb
->aio_fildes
,
1118 } while (len
== -1 && errno
== EINTR
);
1127 * Read/writes the data to/from a given linear buffer.
1129 * Returns the number of bytes handles or -errno in case of an error. Short
1130 * reads are only returned if the end of the file is reached.
1132 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
1137 while (offset
< aiocb
->aio_nbytes
) {
1138 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1139 len
= pwrite(aiocb
->aio_fildes
,
1140 (const char *)buf
+ offset
,
1141 aiocb
->aio_nbytes
- offset
,
1142 aiocb
->aio_offset
+ offset
);
1144 len
= pread(aiocb
->aio_fildes
,
1146 aiocb
->aio_nbytes
- offset
,
1147 aiocb
->aio_offset
+ offset
);
1149 if (len
== -1 && errno
== EINTR
) {
1151 } else if (len
== -1 && errno
== EINVAL
&&
1152 (aiocb
->bs
->open_flags
& BDRV_O_NOCACHE
) &&
1153 !(aiocb
->aio_type
& QEMU_AIO_WRITE
) &&
1155 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1156 * after a short read. Assume that O_DIRECT short reads only occur
1157 * at EOF. Therefore this is a short read, not an I/O error.
1160 } else if (len
== -1) {
1163 } else if (len
== 0) {
1172 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
1177 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
1179 * If there is just a single buffer, and it is properly aligned
1180 * we can just use plain pread/pwrite without any problems.
1182 if (aiocb
->aio_niov
== 1) {
1183 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
1186 * We have more than one iovec, and all are properly aligned.
1188 * Try preadv/pwritev first and fall back to linearizing the
1189 * buffer if it's not supported.
1191 if (preadv_present
) {
1192 nbytes
= handle_aiocb_rw_vector(aiocb
);
1193 if (nbytes
== aiocb
->aio_nbytes
||
1194 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
1197 preadv_present
= false;
1201 * XXX(hch): short read/write. no easy way to handle the reminder
1202 * using these interfaces. For now retry using plain
1208 * Ok, we have to do it the hard way, copy all segments into
1209 * a single aligned buffer.
1211 buf
= qemu_try_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
1216 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1220 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
1221 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
1222 p
+= aiocb
->aio_iov
[i
].iov_len
;
1224 assert(p
- buf
== aiocb
->aio_nbytes
);
1227 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
1228 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
1230 size_t count
= aiocb
->aio_nbytes
, copy
;
1233 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
1235 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
1236 copy
= aiocb
->aio_iov
[i
].iov_len
;
1238 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
1239 assert(count
>= copy
);
1251 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1253 struct xfs_flock64 fl
;
1256 memset(&fl
, 0, sizeof(fl
));
1257 fl
.l_whence
= SEEK_SET
;
1258 fl
.l_start
= offset
;
1261 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
1263 DPRINTF("cannot write zero range (%s)\n", strerror(errno
));
1270 static int xfs_discard(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1272 struct xfs_flock64 fl
;
1275 memset(&fl
, 0, sizeof(fl
));
1276 fl
.l_whence
= SEEK_SET
;
1277 fl
.l_start
= offset
;
1280 if (xfsctl(NULL
, s
->fd
, XFS_IOC_UNRESVSP64
, &fl
) < 0) {
1282 DPRINTF("cannot punch hole (%s)\n", strerror(errno
));
1290 static int translate_err(int err
)
1292 if (err
== -ENODEV
|| err
== -ENOSYS
|| err
== -EOPNOTSUPP
||
1299 #ifdef CONFIG_FALLOCATE
1300 static int do_fallocate(int fd
, int mode
, off_t offset
, off_t len
)
1303 if (fallocate(fd
, mode
, offset
, len
) == 0) {
1306 } while (errno
== EINTR
);
1307 return translate_err(-errno
);
1311 static ssize_t
handle_aiocb_write_zeroes_block(RawPosixAIOData
*aiocb
)
1314 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1316 if (!s
->has_write_zeroes
) {
1322 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1323 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
1326 } while (errno
== EINTR
);
1328 ret
= translate_err(-errno
);
1331 if (ret
== -ENOTSUP
) {
1332 s
->has_write_zeroes
= false;
1337 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
1339 #if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1340 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1342 #ifdef CONFIG_FALLOCATE
1346 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1347 return handle_aiocb_write_zeroes_block(aiocb
);
1352 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1356 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1357 if (s
->has_write_zeroes
) {
1358 int ret
= do_fallocate(s
->fd
, FALLOC_FL_ZERO_RANGE
,
1359 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1360 if (ret
== 0 || ret
!= -ENOTSUP
) {
1363 s
->has_write_zeroes
= false;
1367 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1368 if (s
->has_discard
&& s
->has_fallocate
) {
1369 int ret
= do_fallocate(s
->fd
,
1370 FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1371 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1373 ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1374 if (ret
== 0 || ret
!= -ENOTSUP
) {
1377 s
->has_fallocate
= false;
1378 } else if (ret
!= -ENOTSUP
) {
1381 s
->has_discard
= false;
1386 #ifdef CONFIG_FALLOCATE
1387 /* Last resort: we are trying to extend the file with zeroed data. This
1388 * can be done via fallocate(fd, 0) */
1389 len
= bdrv_getlength(aiocb
->bs
);
1390 if (s
->has_fallocate
&& len
>= 0 && aiocb
->aio_offset
>= len
) {
1391 int ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1392 if (ret
== 0 || ret
!= -ENOTSUP
) {
1395 s
->has_fallocate
= false;
1402 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
1404 int ret
= -EOPNOTSUPP
;
1405 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1407 if (!s
->has_discard
) {
1411 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1414 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1415 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
1418 } while (errno
== EINTR
);
1425 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1429 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1430 ret
= do_fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1431 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1435 ret
= translate_err(ret
);
1436 if (ret
== -ENOTSUP
) {
1437 s
->has_discard
= false;
1442 static int aio_worker(void *arg
)
1444 RawPosixAIOData
*aiocb
= arg
;
1447 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
1449 ret
= handle_aiocb_rw(aiocb
);
1450 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1451 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
1452 0, aiocb
->aio_nbytes
- ret
);
1454 ret
= aiocb
->aio_nbytes
;
1456 if (ret
== aiocb
->aio_nbytes
) {
1458 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1462 case QEMU_AIO_WRITE
:
1463 ret
= handle_aiocb_rw(aiocb
);
1464 if (ret
== aiocb
->aio_nbytes
) {
1466 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1470 case QEMU_AIO_FLUSH
:
1471 ret
= handle_aiocb_flush(aiocb
);
1473 case QEMU_AIO_IOCTL
:
1474 ret
= handle_aiocb_ioctl(aiocb
);
1476 case QEMU_AIO_DISCARD
:
1477 ret
= handle_aiocb_discard(aiocb
);
1479 case QEMU_AIO_WRITE_ZEROES
:
1480 ret
= handle_aiocb_write_zeroes(aiocb
);
1483 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
1492 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
1493 int64_t offset
, QEMUIOVector
*qiov
,
1494 int bytes
, int type
)
1496 RawPosixAIOData
*acb
= g_new(RawPosixAIOData
, 1);
1500 acb
->aio_type
= type
;
1501 acb
->aio_fildes
= fd
;
1503 acb
->aio_nbytes
= bytes
;
1504 acb
->aio_offset
= offset
;
1507 acb
->aio_iov
= qiov
->iov
;
1508 acb
->aio_niov
= qiov
->niov
;
1509 assert(qiov
->size
== bytes
);
1512 trace_paio_submit_co(offset
, bytes
, type
);
1513 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1514 return thread_pool_submit_co(pool
, aio_worker
, acb
);
1517 static BlockAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
1518 int64_t offset
, QEMUIOVector
*qiov
, int bytes
,
1519 BlockCompletionFunc
*cb
, void *opaque
, int type
)
1521 RawPosixAIOData
*acb
= g_new(RawPosixAIOData
, 1);
1525 acb
->aio_type
= type
;
1526 acb
->aio_fildes
= fd
;
1528 acb
->aio_nbytes
= bytes
;
1529 acb
->aio_offset
= offset
;
1532 acb
->aio_iov
= qiov
->iov
;
1533 acb
->aio_niov
= qiov
->niov
;
1534 assert(qiov
->size
== acb
->aio_nbytes
);
1537 trace_paio_submit(acb
, opaque
, offset
, bytes
, type
);
1538 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1539 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1542 static int coroutine_fn
raw_co_prw(BlockDriverState
*bs
, uint64_t offset
,
1543 uint64_t bytes
, QEMUIOVector
*qiov
, int type
)
1545 BDRVRawState
*s
= bs
->opaque
;
1547 if (fd_open(bs
) < 0)
1551 * Check if the underlying device requires requests to be aligned,
1552 * and if the request we are trying to submit is aligned or not.
1553 * If this is the case tell the low-level driver that it needs
1554 * to copy the buffer.
1556 if (s
->needs_alignment
) {
1557 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1558 type
|= QEMU_AIO_MISALIGNED
;
1559 #ifdef CONFIG_LINUX_AIO
1560 } else if (s
->use_linux_aio
) {
1561 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1562 assert(qiov
->size
== bytes
);
1563 return laio_co_submit(bs
, aio
, s
->fd
, offset
, qiov
, type
);
1568 return paio_submit_co(bs
, s
->fd
, offset
, qiov
, bytes
, type
);
1571 static int coroutine_fn
raw_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1572 uint64_t bytes
, QEMUIOVector
*qiov
,
1575 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_READ
);
1578 static int coroutine_fn
raw_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1579 uint64_t bytes
, QEMUIOVector
*qiov
,
1583 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_WRITE
);
1586 static void raw_aio_plug(BlockDriverState
*bs
)
1588 #ifdef CONFIG_LINUX_AIO
1589 BDRVRawState
*s
= bs
->opaque
;
1590 if (s
->use_linux_aio
) {
1591 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1592 laio_io_plug(bs
, aio
);
1597 static void raw_aio_unplug(BlockDriverState
*bs
)
1599 #ifdef CONFIG_LINUX_AIO
1600 BDRVRawState
*s
= bs
->opaque
;
1601 if (s
->use_linux_aio
) {
1602 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1603 laio_io_unplug(bs
, aio
);
1608 static BlockAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1609 BlockCompletionFunc
*cb
, void *opaque
)
1611 BDRVRawState
*s
= bs
->opaque
;
1613 if (fd_open(bs
) < 0)
1616 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1619 static void raw_close(BlockDriverState
*bs
)
1621 BDRVRawState
*s
= bs
->opaque
;
1627 if (s
->lock_fd
>= 0) {
1628 qemu_close(s
->lock_fd
);
1634 * Truncates the given regular file @fd to @offset and, when growing, fills the
1635 * new space according to @prealloc.
1637 * Returns: 0 on success, -errno on failure.
1639 static int raw_regular_truncate(int fd
, int64_t offset
, PreallocMode prealloc
,
1643 int64_t current_length
= 0;
1647 if (fstat(fd
, &st
) < 0) {
1649 error_setg_errno(errp
, -result
, "Could not stat file");
1653 current_length
= st
.st_size
;
1654 if (current_length
> offset
&& prealloc
!= PREALLOC_MODE_OFF
) {
1655 error_setg(errp
, "Cannot use preallocation for shrinking files");
1660 #ifdef CONFIG_POSIX_FALLOCATE
1661 case PREALLOC_MODE_FALLOC
:
1663 * Truncating before posix_fallocate() makes it about twice slower on
1664 * file systems that do not support fallocate(), trying to check if a
1665 * block is allocated before allocating it, so don't do that here.
1667 result
= -posix_fallocate(fd
, current_length
, offset
- current_length
);
1669 /* posix_fallocate() doesn't set errno. */
1670 error_setg_errno(errp
, -result
,
1671 "Could not preallocate new data");
1675 case PREALLOC_MODE_FULL
:
1677 int64_t num
= 0, left
= offset
- current_length
;
1680 * Knowing the final size from the beginning could allow the file
1681 * system driver to do less allocations and possibly avoid
1682 * fragmentation of the file.
1684 if (ftruncate(fd
, offset
) != 0) {
1686 error_setg_errno(errp
, -result
, "Could not resize file");
1690 buf
= g_malloc0(65536);
1692 result
= lseek(fd
, current_length
, SEEK_SET
);
1695 error_setg_errno(errp
, -result
,
1696 "Failed to seek to the old end of file");
1701 num
= MIN(left
, 65536);
1702 result
= write(fd
, buf
, num
);
1705 error_setg_errno(errp
, -result
,
1706 "Could not write zeros for preallocation");
1715 error_setg_errno(errp
, -result
,
1716 "Could not flush file to disk");
1722 case PREALLOC_MODE_OFF
:
1723 if (ftruncate(fd
, offset
) != 0) {
1725 error_setg_errno(errp
, -result
, "Could not resize file");
1730 error_setg(errp
, "Unsupported preallocation mode: %s",
1731 PreallocMode_lookup
[prealloc
]);
1737 if (ftruncate(fd
, current_length
) < 0) {
1738 error_report("Failed to restore old file length: %s",
1747 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
,
1748 PreallocMode prealloc
, Error
**errp
)
1750 BDRVRawState
*s
= bs
->opaque
;
1754 if (fstat(s
->fd
, &st
)) {
1756 error_setg_errno(errp
, -ret
, "Failed to fstat() the file");
1760 if (S_ISREG(st
.st_mode
)) {
1761 return raw_regular_truncate(s
->fd
, offset
, prealloc
, errp
);
1764 if (prealloc
!= PREALLOC_MODE_OFF
) {
1765 error_setg(errp
, "Preallocation mode '%s' unsupported for this "
1766 "non-regular file", PreallocMode_lookup
[prealloc
]);
1770 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1771 if (offset
> raw_getlength(bs
)) {
1772 error_setg(errp
, "Cannot grow device files");
1776 error_setg(errp
, "Resizing this file is not supported");
1784 static int64_t raw_getlength(BlockDriverState
*bs
)
1786 BDRVRawState
*s
= bs
->opaque
;
1792 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1793 struct disklabel dl
;
1795 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1797 return (uint64_t)dl
.d_secsize
*
1798 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1802 #elif defined(__NetBSD__)
1803 static int64_t raw_getlength(BlockDriverState
*bs
)
1805 BDRVRawState
*s
= bs
->opaque
;
1811 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1812 struct dkwedge_info dkw
;
1814 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1815 return dkw
.dkw_size
* 512;
1817 struct disklabel dl
;
1819 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1821 return (uint64_t)dl
.d_secsize
*
1822 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1827 #elif defined(__sun__)
1828 static int64_t raw_getlength(BlockDriverState
*bs
)
1830 BDRVRawState
*s
= bs
->opaque
;
1831 struct dk_minfo minfo
;
1841 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1843 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1845 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1849 * There are reports that lseek on some devices fails, but
1850 * irc discussion said that contingency on contingency was overkill.
1852 size
= lseek(s
->fd
, 0, SEEK_END
);
1858 #elif defined(CONFIG_BSD)
1859 static int64_t raw_getlength(BlockDriverState
*bs
)
1861 BDRVRawState
*s
= bs
->opaque
;
1865 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1874 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1877 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1878 #ifdef DIOCGMEDIASIZE
1879 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1880 #elif defined(DIOCGPART)
1883 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1884 size
= pi
.media_size
;
1890 #if defined(__APPLE__) && defined(__MACH__)
1892 uint64_t sectors
= 0;
1893 uint32_t sector_size
= 0;
1895 if (ioctl(fd
, DKIOCGETBLOCKCOUNT
, §ors
) == 0
1896 && ioctl(fd
, DKIOCGETBLOCKSIZE
, §or_size
) == 0) {
1897 size
= sectors
* sector_size
;
1899 size
= lseek(fd
, 0LL, SEEK_END
);
1906 size
= lseek(fd
, 0LL, SEEK_END
);
1911 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1914 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1915 if (size
== 2048LL * (unsigned)-1)
1917 /* XXX no disc? maybe we need to reopen... */
1918 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1925 size
= lseek(fd
, 0, SEEK_END
);
1933 static int64_t raw_getlength(BlockDriverState
*bs
)
1935 BDRVRawState
*s
= bs
->opaque
;
1944 size
= lseek(s
->fd
, 0, SEEK_END
);
1952 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
1955 BDRVRawState
*s
= bs
->opaque
;
1957 if (fstat(s
->fd
, &st
) < 0) {
1960 return (int64_t)st
.st_blocks
* 512;
1963 static int raw_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
1967 int64_t total_size
= 0;
1969 PreallocMode prealloc
;
1971 Error
*local_err
= NULL
;
1973 strstart(filename
, "file:", &filename
);
1975 /* Read out options */
1976 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
1978 nocow
= qemu_opt_get_bool(opts
, BLOCK_OPT_NOCOW
, false);
1979 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
1980 prealloc
= qapi_enum_parse(PreallocMode_lookup
, buf
,
1981 PREALLOC_MODE__MAX
, PREALLOC_MODE_OFF
,
1985 error_propagate(errp
, local_err
);
1990 fd
= qemu_open(filename
, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
,
1994 error_setg_errno(errp
, -result
, "Could not create file");
2000 /* Set NOCOW flag to solve performance issue on fs like btrfs.
2001 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2002 * will be ignored since any failure of this operation should not
2003 * block the left work.
2006 if (ioctl(fd
, FS_IOC_GETFLAGS
, &attr
) == 0) {
2007 attr
|= FS_NOCOW_FL
;
2008 ioctl(fd
, FS_IOC_SETFLAGS
, &attr
);
2013 result
= raw_regular_truncate(fd
, total_size
, prealloc
, errp
);
2019 if (qemu_close(fd
) != 0 && result
== 0) {
2021 error_setg_errno(errp
, -result
, "Could not close the new file");
2028 * Find allocation range in @bs around offset @start.
2029 * May change underlying file descriptor's file offset.
2030 * If @start is not in a hole, store @start in @data, and the
2031 * beginning of the next hole in @hole, and return 0.
2032 * If @start is in a non-trailing hole, store @start in @hole and the
2033 * beginning of the next non-hole in @data, and return 0.
2034 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
2035 * If we can't find out, return a negative errno other than -ENXIO.
2037 static int find_allocation(BlockDriverState
*bs
, off_t start
,
2038 off_t
*data
, off_t
*hole
)
2040 #if defined SEEK_HOLE && defined SEEK_DATA
2041 BDRVRawState
*s
= bs
->opaque
;
2046 * D1. offs == start: start is in data
2047 * D2. offs > start: start is in a hole, next data at offs
2048 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
2049 * or start is beyond EOF
2050 * If the latter happens, the file has been truncated behind
2051 * our back since we opened it. All bets are off then.
2052 * Treating like a trailing hole is simplest.
2053 * D4. offs < 0, errno != ENXIO: we learned nothing
2055 offs
= lseek(s
->fd
, start
, SEEK_DATA
);
2057 return -errno
; /* D3 or D4 */
2059 assert(offs
>= start
);
2062 /* D2: in hole, next data at offs */
2068 /* D1: in data, end not yet known */
2072 * H1. offs == start: start is in a hole
2073 * If this happens here, a hole has been dug behind our back
2074 * since the previous lseek().
2075 * H2. offs > start: either start is in data, next hole at offs,
2076 * or start is in trailing hole, EOF at offs
2077 * Linux treats trailing holes like any other hole: offs ==
2078 * start. Solaris seeks to EOF instead: offs > start (blech).
2079 * If that happens here, a hole has been dug behind our back
2080 * since the previous lseek().
2081 * H3. offs < 0, errno = ENXIO: start is beyond EOF
2082 * If this happens, the file has been truncated behind our
2083 * back since we opened it. Treat it like a trailing hole.
2084 * H4. offs < 0, errno != ENXIO: we learned nothing
2085 * Pretend we know nothing at all, i.e. "forget" about D1.
2087 offs
= lseek(s
->fd
, start
, SEEK_HOLE
);
2089 return -errno
; /* D1 and (H3 or H4) */
2091 assert(offs
>= start
);
2095 * D1 and H2: either in data, next hole at offs, or it was in
2096 * data but is now in a trailing hole. In the latter case,
2097 * all bets are off. Treating it as if it there was data all
2098 * the way to EOF is safe, so simply do that.
2113 * Returns the allocation status of the specified sectors.
2115 * If 'sector_num' is beyond the end of the disk image the return value is 0
2116 * and 'pnum' is set to 0.
2118 * 'pnum' is set to the number of sectors (including and immediately following
2119 * the specified sector) that are known to be in the same
2120 * allocated/unallocated state.
2122 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
2123 * beyond the end of the disk image it will be clamped.
2125 static int64_t coroutine_fn
raw_co_get_block_status(BlockDriverState
*bs
,
2127 int nb_sectors
, int *pnum
,
2128 BlockDriverState
**file
)
2130 off_t start
, data
= 0, hole
= 0;
2139 start
= sector_num
* BDRV_SECTOR_SIZE
;
2140 total_size
= bdrv_getlength(bs
);
2141 if (total_size
< 0) {
2143 } else if (start
>= total_size
) {
2146 } else if (start
+ nb_sectors
* BDRV_SECTOR_SIZE
> total_size
) {
2147 nb_sectors
= DIV_ROUND_UP(total_size
- start
, BDRV_SECTOR_SIZE
);
2150 ret
= find_allocation(bs
, start
, &data
, &hole
);
2151 if (ret
== -ENXIO
) {
2154 ret
= BDRV_BLOCK_ZERO
;
2155 } else if (ret
< 0) {
2156 /* No info available, so pretend there are no holes */
2158 ret
= BDRV_BLOCK_DATA
;
2159 } else if (data
== start
) {
2160 /* On a data extent, compute sectors to the end of the extent,
2161 * possibly including a partial sector at EOF. */
2162 *pnum
= MIN(nb_sectors
, DIV_ROUND_UP(hole
- start
, BDRV_SECTOR_SIZE
));
2163 ret
= BDRV_BLOCK_DATA
;
2165 /* On a hole, compute sectors to the beginning of the next extent. */
2166 assert(hole
== start
);
2167 *pnum
= MIN(nb_sectors
, (data
- start
) / BDRV_SECTOR_SIZE
);
2168 ret
= BDRV_BLOCK_ZERO
;
2171 return ret
| BDRV_BLOCK_OFFSET_VALID
| start
;
2174 static coroutine_fn BlockAIOCB
*raw_aio_pdiscard(BlockDriverState
*bs
,
2175 int64_t offset
, int bytes
,
2176 BlockCompletionFunc
*cb
, void *opaque
)
2178 BDRVRawState
*s
= bs
->opaque
;
2180 return paio_submit(bs
, s
->fd
, offset
, NULL
, bytes
,
2181 cb
, opaque
, QEMU_AIO_DISCARD
);
2184 static int coroutine_fn
raw_co_pwrite_zeroes(
2185 BlockDriverState
*bs
, int64_t offset
,
2186 int bytes
, BdrvRequestFlags flags
)
2188 BDRVRawState
*s
= bs
->opaque
;
2190 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
2191 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, bytes
,
2192 QEMU_AIO_WRITE_ZEROES
);
2193 } else if (s
->discard_zeroes
) {
2194 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, bytes
,
2200 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2202 BDRVRawState
*s
= bs
->opaque
;
2204 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
2205 bdi
->can_write_zeroes_with_unmap
= s
->discard_zeroes
;
2209 static QemuOptsList raw_create_opts
= {
2210 .name
= "raw-create-opts",
2211 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
2214 .name
= BLOCK_OPT_SIZE
,
2215 .type
= QEMU_OPT_SIZE
,
2216 .help
= "Virtual disk size"
2219 .name
= BLOCK_OPT_NOCOW
,
2220 .type
= QEMU_OPT_BOOL
,
2221 .help
= "Turn off copy-on-write (valid only on btrfs)"
2224 .name
= BLOCK_OPT_PREALLOC
,
2225 .type
= QEMU_OPT_STRING
,
2226 .help
= "Preallocation mode (allowed values: off, falloc, full)"
2228 { /* end of list */ }
2232 static int raw_check_perm(BlockDriverState
*bs
, uint64_t perm
, uint64_t shared
,
2235 return raw_handle_perm_lock(bs
, RAW_PL_PREPARE
, perm
, shared
, errp
);
2238 static void raw_set_perm(BlockDriverState
*bs
, uint64_t perm
, uint64_t shared
)
2240 BDRVRawState
*s
= bs
->opaque
;
2241 raw_handle_perm_lock(bs
, RAW_PL_COMMIT
, perm
, shared
, NULL
);
2243 s
->shared_perm
= shared
;
2246 static void raw_abort_perm_update(BlockDriverState
*bs
)
2248 raw_handle_perm_lock(bs
, RAW_PL_ABORT
, 0, 0, NULL
);
2251 BlockDriver bdrv_file
= {
2252 .format_name
= "file",
2253 .protocol_name
= "file",
2254 .instance_size
= sizeof(BDRVRawState
),
2255 .bdrv_needs_filename
= true,
2256 .bdrv_probe
= NULL
, /* no probe for protocols */
2257 .bdrv_parse_filename
= raw_parse_filename
,
2258 .bdrv_file_open
= raw_open
,
2259 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2260 .bdrv_reopen_commit
= raw_reopen_commit
,
2261 .bdrv_reopen_abort
= raw_reopen_abort
,
2262 .bdrv_close
= raw_close
,
2263 .bdrv_create
= raw_create
,
2264 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
2265 .bdrv_co_get_block_status
= raw_co_get_block_status
,
2266 .bdrv_co_pwrite_zeroes
= raw_co_pwrite_zeroes
,
2268 .bdrv_co_preadv
= raw_co_preadv
,
2269 .bdrv_co_pwritev
= raw_co_pwritev
,
2270 .bdrv_aio_flush
= raw_aio_flush
,
2271 .bdrv_aio_pdiscard
= raw_aio_pdiscard
,
2272 .bdrv_refresh_limits
= raw_refresh_limits
,
2273 .bdrv_io_plug
= raw_aio_plug
,
2274 .bdrv_io_unplug
= raw_aio_unplug
,
2276 .bdrv_truncate
= raw_truncate
,
2277 .bdrv_getlength
= raw_getlength
,
2278 .bdrv_get_info
= raw_get_info
,
2279 .bdrv_get_allocated_file_size
2280 = raw_get_allocated_file_size
,
2281 .bdrv_check_perm
= raw_check_perm
,
2282 .bdrv_set_perm
= raw_set_perm
,
2283 .bdrv_abort_perm_update
= raw_abort_perm_update
,
2284 .create_opts
= &raw_create_opts
,
2287 /***********************************************/
2290 #if defined(__APPLE__) && defined(__MACH__)
2291 static kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
2292 CFIndex maxPathSize
, int flags
);
2293 static char *FindEjectableOpticalMedia(io_iterator_t
*mediaIterator
)
2295 kern_return_t kernResult
= KERN_FAILURE
;
2296 mach_port_t masterPort
;
2297 CFMutableDictionaryRef classesToMatch
;
2298 const char *matching_array
[] = {kIODVDMediaClass
, kIOCDMediaClass
};
2299 char *mediaType
= NULL
;
2301 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
2302 if ( KERN_SUCCESS
!= kernResult
) {
2303 printf( "IOMasterPort returned %d\n", kernResult
);
2307 for (index
= 0; index
< ARRAY_SIZE(matching_array
); index
++) {
2308 classesToMatch
= IOServiceMatching(matching_array
[index
]);
2309 if (classesToMatch
== NULL
) {
2310 error_report("IOServiceMatching returned NULL for %s",
2311 matching_array
[index
]);
2314 CFDictionarySetValue(classesToMatch
, CFSTR(kIOMediaEjectableKey
),
2316 kernResult
= IOServiceGetMatchingServices(masterPort
, classesToMatch
,
2318 if (kernResult
!= KERN_SUCCESS
) {
2319 error_report("Note: IOServiceGetMatchingServices returned %d",
2324 /* If a match was found, leave the loop */
2325 if (*mediaIterator
!= 0) {
2326 DPRINTF("Matching using %s\n", matching_array
[index
]);
2327 mediaType
= g_strdup(matching_array
[index
]);
2334 kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
2335 CFIndex maxPathSize
, int flags
)
2337 io_object_t nextMedia
;
2338 kern_return_t kernResult
= KERN_FAILURE
;
2340 nextMedia
= IOIteratorNext( mediaIterator
);
2343 CFTypeRef bsdPathAsCFString
;
2344 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
2345 if ( bsdPathAsCFString
) {
2346 size_t devPathLength
;
2347 strcpy( bsdPath
, _PATH_DEV
);
2348 if (flags
& BDRV_O_NOCACHE
) {
2349 strcat(bsdPath
, "r");
2351 devPathLength
= strlen( bsdPath
);
2352 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
2353 kernResult
= KERN_SUCCESS
;
2355 CFRelease( bsdPathAsCFString
);
2357 IOObjectRelease( nextMedia
);
2363 /* Sets up a real cdrom for use in QEMU */
2364 static bool setup_cdrom(char *bsd_path
, Error
**errp
)
2366 int index
, num_of_test_partitions
= 2, fd
;
2367 char test_partition
[MAXPATHLEN
];
2368 bool partition_found
= false;
2370 /* look for a working partition */
2371 for (index
= 0; index
< num_of_test_partitions
; index
++) {
2372 snprintf(test_partition
, sizeof(test_partition
), "%ss%d", bsd_path
,
2374 fd
= qemu_open(test_partition
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
2376 partition_found
= true;
2382 /* if a working partition on the device was not found */
2383 if (partition_found
== false) {
2384 error_setg(errp
, "Failed to find a working partition on disc");
2386 DPRINTF("Using %s as optical disc\n", test_partition
);
2387 pstrcpy(bsd_path
, MAXPATHLEN
, test_partition
);
2389 return partition_found
;
2392 /* Prints directions on mounting and unmounting a device */
2393 static void print_unmounting_directions(const char *file_name
)
2395 error_report("If device %s is mounted on the desktop, unmount"
2396 " it first before using it in QEMU", file_name
);
2397 error_report("Command to unmount device: diskutil unmountDisk %s",
2399 error_report("Command to mount device: diskutil mountDisk %s", file_name
);
2402 #endif /* defined(__APPLE__) && defined(__MACH__) */
2404 static int hdev_probe_device(const char *filename
)
2408 /* allow a dedicated CD-ROM driver to match with a higher priority */
2409 if (strstart(filename
, "/dev/cdrom", NULL
))
2412 if (stat(filename
, &st
) >= 0 &&
2413 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
2420 static int check_hdev_writable(BDRVRawState
*s
)
2422 #if defined(BLKROGET)
2423 /* Linux block devices can be configured "read-only" using blockdev(8).
2424 * This is independent of device node permissions and therefore open(2)
2425 * with O_RDWR succeeds. Actual writes fail with EPERM.
2427 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
2428 * check for read-only block devices so that Linux block devices behave
2434 if (fstat(s
->fd
, &st
)) {
2438 if (!S_ISBLK(st
.st_mode
)) {
2442 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
2449 #endif /* defined(BLKROGET) */
2453 static void hdev_parse_filename(const char *filename
, QDict
*options
,
2456 bdrv_parse_filename_strip_prefix(filename
, "host_device:", options
);
2459 static bool hdev_is_sg(BlockDriverState
*bs
)
2462 #if defined(__linux__)
2464 BDRVRawState
*s
= bs
->opaque
;
2466 struct sg_scsi_id scsiid
;
2470 if (stat(bs
->filename
, &st
) < 0 || !S_ISCHR(st
.st_mode
)) {
2474 ret
= ioctl(s
->fd
, SG_GET_VERSION_NUM
, &sg_version
);
2479 ret
= ioctl(s
->fd
, SG_GET_SCSI_ID
, &scsiid
);
2481 DPRINTF("SG device found: type=%d, version=%d\n",
2482 scsiid
.scsi_type
, sg_version
);
2491 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2494 BDRVRawState
*s
= bs
->opaque
;
2495 Error
*local_err
= NULL
;
2498 #if defined(__APPLE__) && defined(__MACH__)
2500 * Caution: while qdict_get_str() is fine, getting non-string types
2501 * would require more care. When @options come from -blockdev or
2502 * blockdev_add, its members are typed according to the QAPI
2503 * schema, but when they come from -drive, they're all QString.
2505 const char *filename
= qdict_get_str(options
, "filename");
2506 char bsd_path
[MAXPATHLEN
] = "";
2507 bool error_occurred
= false;
2509 /* If using a real cdrom */
2510 if (strcmp(filename
, "/dev/cdrom") == 0) {
2511 char *mediaType
= NULL
;
2512 kern_return_t ret_val
;
2513 io_iterator_t mediaIterator
= 0;
2515 mediaType
= FindEjectableOpticalMedia(&mediaIterator
);
2516 if (mediaType
== NULL
) {
2517 error_setg(errp
, "Please make sure your CD/DVD is in the optical"
2519 error_occurred
= true;
2520 goto hdev_open_Mac_error
;
2523 ret_val
= GetBSDPath(mediaIterator
, bsd_path
, sizeof(bsd_path
), flags
);
2524 if (ret_val
!= KERN_SUCCESS
) {
2525 error_setg(errp
, "Could not get BSD path for optical drive");
2526 error_occurred
= true;
2527 goto hdev_open_Mac_error
;
2530 /* If a real optical drive was not found */
2531 if (bsd_path
[0] == '\0') {
2532 error_setg(errp
, "Failed to obtain bsd path for optical drive");
2533 error_occurred
= true;
2534 goto hdev_open_Mac_error
;
2537 /* If using a cdrom disc and finding a partition on the disc failed */
2538 if (strncmp(mediaType
, kIOCDMediaClass
, 9) == 0 &&
2539 setup_cdrom(bsd_path
, errp
) == false) {
2540 print_unmounting_directions(bsd_path
);
2541 error_occurred
= true;
2542 goto hdev_open_Mac_error
;
2545 qdict_put_str(options
, "filename", bsd_path
);
2547 hdev_open_Mac_error
:
2549 if (mediaIterator
) {
2550 IOObjectRelease(mediaIterator
);
2552 if (error_occurred
) {
2556 #endif /* defined(__APPLE__) && defined(__MACH__) */
2558 s
->type
= FTYPE_FILE
;
2560 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2562 error_propagate(errp
, local_err
);
2563 #if defined(__APPLE__) && defined(__MACH__)
2565 filename
= bsd_path
;
2567 /* if a physical device experienced an error while being opened */
2568 if (strncmp(filename
, "/dev/", 5) == 0) {
2569 print_unmounting_directions(filename
);
2571 #endif /* defined(__APPLE__) && defined(__MACH__) */
2575 /* Since this does ioctl the device must be already opened */
2576 bs
->sg
= hdev_is_sg(bs
);
2578 if (flags
& BDRV_O_RDWR
) {
2579 ret
= check_hdev_writable(s
);
2582 error_setg_errno(errp
, -ret
, "The device is not writable");
2590 #if defined(__linux__)
2592 static BlockAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
2593 unsigned long int req
, void *buf
,
2594 BlockCompletionFunc
*cb
, void *opaque
)
2596 BDRVRawState
*s
= bs
->opaque
;
2597 RawPosixAIOData
*acb
;
2600 if (fd_open(bs
) < 0)
2603 acb
= g_new(RawPosixAIOData
, 1);
2605 acb
->aio_type
= QEMU_AIO_IOCTL
;
2606 acb
->aio_fildes
= s
->fd
;
2607 acb
->aio_offset
= 0;
2608 acb
->aio_ioctl_buf
= buf
;
2609 acb
->aio_ioctl_cmd
= req
;
2610 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
2611 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
2615 static int fd_open(BlockDriverState
*bs
)
2617 BDRVRawState
*s
= bs
->opaque
;
2619 /* this is just to ensure s->fd is sane (its called by io ops) */
2625 static coroutine_fn BlockAIOCB
*hdev_aio_pdiscard(BlockDriverState
*bs
,
2626 int64_t offset
, int bytes
,
2627 BlockCompletionFunc
*cb
, void *opaque
)
2629 BDRVRawState
*s
= bs
->opaque
;
2631 if (fd_open(bs
) < 0) {
2634 return paio_submit(bs
, s
->fd
, offset
, NULL
, bytes
,
2635 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2638 static coroutine_fn
int hdev_co_pwrite_zeroes(BlockDriverState
*bs
,
2639 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
2641 BDRVRawState
*s
= bs
->opaque
;
2648 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
2649 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, bytes
,
2650 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
2651 } else if (s
->discard_zeroes
) {
2652 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, bytes
,
2653 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2658 static int hdev_create(const char *filename
, QemuOpts
*opts
,
2663 struct stat stat_buf
;
2664 int64_t total_size
= 0;
2667 /* This function is used by both protocol block drivers and therefore either
2668 * of these prefixes may be given.
2669 * The return value has to be stored somewhere, otherwise this is an error
2670 * due to -Werror=unused-value. */
2672 strstart(filename
, "host_device:", &filename
) ||
2673 strstart(filename
, "host_cdrom:" , &filename
);
2677 ret
= raw_normalize_devicepath(&filename
);
2679 error_setg_errno(errp
, -ret
, "Could not normalize device path");
2683 /* Read out options */
2684 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2687 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
2690 error_setg_errno(errp
, -ret
, "Could not open device");
2694 if (fstat(fd
, &stat_buf
) < 0) {
2696 error_setg_errno(errp
, -ret
, "Could not stat device");
2697 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
2699 "The given file is neither a block nor a character device");
2701 } else if (lseek(fd
, 0, SEEK_END
) < total_size
) {
2702 error_setg(errp
, "Device is too small");
2710 static BlockDriver bdrv_host_device
= {
2711 .format_name
= "host_device",
2712 .protocol_name
= "host_device",
2713 .instance_size
= sizeof(BDRVRawState
),
2714 .bdrv_needs_filename
= true,
2715 .bdrv_probe_device
= hdev_probe_device
,
2716 .bdrv_parse_filename
= hdev_parse_filename
,
2717 .bdrv_file_open
= hdev_open
,
2718 .bdrv_close
= raw_close
,
2719 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2720 .bdrv_reopen_commit
= raw_reopen_commit
,
2721 .bdrv_reopen_abort
= raw_reopen_abort
,
2722 .bdrv_create
= hdev_create
,
2723 .create_opts
= &raw_create_opts
,
2724 .bdrv_co_pwrite_zeroes
= hdev_co_pwrite_zeroes
,
2726 .bdrv_co_preadv
= raw_co_preadv
,
2727 .bdrv_co_pwritev
= raw_co_pwritev
,
2728 .bdrv_aio_flush
= raw_aio_flush
,
2729 .bdrv_aio_pdiscard
= hdev_aio_pdiscard
,
2730 .bdrv_refresh_limits
= raw_refresh_limits
,
2731 .bdrv_io_plug
= raw_aio_plug
,
2732 .bdrv_io_unplug
= raw_aio_unplug
,
2734 .bdrv_truncate
= raw_truncate
,
2735 .bdrv_getlength
= raw_getlength
,
2736 .bdrv_get_info
= raw_get_info
,
2737 .bdrv_get_allocated_file_size
2738 = raw_get_allocated_file_size
,
2739 .bdrv_check_perm
= raw_check_perm
,
2740 .bdrv_set_perm
= raw_set_perm
,
2741 .bdrv_abort_perm_update
= raw_abort_perm_update
,
2742 .bdrv_probe_blocksizes
= hdev_probe_blocksizes
,
2743 .bdrv_probe_geometry
= hdev_probe_geometry
,
2745 /* generic scsi device */
2747 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2751 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2752 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2755 bdrv_parse_filename_strip_prefix(filename
, "host_cdrom:", options
);
2760 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2763 BDRVRawState
*s
= bs
->opaque
;
2767 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2768 return raw_open_common(bs
, options
, flags
, O_NONBLOCK
, errp
);
2771 static int cdrom_probe_device(const char *filename
)
2777 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2781 ret
= fstat(fd
, &st
);
2782 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2786 /* Attempt to detect via a CDROM specific ioctl */
2787 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2797 static bool cdrom_is_inserted(BlockDriverState
*bs
)
2799 BDRVRawState
*s
= bs
->opaque
;
2802 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2803 return ret
== CDS_DISC_OK
;
2806 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2808 BDRVRawState
*s
= bs
->opaque
;
2811 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2812 perror("CDROMEJECT");
2814 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2815 perror("CDROMEJECT");
2819 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2821 BDRVRawState
*s
= bs
->opaque
;
2823 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2825 * Note: an error can happen if the distribution automatically
2828 /* perror("CDROM_LOCKDOOR"); */
2832 static BlockDriver bdrv_host_cdrom
= {
2833 .format_name
= "host_cdrom",
2834 .protocol_name
= "host_cdrom",
2835 .instance_size
= sizeof(BDRVRawState
),
2836 .bdrv_needs_filename
= true,
2837 .bdrv_probe_device
= cdrom_probe_device
,
2838 .bdrv_parse_filename
= cdrom_parse_filename
,
2839 .bdrv_file_open
= cdrom_open
,
2840 .bdrv_close
= raw_close
,
2841 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2842 .bdrv_reopen_commit
= raw_reopen_commit
,
2843 .bdrv_reopen_abort
= raw_reopen_abort
,
2844 .bdrv_create
= hdev_create
,
2845 .create_opts
= &raw_create_opts
,
2848 .bdrv_co_preadv
= raw_co_preadv
,
2849 .bdrv_co_pwritev
= raw_co_pwritev
,
2850 .bdrv_aio_flush
= raw_aio_flush
,
2851 .bdrv_refresh_limits
= raw_refresh_limits
,
2852 .bdrv_io_plug
= raw_aio_plug
,
2853 .bdrv_io_unplug
= raw_aio_unplug
,
2855 .bdrv_truncate
= raw_truncate
,
2856 .bdrv_getlength
= raw_getlength
,
2857 .has_variable_length
= true,
2858 .bdrv_get_allocated_file_size
2859 = raw_get_allocated_file_size
,
2861 /* removable device support */
2862 .bdrv_is_inserted
= cdrom_is_inserted
,
2863 .bdrv_eject
= cdrom_eject
,
2864 .bdrv_lock_medium
= cdrom_lock_medium
,
2866 /* generic scsi device */
2867 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2869 #endif /* __linux__ */
2871 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2872 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2875 BDRVRawState
*s
= bs
->opaque
;
2876 Error
*local_err
= NULL
;
2881 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2883 error_propagate(errp
, local_err
);
2887 /* make sure the door isn't locked at this time */
2888 ioctl(s
->fd
, CDIOCALLOW
);
2892 static int cdrom_probe_device(const char *filename
)
2894 if (strstart(filename
, "/dev/cd", NULL
) ||
2895 strstart(filename
, "/dev/acd", NULL
))
2900 static int cdrom_reopen(BlockDriverState
*bs
)
2902 BDRVRawState
*s
= bs
->opaque
;
2906 * Force reread of possibly changed/newly loaded disc,
2907 * FreeBSD seems to not notice sometimes...
2911 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
2918 /* make sure the door isn't locked at this time */
2919 ioctl(s
->fd
, CDIOCALLOW
);
2923 static bool cdrom_is_inserted(BlockDriverState
*bs
)
2925 return raw_getlength(bs
) > 0;
2928 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2930 BDRVRawState
*s
= bs
->opaque
;
2935 (void) ioctl(s
->fd
, CDIOCALLOW
);
2938 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
2939 perror("CDIOCEJECT");
2941 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
2942 perror("CDIOCCLOSE");
2948 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2950 BDRVRawState
*s
= bs
->opaque
;
2954 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
2956 * Note: an error can happen if the distribution automatically
2959 /* perror("CDROM_LOCKDOOR"); */
2963 static BlockDriver bdrv_host_cdrom
= {
2964 .format_name
= "host_cdrom",
2965 .protocol_name
= "host_cdrom",
2966 .instance_size
= sizeof(BDRVRawState
),
2967 .bdrv_needs_filename
= true,
2968 .bdrv_probe_device
= cdrom_probe_device
,
2969 .bdrv_parse_filename
= cdrom_parse_filename
,
2970 .bdrv_file_open
= cdrom_open
,
2971 .bdrv_close
= raw_close
,
2972 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2973 .bdrv_reopen_commit
= raw_reopen_commit
,
2974 .bdrv_reopen_abort
= raw_reopen_abort
,
2975 .bdrv_create
= hdev_create
,
2976 .create_opts
= &raw_create_opts
,
2978 .bdrv_co_preadv
= raw_co_preadv
,
2979 .bdrv_co_pwritev
= raw_co_pwritev
,
2980 .bdrv_aio_flush
= raw_aio_flush
,
2981 .bdrv_refresh_limits
= raw_refresh_limits
,
2982 .bdrv_io_plug
= raw_aio_plug
,
2983 .bdrv_io_unplug
= raw_aio_unplug
,
2985 .bdrv_truncate
= raw_truncate
,
2986 .bdrv_getlength
= raw_getlength
,
2987 .has_variable_length
= true,
2988 .bdrv_get_allocated_file_size
2989 = raw_get_allocated_file_size
,
2991 /* removable device support */
2992 .bdrv_is_inserted
= cdrom_is_inserted
,
2993 .bdrv_eject
= cdrom_eject
,
2994 .bdrv_lock_medium
= cdrom_lock_medium
,
2996 #endif /* __FreeBSD__ */
2998 static void bdrv_file_init(void)
3001 * Register all the drivers. Note that order is important, the driver
3002 * registered last will get probed first.
3004 bdrv_register(&bdrv_file
);
3005 bdrv_register(&bdrv_host_device
);
3007 bdrv_register(&bdrv_host_cdrom
);
3009 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3010 bdrv_register(&bdrv_host_cdrom
);
3014 block_init(bdrv_file_init
);