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
25 #include "qemu/osdep.h"
26 #include "qapi/error.h"
27 #include "qemu/cutils.h"
28 #include "qemu/error-report.h"
29 #include "block/block_int.h"
30 #include "qemu/module.h"
31 #include "qemu/option.h"
33 #include "block/thread-pool.h"
35 #include "block/raw-aio.h"
36 #include "qapi/qmp/qdict.h"
37 #include "qapi/qmp/qstring.h"
39 #include "scsi/pr-manager.h"
40 #include "scsi/constants.h"
42 #if defined(__APPLE__) && (__MACH__)
44 #include <sys/param.h>
45 #include <IOKit/IOKitLib.h>
46 #include <IOKit/IOBSD.h>
47 #include <IOKit/storage/IOMediaBSDClient.h>
48 #include <IOKit/storage/IOMedia.h>
49 #include <IOKit/storage/IOCDMedia.h>
50 //#include <IOKit/storage/IOCDTypes.h>
51 #include <IOKit/storage/IODVDMedia.h>
52 #include <CoreFoundation/CoreFoundation.h>
56 #define _POSIX_PTHREAD_SEMANTICS 1
60 #include <sys/ioctl.h>
61 #include <sys/param.h>
62 #include <linux/cdrom.h>
65 #include <linux/hdreg.h>
71 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
74 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
75 #include <linux/falloc.h>
77 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
83 #include <sys/ioctl.h>
84 #include <sys/disklabel.h>
89 #include <sys/ioctl.h>
90 #include <sys/disklabel.h>
96 #include <sys/ioctl.h>
97 #include <sys/diskslice.h>
104 //#define DEBUG_BLOCK
107 # define DEBUG_BLOCK_PRINT 1
109 # define DEBUG_BLOCK_PRINT 0
111 #define DPRINTF(fmt, ...) \
113 if (DEBUG_BLOCK_PRINT) { \
114 printf(fmt, ## __VA_ARGS__); \
118 /* OS X does not have O_DSYNC */
121 #define O_DSYNC O_SYNC
122 #elif defined(O_FSYNC)
123 #define O_DSYNC O_FSYNC
127 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
129 #define O_DIRECT O_DSYNC
135 #define MAX_BLOCKSIZE 4096
137 /* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
138 * leaving a few more bytes for its future use. */
139 #define RAW_LOCK_PERM_BASE 100
140 #define RAW_LOCK_SHARED_BASE 200
142 typedef struct BDRVRawState
{
150 /* The current permissions. */
152 uint64_t shared_perm
;
158 bool has_write_zeroes
:1;
159 bool discard_zeroes
:1;
160 bool use_linux_aio
:1;
161 bool page_cache_inconsistent
:1;
163 bool needs_alignment
;
168 typedef struct BDRVRawReopenState
{
171 } BDRVRawReopenState
;
173 static int fd_open(BlockDriverState
*bs
);
174 static int64_t raw_getlength(BlockDriverState
*bs
);
176 typedef struct RawPosixAIOData
{
177 BlockDriverState
*bs
;
180 struct iovec
*aio_iov
;
185 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
190 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
191 static int cdrom_reopen(BlockDriverState
*bs
);
194 #if defined(__NetBSD__)
195 static int raw_normalize_devicepath(const char **filename
)
197 static char namebuf
[PATH_MAX
];
198 const char *dp
, *fname
;
202 dp
= strrchr(fname
, '/');
203 if (lstat(fname
, &sb
) < 0) {
204 fprintf(stderr
, "%s: stat failed: %s\n",
205 fname
, strerror(errno
));
209 if (!S_ISBLK(sb
.st_mode
)) {
214 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
216 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
217 (int)(dp
- fname
), fname
, dp
+ 1);
219 fprintf(stderr
, "%s is a block device", fname
);
221 fprintf(stderr
, ", using %s\n", *filename
);
226 static int raw_normalize_devicepath(const char **filename
)
233 * Get logical block size via ioctl. On success store it in @sector_size_p.
235 static int probe_logical_blocksize(int fd
, unsigned int *sector_size_p
)
237 unsigned int sector_size
;
238 bool success
= false;
242 static const unsigned long ioctl_list
[] = {
246 #ifdef DKIOCGETBLOCKSIZE
249 #ifdef DIOCGSECTORSIZE
254 /* Try a few ioctls to get the right size */
255 for (i
= 0; i
< (int)ARRAY_SIZE(ioctl_list
); i
++) {
256 if (ioctl(fd
, ioctl_list
[i
], §or_size
) >= 0) {
257 *sector_size_p
= sector_size
;
262 return success
? 0 : -errno
;
266 * Get physical block size of @fd.
267 * On success, store it in @blk_size and return 0.
268 * On failure, return -errno.
270 static int probe_physical_blocksize(int fd
, unsigned int *blk_size
)
273 if (ioctl(fd
, BLKPBSZGET
, blk_size
) < 0) {
282 /* Check if read is allowed with given memory buffer and length.
284 * This function is used to check O_DIRECT memory buffer and request alignment.
286 static bool raw_is_io_aligned(int fd
, void *buf
, size_t len
)
288 ssize_t ret
= pread(fd
, buf
, len
, 0);
295 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
296 * other errors (e.g. real I/O error), which could happen on a failed
297 * drive, since we only care about probing alignment.
299 if (errno
!= EINVAL
) {
307 static void raw_probe_alignment(BlockDriverState
*bs
, int fd
, Error
**errp
)
309 BDRVRawState
*s
= bs
->opaque
;
311 size_t max_align
= MAX(MAX_BLOCKSIZE
, getpagesize());
313 /* For SCSI generic devices the alignment is not really used.
314 With buffered I/O, we don't have any restrictions. */
315 if (bdrv_is_sg(bs
) || !s
->needs_alignment
) {
316 bs
->bl
.request_alignment
= 1;
321 bs
->bl
.request_alignment
= 0;
323 /* Let's try to use the logical blocksize for the alignment. */
324 if (probe_logical_blocksize(fd
, &bs
->bl
.request_alignment
) < 0) {
325 bs
->bl
.request_alignment
= 0;
330 if (xfsctl(NULL
, fd
, XFS_IOC_DIOINFO
, &da
) >= 0) {
331 bs
->bl
.request_alignment
= da
.d_miniosz
;
332 /* The kernel returns wrong information for d_mem */
333 /* s->buf_align = da.d_mem; */
338 /* If we could not get the sizes so far, we can only guess them */
341 buf
= qemu_memalign(max_align
, 2 * max_align
);
342 for (align
= 512; align
<= max_align
; align
<<= 1) {
343 if (raw_is_io_aligned(fd
, buf
+ align
, max_align
)) {
344 s
->buf_align
= align
;
351 if (!bs
->bl
.request_alignment
) {
353 buf
= qemu_memalign(s
->buf_align
, max_align
);
354 for (align
= 512; align
<= max_align
; align
<<= 1) {
355 if (raw_is_io_aligned(fd
, buf
, align
)) {
356 bs
->bl
.request_alignment
= align
;
363 if (!s
->buf_align
|| !bs
->bl
.request_alignment
) {
364 error_setg(errp
, "Could not find working O_DIRECT alignment");
365 error_append_hint(errp
, "Try cache.direct=off\n");
369 static void raw_parse_flags(int bdrv_flags
, int *open_flags
)
371 assert(open_flags
!= NULL
);
373 *open_flags
|= O_BINARY
;
374 *open_flags
&= ~O_ACCMODE
;
375 if (bdrv_flags
& BDRV_O_RDWR
) {
376 *open_flags
|= O_RDWR
;
378 *open_flags
|= O_RDONLY
;
381 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
382 * and O_DIRECT for no caching. */
383 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
384 *open_flags
|= O_DIRECT
;
388 static void raw_parse_filename(const char *filename
, QDict
*options
,
391 bdrv_parse_filename_strip_prefix(filename
, "file:", options
);
394 static QemuOptsList raw_runtime_opts
= {
396 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
400 .type
= QEMU_OPT_STRING
,
401 .help
= "File name of the image",
405 .type
= QEMU_OPT_STRING
,
406 .help
= "host AIO implementation (threads, native)",
410 .type
= QEMU_OPT_STRING
,
411 .help
= "file locking mode (on/off/auto, default: auto)",
414 .name
= "pr-manager",
415 .type
= QEMU_OPT_STRING
,
416 .help
= "id of persistent reservation manager object (default: none)",
418 { /* end of list */ }
422 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
423 int bdrv_flags
, int open_flags
, Error
**errp
)
425 BDRVRawState
*s
= bs
->opaque
;
427 Error
*local_err
= NULL
;
428 const char *filename
= NULL
;
430 BlockdevAioOptions aio
, aio_default
;
435 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
436 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
438 error_propagate(errp
, local_err
);
443 filename
= qemu_opt_get(opts
, "filename");
445 ret
= raw_normalize_devicepath(&filename
);
447 error_setg_errno(errp
, -ret
, "Could not normalize device path");
451 aio_default
= (bdrv_flags
& BDRV_O_NATIVE_AIO
)
452 ? BLOCKDEV_AIO_OPTIONS_NATIVE
453 : BLOCKDEV_AIO_OPTIONS_THREADS
;
454 aio
= qapi_enum_parse(&BlockdevAioOptions_lookup
,
455 qemu_opt_get(opts
, "aio"),
456 aio_default
, &local_err
);
458 error_propagate(errp
, local_err
);
462 s
->use_linux_aio
= (aio
== BLOCKDEV_AIO_OPTIONS_NATIVE
);
464 locking
= qapi_enum_parse(&OnOffAuto_lookup
,
465 qemu_opt_get(opts
, "locking"),
466 ON_OFF_AUTO_AUTO
, &local_err
);
468 error_propagate(errp
, local_err
);
475 if (!qemu_has_ofd_lock()) {
477 "File lock requested but OFD locking syscall is "
478 "unavailable, falling back to POSIX file locks.\n"
479 "Due to the implementation, locks can be lost "
483 case ON_OFF_AUTO_OFF
:
486 case ON_OFF_AUTO_AUTO
:
487 s
->use_lock
= qemu_has_ofd_lock();
493 str
= qemu_opt_get(opts
, "pr-manager");
495 s
->pr_mgr
= pr_manager_lookup(str
, &local_err
);
497 error_propagate(errp
, local_err
);
503 s
->open_flags
= open_flags
;
504 raw_parse_flags(bdrv_flags
, &s
->open_flags
);
507 fd
= qemu_open(filename
, s
->open_flags
, 0644);
510 error_setg_errno(errp
, errno
, "Could not open '%s'", filename
);
520 fd
= qemu_open(filename
, s
->open_flags
);
523 error_setg_errno(errp
, errno
, "Could not open '%s' for locking",
531 s
->shared_perm
= BLK_PERM_ALL
;
533 #ifdef CONFIG_LINUX_AIO
534 /* Currently Linux does AIO only for files opened with O_DIRECT */
535 if (s
->use_linux_aio
&& !(s
->open_flags
& O_DIRECT
)) {
536 error_setg(errp
, "aio=native was specified, but it requires "
537 "cache.direct=on, which was not specified.");
542 if (s
->use_linux_aio
) {
543 error_setg(errp
, "aio=native was specified, but is not supported "
548 #endif /* !defined(CONFIG_LINUX_AIO) */
550 s
->has_discard
= true;
551 s
->has_write_zeroes
= true;
552 if ((bs
->open_flags
& BDRV_O_NOCACHE
) != 0) {
553 s
->needs_alignment
= true;
556 if (fstat(s
->fd
, &st
) < 0) {
558 error_setg_errno(errp
, errno
, "Could not stat file");
561 if (S_ISREG(st
.st_mode
)) {
562 s
->discard_zeroes
= true;
563 s
->has_fallocate
= true;
565 if (S_ISBLK(st
.st_mode
)) {
566 #ifdef BLKDISCARDZEROES
568 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
569 s
->discard_zeroes
= true;
573 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
574 * not rely on the contents of discarded blocks unless using O_DIRECT.
575 * Same for BLKZEROOUT.
577 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
578 s
->discard_zeroes
= false;
579 s
->has_write_zeroes
= false;
584 if (S_ISCHR(st
.st_mode
)) {
586 * The file is a char device (disk), which on FreeBSD isn't behind
587 * a pager, so force all requests to be aligned. This is needed
588 * so QEMU makes sure all IO operations on the device are aligned
589 * to sector size, or else FreeBSD will reject them with EINVAL.
591 s
->needs_alignment
= true;
596 if (platform_test_xfs_fd(s
->fd
)) {
601 bs
->supported_zero_flags
= s
->discard_zeroes
? BDRV_REQ_MAY_UNMAP
: 0;
604 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
611 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
614 BDRVRawState
*s
= bs
->opaque
;
616 s
->type
= FTYPE_FILE
;
617 return raw_open_common(bs
, options
, flags
, 0, errp
);
626 #define PERM_FOREACH(i) \
627 for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
629 /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
630 * file; if @unlock == true, also unlock the unneeded bytes.
631 * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
633 static int raw_apply_lock_bytes(BDRVRawState
*s
,
634 uint64_t perm_lock_bits
,
635 uint64_t shared_perm_lock_bits
,
636 bool unlock
, Error
**errp
)
642 int off
= RAW_LOCK_PERM_BASE
+ i
;
643 if (perm_lock_bits
& (1ULL << i
)) {
644 ret
= qemu_lock_fd(s
->lock_fd
, off
, 1, false);
646 error_setg(errp
, "Failed to lock byte %d", off
);
650 ret
= qemu_unlock_fd(s
->lock_fd
, off
, 1);
652 error_setg(errp
, "Failed to unlock byte %d", off
);
658 int off
= RAW_LOCK_SHARED_BASE
+ i
;
659 if (shared_perm_lock_bits
& (1ULL << i
)) {
660 ret
= qemu_lock_fd(s
->lock_fd
, off
, 1, false);
662 error_setg(errp
, "Failed to lock byte %d", off
);
666 ret
= qemu_unlock_fd(s
->lock_fd
, off
, 1);
668 error_setg(errp
, "Failed to unlock byte %d", off
);
676 /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
677 static int raw_check_lock_bytes(BDRVRawState
*s
,
678 uint64_t perm
, uint64_t shared_perm
,
685 int off
= RAW_LOCK_SHARED_BASE
+ i
;
686 uint64_t p
= 1ULL << i
;
688 ret
= qemu_lock_fd_test(s
->lock_fd
, off
, 1, true);
690 char *perm_name
= bdrv_perm_names(p
);
692 "Failed to get \"%s\" lock",
695 error_append_hint(errp
,
696 "Is another process using the image?\n");
702 int off
= RAW_LOCK_PERM_BASE
+ i
;
703 uint64_t p
= 1ULL << i
;
704 if (!(shared_perm
& p
)) {
705 ret
= qemu_lock_fd_test(s
->lock_fd
, off
, 1, true);
707 char *perm_name
= bdrv_perm_names(p
);
709 "Failed to get shared \"%s\" lock",
712 error_append_hint(errp
,
713 "Is another process using the image?\n");
721 static int raw_handle_perm_lock(BlockDriverState
*bs
,
723 uint64_t new_perm
, uint64_t new_shared
,
726 BDRVRawState
*s
= bs
->opaque
;
728 Error
*local_err
= NULL
;
734 if (bdrv_get_flags(bs
) & BDRV_O_INACTIVE
) {
738 assert(s
->lock_fd
> 0);
742 ret
= raw_apply_lock_bytes(s
, s
->perm
| new_perm
,
743 ~s
->shared_perm
| ~new_shared
,
746 ret
= raw_check_lock_bytes(s
, new_perm
, new_shared
, errp
);
752 /* fall through to unlock bytes. */
754 raw_apply_lock_bytes(s
, s
->perm
, ~s
->shared_perm
, true, &local_err
);
756 /* Theoretically the above call only unlocks bytes and it cannot
757 * fail. Something weird happened, report it.
759 error_report_err(local_err
);
763 raw_apply_lock_bytes(s
, new_perm
, ~new_shared
, true, &local_err
);
765 /* Theoretically the above call only unlocks bytes and it cannot
766 * fail. Something weird happened, report it.
768 error_report_err(local_err
);
775 static int raw_reopen_prepare(BDRVReopenState
*state
,
776 BlockReopenQueue
*queue
, Error
**errp
)
779 BDRVRawReopenState
*rs
;
781 Error
*local_err
= NULL
;
783 assert(state
!= NULL
);
784 assert(state
->bs
!= NULL
);
786 s
= state
->bs
->opaque
;
788 state
->opaque
= g_new0(BDRVRawReopenState
, 1);
791 if (s
->type
== FTYPE_CD
) {
792 rs
->open_flags
|= O_NONBLOCK
;
795 raw_parse_flags(state
->flags
, &rs
->open_flags
);
799 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
801 fcntl_flags
|= O_NOATIME
;
805 /* Not all operating systems have O_ASYNC, and those that don't
806 * will not let us track the state into rs->open_flags (typically
807 * you achieve the same effect with an ioctl, for example I_SETSIG
808 * on Solaris). But we do not use O_ASYNC, so that's fine.
810 assert((s
->open_flags
& O_ASYNC
) == 0);
813 if ((rs
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
814 /* dup the original fd */
815 rs
->fd
= qemu_dup(s
->fd
);
817 ret
= fcntl_setfl(rs
->fd
, rs
->open_flags
);
825 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
827 const char *normalized_filename
= state
->bs
->filename
;
828 ret
= raw_normalize_devicepath(&normalized_filename
);
830 error_setg_errno(errp
, -ret
, "Could not normalize device path");
832 assert(!(rs
->open_flags
& O_CREAT
));
833 rs
->fd
= qemu_open(normalized_filename
, rs
->open_flags
);
835 error_setg_errno(errp
, errno
, "Could not reopen file");
841 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
842 * alignment with the new fd. */
844 raw_probe_alignment(state
->bs
, rs
->fd
, &local_err
);
848 error_propagate(errp
, local_err
);
856 static void raw_reopen_commit(BDRVReopenState
*state
)
858 BDRVRawReopenState
*rs
= state
->opaque
;
859 BDRVRawState
*s
= state
->bs
->opaque
;
861 s
->open_flags
= rs
->open_flags
;
866 g_free(state
->opaque
);
867 state
->opaque
= NULL
;
871 static void raw_reopen_abort(BDRVReopenState
*state
)
873 BDRVRawReopenState
*rs
= state
->opaque
;
875 /* nothing to do if NULL, we didn't get far enough */
884 g_free(state
->opaque
);
885 state
->opaque
= NULL
;
888 static int hdev_get_max_transfer_length(BlockDriverState
*bs
, int fd
)
892 short max_sectors
= 0;
893 if (bs
->sg
&& ioctl(fd
, BLKSECTGET
, &max_bytes
) == 0) {
895 } else if (!bs
->sg
&& ioctl(fd
, BLKSECTGET
, &max_sectors
) == 0) {
896 return max_sectors
<< BDRV_SECTOR_BITS
;
905 static int hdev_get_max_segments(const struct stat
*st
)
915 sysfspath
= g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
916 major(st
->st_rdev
), minor(st
->st_rdev
));
917 fd
= open(sysfspath
, O_RDONLY
);
923 ret
= read(fd
, buf
, sizeof(buf
) - 1);
924 } while (ret
== -1 && errno
== EINTR
);
928 } else if (ret
== 0) {
933 /* The file is ended with '\n', pass 'end' to accept that. */
934 ret
= qemu_strtol(buf
, &end
, 10, &max_segments
);
935 if (ret
== 0 && end
&& *end
== '\n') {
950 static void raw_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
952 BDRVRawState
*s
= bs
->opaque
;
955 if (!fstat(s
->fd
, &st
)) {
956 if (S_ISBLK(st
.st_mode
) || S_ISCHR(st
.st_mode
)) {
957 int ret
= hdev_get_max_transfer_length(bs
, s
->fd
);
958 if (ret
> 0 && ret
<= BDRV_REQUEST_MAX_BYTES
) {
959 bs
->bl
.max_transfer
= pow2floor(ret
);
961 ret
= hdev_get_max_segments(&st
);
963 bs
->bl
.max_transfer
= MIN(bs
->bl
.max_transfer
,
964 ret
* getpagesize());
969 raw_probe_alignment(bs
, s
->fd
, errp
);
970 bs
->bl
.min_mem_alignment
= s
->buf_align
;
971 bs
->bl
.opt_mem_alignment
= MAX(s
->buf_align
, getpagesize());
974 static int check_for_dasd(int fd
)
977 struct dasd_information2_t info
= {0};
979 return ioctl(fd
, BIODASDINFO2
, &info
);
986 * Try to get @bs's logical and physical block size.
987 * On success, store them in @bsz and return zero.
988 * On failure, return negative errno.
990 static int hdev_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
992 BDRVRawState
*s
= bs
->opaque
;
995 /* If DASD, get blocksizes */
996 if (check_for_dasd(s
->fd
) < 0) {
999 ret
= probe_logical_blocksize(s
->fd
, &bsz
->log
);
1003 return probe_physical_blocksize(s
->fd
, &bsz
->phys
);
1007 * Try to get @bs's geometry: cyls, heads, sectors.
1008 * On success, store them in @geo and return 0.
1009 * On failure return -errno.
1010 * (Allows block driver to assign default geometry values that guest sees)
1013 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
1015 BDRVRawState
*s
= bs
->opaque
;
1016 struct hd_geometry ioctl_geo
= {0};
1018 /* If DASD, get its geometry */
1019 if (check_for_dasd(s
->fd
) < 0) {
1022 if (ioctl(s
->fd
, HDIO_GETGEO
, &ioctl_geo
) < 0) {
1025 /* HDIO_GETGEO may return success even though geo contains zeros
1026 (e.g. certain multipath setups) */
1027 if (!ioctl_geo
.heads
|| !ioctl_geo
.sectors
|| !ioctl_geo
.cylinders
) {
1030 /* Do not return a geometry for partition */
1031 if (ioctl_geo
.start
!= 0) {
1034 geo
->heads
= ioctl_geo
.heads
;
1035 geo
->sectors
= ioctl_geo
.sectors
;
1036 geo
->cylinders
= ioctl_geo
.cylinders
;
1040 #else /* __linux__ */
1041 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
1047 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
1051 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
1059 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
1061 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1064 if (s
->page_cache_inconsistent
) {
1068 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
1070 /* There is no clear definition of the semantics of a failing fsync(),
1071 * so we may have to assume the worst. The sad truth is that this
1072 * assumption is correct for Linux. Some pages are now probably marked
1073 * clean in the page cache even though they are inconsistent with the
1074 * on-disk contents. The next fdatasync() call would succeed, but no
1075 * further writeback attempt will be made. We can't get back to a state
1076 * in which we know what is on disk (we would have to rewrite
1077 * everything that was touched since the last fdatasync() at least), so
1078 * make bdrv_flush() fail permanently. Given that the behaviour isn't
1079 * really defined, I have little hope that other OSes are doing better.
1081 * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1083 if ((s
->open_flags
& O_DIRECT
) == 0) {
1084 s
->page_cache_inconsistent
= true;
1091 #ifdef CONFIG_PREADV
1093 static bool preadv_present
= true;
1096 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1098 return preadv(fd
, iov
, nr_iov
, offset
);
1102 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1104 return pwritev(fd
, iov
, nr_iov
, offset
);
1109 static bool preadv_present
= false;
1112 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1118 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1125 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
1130 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
1131 len
= qemu_pwritev(aiocb
->aio_fildes
,
1136 len
= qemu_preadv(aiocb
->aio_fildes
,
1140 } while (len
== -1 && errno
== EINTR
);
1149 * Read/writes the data to/from a given linear buffer.
1151 * Returns the number of bytes handles or -errno in case of an error. Short
1152 * reads are only returned if the end of the file is reached.
1154 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
1159 while (offset
< aiocb
->aio_nbytes
) {
1160 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1161 len
= pwrite(aiocb
->aio_fildes
,
1162 (const char *)buf
+ offset
,
1163 aiocb
->aio_nbytes
- offset
,
1164 aiocb
->aio_offset
+ offset
);
1166 len
= pread(aiocb
->aio_fildes
,
1168 aiocb
->aio_nbytes
- offset
,
1169 aiocb
->aio_offset
+ offset
);
1171 if (len
== -1 && errno
== EINTR
) {
1173 } else if (len
== -1 && errno
== EINVAL
&&
1174 (aiocb
->bs
->open_flags
& BDRV_O_NOCACHE
) &&
1175 !(aiocb
->aio_type
& QEMU_AIO_WRITE
) &&
1177 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1178 * after a short read. Assume that O_DIRECT short reads only occur
1179 * at EOF. Therefore this is a short read, not an I/O error.
1182 } else if (len
== -1) {
1185 } else if (len
== 0) {
1194 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
1199 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
1201 * If there is just a single buffer, and it is properly aligned
1202 * we can just use plain pread/pwrite without any problems.
1204 if (aiocb
->aio_niov
== 1) {
1205 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
1208 * We have more than one iovec, and all are properly aligned.
1210 * Try preadv/pwritev first and fall back to linearizing the
1211 * buffer if it's not supported.
1213 if (preadv_present
) {
1214 nbytes
= handle_aiocb_rw_vector(aiocb
);
1215 if (nbytes
== aiocb
->aio_nbytes
||
1216 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
1219 preadv_present
= false;
1223 * XXX(hch): short read/write. no easy way to handle the reminder
1224 * using these interfaces. For now retry using plain
1230 * Ok, we have to do it the hard way, copy all segments into
1231 * a single aligned buffer.
1233 buf
= qemu_try_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
1238 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1242 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
1243 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
1244 p
+= aiocb
->aio_iov
[i
].iov_len
;
1246 assert(p
- buf
== aiocb
->aio_nbytes
);
1249 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
1250 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
1252 size_t count
= aiocb
->aio_nbytes
, copy
;
1255 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
1257 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
1258 copy
= aiocb
->aio_iov
[i
].iov_len
;
1260 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
1261 assert(count
>= copy
);
1273 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1275 struct xfs_flock64 fl
;
1278 memset(&fl
, 0, sizeof(fl
));
1279 fl
.l_whence
= SEEK_SET
;
1280 fl
.l_start
= offset
;
1283 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
1285 DPRINTF("cannot write zero range (%s)\n", strerror(errno
));
1292 static int xfs_discard(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1294 struct xfs_flock64 fl
;
1297 memset(&fl
, 0, sizeof(fl
));
1298 fl
.l_whence
= SEEK_SET
;
1299 fl
.l_start
= offset
;
1302 if (xfsctl(NULL
, s
->fd
, XFS_IOC_UNRESVSP64
, &fl
) < 0) {
1304 DPRINTF("cannot punch hole (%s)\n", strerror(errno
));
1312 static int translate_err(int err
)
1314 if (err
== -ENODEV
|| err
== -ENOSYS
|| err
== -EOPNOTSUPP
||
1321 #ifdef CONFIG_FALLOCATE
1322 static int do_fallocate(int fd
, int mode
, off_t offset
, off_t len
)
1325 if (fallocate(fd
, mode
, offset
, len
) == 0) {
1328 } while (errno
== EINTR
);
1329 return translate_err(-errno
);
1333 static ssize_t
handle_aiocb_write_zeroes_block(RawPosixAIOData
*aiocb
)
1336 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1338 if (!s
->has_write_zeroes
) {
1344 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1345 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
1348 } while (errno
== EINTR
);
1350 ret
= translate_err(-errno
);
1353 if (ret
== -ENOTSUP
) {
1354 s
->has_write_zeroes
= false;
1359 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
1361 #if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1362 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1364 #ifdef CONFIG_FALLOCATE
1368 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1369 return handle_aiocb_write_zeroes_block(aiocb
);
1374 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1378 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1379 if (s
->has_write_zeroes
) {
1380 int ret
= do_fallocate(s
->fd
, FALLOC_FL_ZERO_RANGE
,
1381 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1382 if (ret
== 0 || ret
!= -ENOTSUP
) {
1385 s
->has_write_zeroes
= false;
1389 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1390 if (s
->has_discard
&& s
->has_fallocate
) {
1391 int ret
= do_fallocate(s
->fd
,
1392 FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1393 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1395 ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1396 if (ret
== 0 || ret
!= -ENOTSUP
) {
1399 s
->has_fallocate
= false;
1400 } else if (ret
!= -ENOTSUP
) {
1403 s
->has_discard
= false;
1408 #ifdef CONFIG_FALLOCATE
1409 /* Last resort: we are trying to extend the file with zeroed data. This
1410 * can be done via fallocate(fd, 0) */
1411 len
= bdrv_getlength(aiocb
->bs
);
1412 if (s
->has_fallocate
&& len
>= 0 && aiocb
->aio_offset
>= len
) {
1413 int ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1414 if (ret
== 0 || ret
!= -ENOTSUP
) {
1417 s
->has_fallocate
= false;
1424 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
1426 int ret
= -EOPNOTSUPP
;
1427 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1429 if (!s
->has_discard
) {
1433 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1436 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1437 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
1440 } while (errno
== EINTR
);
1447 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1451 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1452 ret
= do_fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1453 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1457 ret
= translate_err(ret
);
1458 if (ret
== -ENOTSUP
) {
1459 s
->has_discard
= false;
1464 static int aio_worker(void *arg
)
1466 RawPosixAIOData
*aiocb
= arg
;
1469 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
1471 ret
= handle_aiocb_rw(aiocb
);
1472 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1473 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
1474 0, aiocb
->aio_nbytes
- ret
);
1476 ret
= aiocb
->aio_nbytes
;
1478 if (ret
== aiocb
->aio_nbytes
) {
1480 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1484 case QEMU_AIO_WRITE
:
1485 ret
= handle_aiocb_rw(aiocb
);
1486 if (ret
== aiocb
->aio_nbytes
) {
1488 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1492 case QEMU_AIO_FLUSH
:
1493 ret
= handle_aiocb_flush(aiocb
);
1495 case QEMU_AIO_IOCTL
:
1496 ret
= handle_aiocb_ioctl(aiocb
);
1498 case QEMU_AIO_DISCARD
:
1499 ret
= handle_aiocb_discard(aiocb
);
1501 case QEMU_AIO_WRITE_ZEROES
:
1502 ret
= handle_aiocb_write_zeroes(aiocb
);
1505 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
1514 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
1515 int64_t offset
, QEMUIOVector
*qiov
,
1516 int bytes
, int type
)
1518 RawPosixAIOData
*acb
= g_new(RawPosixAIOData
, 1);
1522 acb
->aio_type
= type
;
1523 acb
->aio_fildes
= fd
;
1525 acb
->aio_nbytes
= bytes
;
1526 acb
->aio_offset
= offset
;
1529 acb
->aio_iov
= qiov
->iov
;
1530 acb
->aio_niov
= qiov
->niov
;
1531 assert(qiov
->size
== bytes
);
1534 trace_paio_submit_co(offset
, bytes
, type
);
1535 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1536 return thread_pool_submit_co(pool
, aio_worker
, acb
);
1539 static BlockAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
1540 int64_t offset
, QEMUIOVector
*qiov
, int bytes
,
1541 BlockCompletionFunc
*cb
, void *opaque
, int type
)
1543 RawPosixAIOData
*acb
= g_new(RawPosixAIOData
, 1);
1547 acb
->aio_type
= type
;
1548 acb
->aio_fildes
= fd
;
1550 acb
->aio_nbytes
= bytes
;
1551 acb
->aio_offset
= offset
;
1554 acb
->aio_iov
= qiov
->iov
;
1555 acb
->aio_niov
= qiov
->niov
;
1556 assert(qiov
->size
== acb
->aio_nbytes
);
1559 trace_paio_submit(acb
, opaque
, offset
, bytes
, type
);
1560 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1561 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1564 static int coroutine_fn
raw_co_prw(BlockDriverState
*bs
, uint64_t offset
,
1565 uint64_t bytes
, QEMUIOVector
*qiov
, int type
)
1567 BDRVRawState
*s
= bs
->opaque
;
1569 if (fd_open(bs
) < 0)
1573 * Check if the underlying device requires requests to be aligned,
1574 * and if the request we are trying to submit is aligned or not.
1575 * If this is the case tell the low-level driver that it needs
1576 * to copy the buffer.
1578 if (s
->needs_alignment
) {
1579 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1580 type
|= QEMU_AIO_MISALIGNED
;
1581 #ifdef CONFIG_LINUX_AIO
1582 } else if (s
->use_linux_aio
) {
1583 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1584 assert(qiov
->size
== bytes
);
1585 return laio_co_submit(bs
, aio
, s
->fd
, offset
, qiov
, type
);
1590 return paio_submit_co(bs
, s
->fd
, offset
, qiov
, bytes
, type
);
1593 static int coroutine_fn
raw_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1594 uint64_t bytes
, QEMUIOVector
*qiov
,
1597 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_READ
);
1600 static int coroutine_fn
raw_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1601 uint64_t bytes
, QEMUIOVector
*qiov
,
1605 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_WRITE
);
1608 static void raw_aio_plug(BlockDriverState
*bs
)
1610 #ifdef CONFIG_LINUX_AIO
1611 BDRVRawState
*s
= bs
->opaque
;
1612 if (s
->use_linux_aio
) {
1613 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1614 laio_io_plug(bs
, aio
);
1619 static void raw_aio_unplug(BlockDriverState
*bs
)
1621 #ifdef CONFIG_LINUX_AIO
1622 BDRVRawState
*s
= bs
->opaque
;
1623 if (s
->use_linux_aio
) {
1624 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1625 laio_io_unplug(bs
, aio
);
1630 static BlockAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1631 BlockCompletionFunc
*cb
, void *opaque
)
1633 BDRVRawState
*s
= bs
->opaque
;
1635 if (fd_open(bs
) < 0)
1638 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1641 static void raw_close(BlockDriverState
*bs
)
1643 BDRVRawState
*s
= bs
->opaque
;
1649 if (s
->lock_fd
>= 0) {
1650 qemu_close(s
->lock_fd
);
1656 * Truncates the given regular file @fd to @offset and, when growing, fills the
1657 * new space according to @prealloc.
1659 * Returns: 0 on success, -errno on failure.
1661 static int raw_regular_truncate(int fd
, int64_t offset
, PreallocMode prealloc
,
1665 int64_t current_length
= 0;
1669 if (fstat(fd
, &st
) < 0) {
1671 error_setg_errno(errp
, -result
, "Could not stat file");
1675 current_length
= st
.st_size
;
1676 if (current_length
> offset
&& prealloc
!= PREALLOC_MODE_OFF
) {
1677 error_setg(errp
, "Cannot use preallocation for shrinking files");
1682 #ifdef CONFIG_POSIX_FALLOCATE
1683 case PREALLOC_MODE_FALLOC
:
1685 * Truncating before posix_fallocate() makes it about twice slower on
1686 * file systems that do not support fallocate(), trying to check if a
1687 * block is allocated before allocating it, so don't do that here.
1689 if (offset
!= current_length
) {
1690 result
= -posix_fallocate(fd
, current_length
, offset
- current_length
);
1692 /* posix_fallocate() doesn't set errno. */
1693 error_setg_errno(errp
, -result
,
1694 "Could not preallocate new data");
1701 case PREALLOC_MODE_FULL
:
1703 int64_t num
= 0, left
= offset
- current_length
;
1707 * Knowing the final size from the beginning could allow the file
1708 * system driver to do less allocations and possibly avoid
1709 * fragmentation of the file.
1711 if (ftruncate(fd
, offset
) != 0) {
1713 error_setg_errno(errp
, -result
, "Could not resize file");
1717 buf
= g_malloc0(65536);
1719 seek_result
= lseek(fd
, current_length
, SEEK_SET
);
1720 if (seek_result
< 0) {
1722 error_setg_errno(errp
, -result
,
1723 "Failed to seek to the old end of file");
1728 num
= MIN(left
, 65536);
1729 result
= write(fd
, buf
, num
);
1732 error_setg_errno(errp
, -result
,
1733 "Could not write zeros for preallocation");
1742 error_setg_errno(errp
, -result
,
1743 "Could not flush file to disk");
1749 case PREALLOC_MODE_OFF
:
1750 if (ftruncate(fd
, offset
) != 0) {
1752 error_setg_errno(errp
, -result
, "Could not resize file");
1757 error_setg(errp
, "Unsupported preallocation mode: %s",
1758 PreallocMode_str(prealloc
));
1764 if (ftruncate(fd
, current_length
) < 0) {
1765 error_report("Failed to restore old file length: %s",
1774 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
,
1775 PreallocMode prealloc
, Error
**errp
)
1777 BDRVRawState
*s
= bs
->opaque
;
1781 if (fstat(s
->fd
, &st
)) {
1783 error_setg_errno(errp
, -ret
, "Failed to fstat() the file");
1787 if (S_ISREG(st
.st_mode
)) {
1788 return raw_regular_truncate(s
->fd
, offset
, prealloc
, errp
);
1791 if (prealloc
!= PREALLOC_MODE_OFF
) {
1792 error_setg(errp
, "Preallocation mode '%s' unsupported for this "
1793 "non-regular file", PreallocMode_str(prealloc
));
1797 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1798 if (offset
> raw_getlength(bs
)) {
1799 error_setg(errp
, "Cannot grow device files");
1803 error_setg(errp
, "Resizing this file is not supported");
1811 static int64_t raw_getlength(BlockDriverState
*bs
)
1813 BDRVRawState
*s
= bs
->opaque
;
1819 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1820 struct disklabel dl
;
1822 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1824 return (uint64_t)dl
.d_secsize
*
1825 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1829 #elif defined(__NetBSD__)
1830 static int64_t raw_getlength(BlockDriverState
*bs
)
1832 BDRVRawState
*s
= bs
->opaque
;
1838 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1839 struct dkwedge_info dkw
;
1841 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1842 return dkw
.dkw_size
* 512;
1844 struct disklabel dl
;
1846 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1848 return (uint64_t)dl
.d_secsize
*
1849 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1854 #elif defined(__sun__)
1855 static int64_t raw_getlength(BlockDriverState
*bs
)
1857 BDRVRawState
*s
= bs
->opaque
;
1858 struct dk_minfo minfo
;
1868 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1870 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1872 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1876 * There are reports that lseek on some devices fails, but
1877 * irc discussion said that contingency on contingency was overkill.
1879 size
= lseek(s
->fd
, 0, SEEK_END
);
1885 #elif defined(CONFIG_BSD)
1886 static int64_t raw_getlength(BlockDriverState
*bs
)
1888 BDRVRawState
*s
= bs
->opaque
;
1892 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1901 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1904 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1905 #ifdef DIOCGMEDIASIZE
1906 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1907 #elif defined(DIOCGPART)
1910 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1911 size
= pi
.media_size
;
1917 #if defined(__APPLE__) && defined(__MACH__)
1919 uint64_t sectors
= 0;
1920 uint32_t sector_size
= 0;
1922 if (ioctl(fd
, DKIOCGETBLOCKCOUNT
, §ors
) == 0
1923 && ioctl(fd
, DKIOCGETBLOCKSIZE
, §or_size
) == 0) {
1924 size
= sectors
* sector_size
;
1926 size
= lseek(fd
, 0LL, SEEK_END
);
1933 size
= lseek(fd
, 0LL, SEEK_END
);
1938 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1941 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1942 if (size
== 2048LL * (unsigned)-1)
1944 /* XXX no disc? maybe we need to reopen... */
1945 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1952 size
= lseek(fd
, 0, SEEK_END
);
1960 static int64_t raw_getlength(BlockDriverState
*bs
)
1962 BDRVRawState
*s
= bs
->opaque
;
1971 size
= lseek(s
->fd
, 0, SEEK_END
);
1979 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
1982 BDRVRawState
*s
= bs
->opaque
;
1984 if (fstat(s
->fd
, &st
) < 0) {
1987 return (int64_t)st
.st_blocks
* 512;
1990 static int raw_co_create(BlockdevCreateOptions
*options
, Error
**errp
)
1992 BlockdevCreateOptionsFile
*file_opts
;
1996 /* Validate options and set default values */
1997 assert(options
->driver
== BLOCKDEV_DRIVER_FILE
);
1998 file_opts
= &options
->u
.file
;
2000 if (!file_opts
->has_nocow
) {
2001 file_opts
->nocow
= false;
2003 if (!file_opts
->has_preallocation
) {
2004 file_opts
->preallocation
= PREALLOC_MODE_OFF
;
2008 fd
= qemu_open(file_opts
->filename
, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
,
2012 error_setg_errno(errp
, -result
, "Could not create file");
2016 if (file_opts
->nocow
) {
2018 /* Set NOCOW flag to solve performance issue on fs like btrfs.
2019 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2020 * will be ignored since any failure of this operation should not
2021 * block the left work.
2024 if (ioctl(fd
, FS_IOC_GETFLAGS
, &attr
) == 0) {
2025 attr
|= FS_NOCOW_FL
;
2026 ioctl(fd
, FS_IOC_SETFLAGS
, &attr
);
2031 result
= raw_regular_truncate(fd
, file_opts
->size
, file_opts
->preallocation
,
2038 if (qemu_close(fd
) != 0 && result
== 0) {
2040 error_setg_errno(errp
, -result
, "Could not close the new file");
2046 static int coroutine_fn
raw_co_create_opts(const char *filename
, QemuOpts
*opts
,
2049 BlockdevCreateOptions options
;
2050 int64_t total_size
= 0;
2052 PreallocMode prealloc
;
2054 Error
*local_err
= NULL
;
2056 /* Skip file: protocol prefix */
2057 strstart(filename
, "file:", &filename
);
2059 /* Read out options */
2060 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2062 nocow
= qemu_opt_get_bool(opts
, BLOCK_OPT_NOCOW
, false);
2063 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
2064 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
2065 PREALLOC_MODE_OFF
, &local_err
);
2068 error_propagate(errp
, local_err
);
2072 options
= (BlockdevCreateOptions
) {
2073 .driver
= BLOCKDEV_DRIVER_FILE
,
2075 .filename
= (char *) filename
,
2077 .has_preallocation
= true,
2078 .preallocation
= prealloc
,
2083 return raw_co_create(&options
, errp
);
2087 * Find allocation range in @bs around offset @start.
2088 * May change underlying file descriptor's file offset.
2089 * If @start is not in a hole, store @start in @data, and the
2090 * beginning of the next hole in @hole, and return 0.
2091 * If @start is in a non-trailing hole, store @start in @hole and the
2092 * beginning of the next non-hole in @data, and return 0.
2093 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
2094 * If we can't find out, return a negative errno other than -ENXIO.
2096 static int find_allocation(BlockDriverState
*bs
, off_t start
,
2097 off_t
*data
, off_t
*hole
)
2099 #if defined SEEK_HOLE && defined SEEK_DATA
2100 BDRVRawState
*s
= bs
->opaque
;
2105 * D1. offs == start: start is in data
2106 * D2. offs > start: start is in a hole, next data at offs
2107 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
2108 * or start is beyond EOF
2109 * If the latter happens, the file has been truncated behind
2110 * our back since we opened it. All bets are off then.
2111 * Treating like a trailing hole is simplest.
2112 * D4. offs < 0, errno != ENXIO: we learned nothing
2114 offs
= lseek(s
->fd
, start
, SEEK_DATA
);
2116 return -errno
; /* D3 or D4 */
2120 /* This is not a valid return by lseek(). We are safe to just return
2121 * -EIO in this case, and we'll treat it like D4. */
2126 /* D2: in hole, next data at offs */
2132 /* D1: in data, end not yet known */
2136 * H1. offs == start: start is in a hole
2137 * If this happens here, a hole has been dug behind our back
2138 * since the previous lseek().
2139 * H2. offs > start: either start is in data, next hole at offs,
2140 * or start is in trailing hole, EOF at offs
2141 * Linux treats trailing holes like any other hole: offs ==
2142 * start. Solaris seeks to EOF instead: offs > start (blech).
2143 * If that happens here, a hole has been dug behind our back
2144 * since the previous lseek().
2145 * H3. offs < 0, errno = ENXIO: start is beyond EOF
2146 * If this happens, the file has been truncated behind our
2147 * back since we opened it. Treat it like a trailing hole.
2148 * H4. offs < 0, errno != ENXIO: we learned nothing
2149 * Pretend we know nothing at all, i.e. "forget" about D1.
2151 offs
= lseek(s
->fd
, start
, SEEK_HOLE
);
2153 return -errno
; /* D1 and (H3 or H4) */
2157 /* This is not a valid return by lseek(). We are safe to just return
2158 * -EIO in this case, and we'll treat it like H4. */
2164 * D1 and H2: either in data, next hole at offs, or it was in
2165 * data but is now in a trailing hole. In the latter case,
2166 * all bets are off. Treating it as if it there was data all
2167 * the way to EOF is safe, so simply do that.
2182 * Returns the allocation status of the specified offset.
2184 * The block layer guarantees 'offset' and 'bytes' are within bounds.
2186 * 'pnum' is set to the number of bytes (including and immediately following
2187 * the specified offset) that are known to be in the same
2188 * allocated/unallocated state.
2190 * 'bytes' is the max value 'pnum' should be set to.
2192 static int coroutine_fn
raw_co_block_status(BlockDriverState
*bs
,
2195 int64_t bytes
, int64_t *pnum
,
2197 BlockDriverState
**file
)
2199 off_t data
= 0, hole
= 0;
2211 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
2214 ret
= find_allocation(bs
, offset
, &data
, &hole
);
2215 if (ret
== -ENXIO
) {
2218 ret
= BDRV_BLOCK_ZERO
;
2219 } else if (ret
< 0) {
2220 /* No info available, so pretend there are no holes */
2222 ret
= BDRV_BLOCK_DATA
;
2223 } else if (data
== offset
) {
2224 /* On a data extent, compute bytes to the end of the extent,
2225 * possibly including a partial sector at EOF. */
2226 *pnum
= MIN(bytes
, hole
- offset
);
2227 ret
= BDRV_BLOCK_DATA
;
2229 /* On a hole, compute bytes to the beginning of the next extent. */
2230 assert(hole
== offset
);
2231 *pnum
= MIN(bytes
, data
- offset
);
2232 ret
= BDRV_BLOCK_ZERO
;
2236 return ret
| BDRV_BLOCK_OFFSET_VALID
;
2239 static coroutine_fn BlockAIOCB
*raw_aio_pdiscard(BlockDriverState
*bs
,
2240 int64_t offset
, int bytes
,
2241 BlockCompletionFunc
*cb
, void *opaque
)
2243 BDRVRawState
*s
= bs
->opaque
;
2245 return paio_submit(bs
, s
->fd
, offset
, NULL
, bytes
,
2246 cb
, opaque
, QEMU_AIO_DISCARD
);
2249 static int coroutine_fn
raw_co_pwrite_zeroes(
2250 BlockDriverState
*bs
, int64_t offset
,
2251 int bytes
, BdrvRequestFlags flags
)
2253 BDRVRawState
*s
= bs
->opaque
;
2255 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
2256 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, bytes
,
2257 QEMU_AIO_WRITE_ZEROES
);
2258 } else if (s
->discard_zeroes
) {
2259 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, bytes
,
2265 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2267 BDRVRawState
*s
= bs
->opaque
;
2269 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
2273 static QemuOptsList raw_create_opts
= {
2274 .name
= "raw-create-opts",
2275 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
2278 .name
= BLOCK_OPT_SIZE
,
2279 .type
= QEMU_OPT_SIZE
,
2280 .help
= "Virtual disk size"
2283 .name
= BLOCK_OPT_NOCOW
,
2284 .type
= QEMU_OPT_BOOL
,
2285 .help
= "Turn off copy-on-write (valid only on btrfs)"
2288 .name
= BLOCK_OPT_PREALLOC
,
2289 .type
= QEMU_OPT_STRING
,
2290 .help
= "Preallocation mode (allowed values: off, falloc, full)"
2292 { /* end of list */ }
2296 static int raw_check_perm(BlockDriverState
*bs
, uint64_t perm
, uint64_t shared
,
2299 return raw_handle_perm_lock(bs
, RAW_PL_PREPARE
, perm
, shared
, errp
);
2302 static void raw_set_perm(BlockDriverState
*bs
, uint64_t perm
, uint64_t shared
)
2304 BDRVRawState
*s
= bs
->opaque
;
2305 raw_handle_perm_lock(bs
, RAW_PL_COMMIT
, perm
, shared
, NULL
);
2307 s
->shared_perm
= shared
;
2310 static void raw_abort_perm_update(BlockDriverState
*bs
)
2312 raw_handle_perm_lock(bs
, RAW_PL_ABORT
, 0, 0, NULL
);
2315 BlockDriver bdrv_file
= {
2316 .format_name
= "file",
2317 .protocol_name
= "file",
2318 .instance_size
= sizeof(BDRVRawState
),
2319 .bdrv_needs_filename
= true,
2320 .bdrv_probe
= NULL
, /* no probe for protocols */
2321 .bdrv_parse_filename
= raw_parse_filename
,
2322 .bdrv_file_open
= raw_open
,
2323 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2324 .bdrv_reopen_commit
= raw_reopen_commit
,
2325 .bdrv_reopen_abort
= raw_reopen_abort
,
2326 .bdrv_close
= raw_close
,
2327 .bdrv_co_create
= raw_co_create
,
2328 .bdrv_co_create_opts
= raw_co_create_opts
,
2329 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
2330 .bdrv_co_block_status
= raw_co_block_status
,
2331 .bdrv_co_pwrite_zeroes
= raw_co_pwrite_zeroes
,
2333 .bdrv_co_preadv
= raw_co_preadv
,
2334 .bdrv_co_pwritev
= raw_co_pwritev
,
2335 .bdrv_aio_flush
= raw_aio_flush
,
2336 .bdrv_aio_pdiscard
= raw_aio_pdiscard
,
2337 .bdrv_refresh_limits
= raw_refresh_limits
,
2338 .bdrv_io_plug
= raw_aio_plug
,
2339 .bdrv_io_unplug
= raw_aio_unplug
,
2341 .bdrv_truncate
= raw_truncate
,
2342 .bdrv_getlength
= raw_getlength
,
2343 .bdrv_get_info
= raw_get_info
,
2344 .bdrv_get_allocated_file_size
2345 = raw_get_allocated_file_size
,
2346 .bdrv_check_perm
= raw_check_perm
,
2347 .bdrv_set_perm
= raw_set_perm
,
2348 .bdrv_abort_perm_update
= raw_abort_perm_update
,
2349 .create_opts
= &raw_create_opts
,
2352 /***********************************************/
2355 #if defined(__APPLE__) && defined(__MACH__)
2356 static kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
2357 CFIndex maxPathSize
, int flags
);
2358 static char *FindEjectableOpticalMedia(io_iterator_t
*mediaIterator
)
2360 kern_return_t kernResult
= KERN_FAILURE
;
2361 mach_port_t masterPort
;
2362 CFMutableDictionaryRef classesToMatch
;
2363 const char *matching_array
[] = {kIODVDMediaClass
, kIOCDMediaClass
};
2364 char *mediaType
= NULL
;
2366 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
2367 if ( KERN_SUCCESS
!= kernResult
) {
2368 printf( "IOMasterPort returned %d\n", kernResult
);
2372 for (index
= 0; index
< ARRAY_SIZE(matching_array
); index
++) {
2373 classesToMatch
= IOServiceMatching(matching_array
[index
]);
2374 if (classesToMatch
== NULL
) {
2375 error_report("IOServiceMatching returned NULL for %s",
2376 matching_array
[index
]);
2379 CFDictionarySetValue(classesToMatch
, CFSTR(kIOMediaEjectableKey
),
2381 kernResult
= IOServiceGetMatchingServices(masterPort
, classesToMatch
,
2383 if (kernResult
!= KERN_SUCCESS
) {
2384 error_report("Note: IOServiceGetMatchingServices returned %d",
2389 /* If a match was found, leave the loop */
2390 if (*mediaIterator
!= 0) {
2391 DPRINTF("Matching using %s\n", matching_array
[index
]);
2392 mediaType
= g_strdup(matching_array
[index
]);
2399 kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
2400 CFIndex maxPathSize
, int flags
)
2402 io_object_t nextMedia
;
2403 kern_return_t kernResult
= KERN_FAILURE
;
2405 nextMedia
= IOIteratorNext( mediaIterator
);
2408 CFTypeRef bsdPathAsCFString
;
2409 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
2410 if ( bsdPathAsCFString
) {
2411 size_t devPathLength
;
2412 strcpy( bsdPath
, _PATH_DEV
);
2413 if (flags
& BDRV_O_NOCACHE
) {
2414 strcat(bsdPath
, "r");
2416 devPathLength
= strlen( bsdPath
);
2417 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
2418 kernResult
= KERN_SUCCESS
;
2420 CFRelease( bsdPathAsCFString
);
2422 IOObjectRelease( nextMedia
);
2428 /* Sets up a real cdrom for use in QEMU */
2429 static bool setup_cdrom(char *bsd_path
, Error
**errp
)
2431 int index
, num_of_test_partitions
= 2, fd
;
2432 char test_partition
[MAXPATHLEN
];
2433 bool partition_found
= false;
2435 /* look for a working partition */
2436 for (index
= 0; index
< num_of_test_partitions
; index
++) {
2437 snprintf(test_partition
, sizeof(test_partition
), "%ss%d", bsd_path
,
2439 fd
= qemu_open(test_partition
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
2441 partition_found
= true;
2447 /* if a working partition on the device was not found */
2448 if (partition_found
== false) {
2449 error_setg(errp
, "Failed to find a working partition on disc");
2451 DPRINTF("Using %s as optical disc\n", test_partition
);
2452 pstrcpy(bsd_path
, MAXPATHLEN
, test_partition
);
2454 return partition_found
;
2457 /* Prints directions on mounting and unmounting a device */
2458 static void print_unmounting_directions(const char *file_name
)
2460 error_report("If device %s is mounted on the desktop, unmount"
2461 " it first before using it in QEMU", file_name
);
2462 error_report("Command to unmount device: diskutil unmountDisk %s",
2464 error_report("Command to mount device: diskutil mountDisk %s", file_name
);
2467 #endif /* defined(__APPLE__) && defined(__MACH__) */
2469 static int hdev_probe_device(const char *filename
)
2473 /* allow a dedicated CD-ROM driver to match with a higher priority */
2474 if (strstart(filename
, "/dev/cdrom", NULL
))
2477 if (stat(filename
, &st
) >= 0 &&
2478 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
2485 static int check_hdev_writable(BDRVRawState
*s
)
2487 #if defined(BLKROGET)
2488 /* Linux block devices can be configured "read-only" using blockdev(8).
2489 * This is independent of device node permissions and therefore open(2)
2490 * with O_RDWR succeeds. Actual writes fail with EPERM.
2492 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
2493 * check for read-only block devices so that Linux block devices behave
2499 if (fstat(s
->fd
, &st
)) {
2503 if (!S_ISBLK(st
.st_mode
)) {
2507 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
2514 #endif /* defined(BLKROGET) */
2518 static void hdev_parse_filename(const char *filename
, QDict
*options
,
2521 bdrv_parse_filename_strip_prefix(filename
, "host_device:", options
);
2524 static bool hdev_is_sg(BlockDriverState
*bs
)
2527 #if defined(__linux__)
2529 BDRVRawState
*s
= bs
->opaque
;
2531 struct sg_scsi_id scsiid
;
2535 if (stat(bs
->filename
, &st
) < 0 || !S_ISCHR(st
.st_mode
)) {
2539 ret
= ioctl(s
->fd
, SG_GET_VERSION_NUM
, &sg_version
);
2544 ret
= ioctl(s
->fd
, SG_GET_SCSI_ID
, &scsiid
);
2546 DPRINTF("SG device found: type=%d, version=%d\n",
2547 scsiid
.scsi_type
, sg_version
);
2556 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2559 BDRVRawState
*s
= bs
->opaque
;
2560 Error
*local_err
= NULL
;
2563 #if defined(__APPLE__) && defined(__MACH__)
2565 * Caution: while qdict_get_str() is fine, getting non-string types
2566 * would require more care. When @options come from -blockdev or
2567 * blockdev_add, its members are typed according to the QAPI
2568 * schema, but when they come from -drive, they're all QString.
2570 const char *filename
= qdict_get_str(options
, "filename");
2571 char bsd_path
[MAXPATHLEN
] = "";
2572 bool error_occurred
= false;
2574 /* If using a real cdrom */
2575 if (strcmp(filename
, "/dev/cdrom") == 0) {
2576 char *mediaType
= NULL
;
2577 kern_return_t ret_val
;
2578 io_iterator_t mediaIterator
= 0;
2580 mediaType
= FindEjectableOpticalMedia(&mediaIterator
);
2581 if (mediaType
== NULL
) {
2582 error_setg(errp
, "Please make sure your CD/DVD is in the optical"
2584 error_occurred
= true;
2585 goto hdev_open_Mac_error
;
2588 ret_val
= GetBSDPath(mediaIterator
, bsd_path
, sizeof(bsd_path
), flags
);
2589 if (ret_val
!= KERN_SUCCESS
) {
2590 error_setg(errp
, "Could not get BSD path for optical drive");
2591 error_occurred
= true;
2592 goto hdev_open_Mac_error
;
2595 /* If a real optical drive was not found */
2596 if (bsd_path
[0] == '\0') {
2597 error_setg(errp
, "Failed to obtain bsd path for optical drive");
2598 error_occurred
= true;
2599 goto hdev_open_Mac_error
;
2602 /* If using a cdrom disc and finding a partition on the disc failed */
2603 if (strncmp(mediaType
, kIOCDMediaClass
, 9) == 0 &&
2604 setup_cdrom(bsd_path
, errp
) == false) {
2605 print_unmounting_directions(bsd_path
);
2606 error_occurred
= true;
2607 goto hdev_open_Mac_error
;
2610 qdict_put_str(options
, "filename", bsd_path
);
2612 hdev_open_Mac_error
:
2614 if (mediaIterator
) {
2615 IOObjectRelease(mediaIterator
);
2617 if (error_occurred
) {
2621 #endif /* defined(__APPLE__) && defined(__MACH__) */
2623 s
->type
= FTYPE_FILE
;
2625 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2627 error_propagate(errp
, local_err
);
2628 #if defined(__APPLE__) && defined(__MACH__)
2630 filename
= bsd_path
;
2632 /* if a physical device experienced an error while being opened */
2633 if (strncmp(filename
, "/dev/", 5) == 0) {
2634 print_unmounting_directions(filename
);
2636 #endif /* defined(__APPLE__) && defined(__MACH__) */
2640 /* Since this does ioctl the device must be already opened */
2641 bs
->sg
= hdev_is_sg(bs
);
2643 if (flags
& BDRV_O_RDWR
) {
2644 ret
= check_hdev_writable(s
);
2647 error_setg_errno(errp
, -ret
, "The device is not writable");
2655 #if defined(__linux__)
2657 static BlockAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
2658 unsigned long int req
, void *buf
,
2659 BlockCompletionFunc
*cb
, void *opaque
)
2661 BDRVRawState
*s
= bs
->opaque
;
2662 RawPosixAIOData
*acb
;
2665 if (fd_open(bs
) < 0)
2668 if (req
== SG_IO
&& s
->pr_mgr
) {
2669 struct sg_io_hdr
*io_hdr
= buf
;
2670 if (io_hdr
->cmdp
[0] == PERSISTENT_RESERVE_OUT
||
2671 io_hdr
->cmdp
[0] == PERSISTENT_RESERVE_IN
) {
2672 return pr_manager_execute(s
->pr_mgr
, bdrv_get_aio_context(bs
),
2673 s
->fd
, io_hdr
, cb
, opaque
);
2677 acb
= g_new(RawPosixAIOData
, 1);
2679 acb
->aio_type
= QEMU_AIO_IOCTL
;
2680 acb
->aio_fildes
= s
->fd
;
2681 acb
->aio_offset
= 0;
2682 acb
->aio_ioctl_buf
= buf
;
2683 acb
->aio_ioctl_cmd
= req
;
2684 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
2685 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
2689 static int fd_open(BlockDriverState
*bs
)
2691 BDRVRawState
*s
= bs
->opaque
;
2693 /* this is just to ensure s->fd is sane (its called by io ops) */
2699 static coroutine_fn BlockAIOCB
*hdev_aio_pdiscard(BlockDriverState
*bs
,
2700 int64_t offset
, int bytes
,
2701 BlockCompletionFunc
*cb
, void *opaque
)
2703 BDRVRawState
*s
= bs
->opaque
;
2705 if (fd_open(bs
) < 0) {
2708 return paio_submit(bs
, s
->fd
, offset
, NULL
, bytes
,
2709 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2712 static coroutine_fn
int hdev_co_pwrite_zeroes(BlockDriverState
*bs
,
2713 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
2715 BDRVRawState
*s
= bs
->opaque
;
2722 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
2723 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, bytes
,
2724 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
2725 } else if (s
->discard_zeroes
) {
2726 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, bytes
,
2727 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2732 static int coroutine_fn
hdev_co_create_opts(const char *filename
, QemuOpts
*opts
,
2737 struct stat stat_buf
;
2738 int64_t total_size
= 0;
2741 /* This function is used by both protocol block drivers and therefore either
2742 * of these prefixes may be given.
2743 * The return value has to be stored somewhere, otherwise this is an error
2744 * due to -Werror=unused-value. */
2746 strstart(filename
, "host_device:", &filename
) ||
2747 strstart(filename
, "host_cdrom:" , &filename
);
2751 ret
= raw_normalize_devicepath(&filename
);
2753 error_setg_errno(errp
, -ret
, "Could not normalize device path");
2757 /* Read out options */
2758 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2761 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
2764 error_setg_errno(errp
, -ret
, "Could not open device");
2768 if (fstat(fd
, &stat_buf
) < 0) {
2770 error_setg_errno(errp
, -ret
, "Could not stat device");
2771 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
2773 "The given file is neither a block nor a character device");
2775 } else if (lseek(fd
, 0, SEEK_END
) < total_size
) {
2776 error_setg(errp
, "Device is too small");
2780 if (!ret
&& total_size
) {
2781 uint8_t buf
[BDRV_SECTOR_SIZE
] = { 0 };
2782 int64_t zero_size
= MIN(BDRV_SECTOR_SIZE
, total_size
);
2783 if (lseek(fd
, 0, SEEK_SET
) == -1) {
2786 ret
= qemu_write_full(fd
, buf
, zero_size
);
2787 ret
= ret
== zero_size
? 0 : -errno
;
2794 static BlockDriver bdrv_host_device
= {
2795 .format_name
= "host_device",
2796 .protocol_name
= "host_device",
2797 .instance_size
= sizeof(BDRVRawState
),
2798 .bdrv_needs_filename
= true,
2799 .bdrv_probe_device
= hdev_probe_device
,
2800 .bdrv_parse_filename
= hdev_parse_filename
,
2801 .bdrv_file_open
= hdev_open
,
2802 .bdrv_close
= raw_close
,
2803 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2804 .bdrv_reopen_commit
= raw_reopen_commit
,
2805 .bdrv_reopen_abort
= raw_reopen_abort
,
2806 .bdrv_co_create_opts
= hdev_co_create_opts
,
2807 .create_opts
= &raw_create_opts
,
2808 .bdrv_co_pwrite_zeroes
= hdev_co_pwrite_zeroes
,
2810 .bdrv_co_preadv
= raw_co_preadv
,
2811 .bdrv_co_pwritev
= raw_co_pwritev
,
2812 .bdrv_aio_flush
= raw_aio_flush
,
2813 .bdrv_aio_pdiscard
= hdev_aio_pdiscard
,
2814 .bdrv_refresh_limits
= raw_refresh_limits
,
2815 .bdrv_io_plug
= raw_aio_plug
,
2816 .bdrv_io_unplug
= raw_aio_unplug
,
2818 .bdrv_truncate
= raw_truncate
,
2819 .bdrv_getlength
= raw_getlength
,
2820 .bdrv_get_info
= raw_get_info
,
2821 .bdrv_get_allocated_file_size
2822 = raw_get_allocated_file_size
,
2823 .bdrv_check_perm
= raw_check_perm
,
2824 .bdrv_set_perm
= raw_set_perm
,
2825 .bdrv_abort_perm_update
= raw_abort_perm_update
,
2826 .bdrv_probe_blocksizes
= hdev_probe_blocksizes
,
2827 .bdrv_probe_geometry
= hdev_probe_geometry
,
2829 /* generic scsi device */
2831 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2835 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2836 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2839 bdrv_parse_filename_strip_prefix(filename
, "host_cdrom:", options
);
2844 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2847 BDRVRawState
*s
= bs
->opaque
;
2851 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2852 return raw_open_common(bs
, options
, flags
, O_NONBLOCK
, errp
);
2855 static int cdrom_probe_device(const char *filename
)
2861 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
2865 ret
= fstat(fd
, &st
);
2866 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
2870 /* Attempt to detect via a CDROM specific ioctl */
2871 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2881 static bool cdrom_is_inserted(BlockDriverState
*bs
)
2883 BDRVRawState
*s
= bs
->opaque
;
2886 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
2887 return ret
== CDS_DISC_OK
;
2890 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
2892 BDRVRawState
*s
= bs
->opaque
;
2895 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
2896 perror("CDROMEJECT");
2898 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
2899 perror("CDROMEJECT");
2903 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
2905 BDRVRawState
*s
= bs
->opaque
;
2907 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
2909 * Note: an error can happen if the distribution automatically
2912 /* perror("CDROM_LOCKDOOR"); */
2916 static BlockDriver bdrv_host_cdrom
= {
2917 .format_name
= "host_cdrom",
2918 .protocol_name
= "host_cdrom",
2919 .instance_size
= sizeof(BDRVRawState
),
2920 .bdrv_needs_filename
= true,
2921 .bdrv_probe_device
= cdrom_probe_device
,
2922 .bdrv_parse_filename
= cdrom_parse_filename
,
2923 .bdrv_file_open
= cdrom_open
,
2924 .bdrv_close
= raw_close
,
2925 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2926 .bdrv_reopen_commit
= raw_reopen_commit
,
2927 .bdrv_reopen_abort
= raw_reopen_abort
,
2928 .bdrv_co_create_opts
= hdev_co_create_opts
,
2929 .create_opts
= &raw_create_opts
,
2932 .bdrv_co_preadv
= raw_co_preadv
,
2933 .bdrv_co_pwritev
= raw_co_pwritev
,
2934 .bdrv_aio_flush
= raw_aio_flush
,
2935 .bdrv_refresh_limits
= raw_refresh_limits
,
2936 .bdrv_io_plug
= raw_aio_plug
,
2937 .bdrv_io_unplug
= raw_aio_unplug
,
2939 .bdrv_truncate
= raw_truncate
,
2940 .bdrv_getlength
= raw_getlength
,
2941 .has_variable_length
= true,
2942 .bdrv_get_allocated_file_size
2943 = raw_get_allocated_file_size
,
2945 /* removable device support */
2946 .bdrv_is_inserted
= cdrom_is_inserted
,
2947 .bdrv_eject
= cdrom_eject
,
2948 .bdrv_lock_medium
= cdrom_lock_medium
,
2950 /* generic scsi device */
2951 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2953 #endif /* __linux__ */
2955 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2956 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2959 BDRVRawState
*s
= bs
->opaque
;
2960 Error
*local_err
= NULL
;
2965 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2967 error_propagate(errp
, local_err
);
2971 /* make sure the door isn't locked at this time */
2972 ioctl(s
->fd
, CDIOCALLOW
);
2976 static int cdrom_probe_device(const char *filename
)
2978 if (strstart(filename
, "/dev/cd", NULL
) ||
2979 strstart(filename
, "/dev/acd", NULL
))
2984 static int cdrom_reopen(BlockDriverState
*bs
)
2986 BDRVRawState
*s
= bs
->opaque
;
2990 * Force reread of possibly changed/newly loaded disc,
2991 * FreeBSD seems to not notice sometimes...
2995 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
3002 /* make sure the door isn't locked at this time */
3003 ioctl(s
->fd
, CDIOCALLOW
);
3007 static bool cdrom_is_inserted(BlockDriverState
*bs
)
3009 return raw_getlength(bs
) > 0;
3012 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
3014 BDRVRawState
*s
= bs
->opaque
;
3019 (void) ioctl(s
->fd
, CDIOCALLOW
);
3022 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
3023 perror("CDIOCEJECT");
3025 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
3026 perror("CDIOCCLOSE");
3032 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
3034 BDRVRawState
*s
= bs
->opaque
;
3038 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
3040 * Note: an error can happen if the distribution automatically
3043 /* perror("CDROM_LOCKDOOR"); */
3047 static BlockDriver bdrv_host_cdrom
= {
3048 .format_name
= "host_cdrom",
3049 .protocol_name
= "host_cdrom",
3050 .instance_size
= sizeof(BDRVRawState
),
3051 .bdrv_needs_filename
= true,
3052 .bdrv_probe_device
= cdrom_probe_device
,
3053 .bdrv_parse_filename
= cdrom_parse_filename
,
3054 .bdrv_file_open
= cdrom_open
,
3055 .bdrv_close
= raw_close
,
3056 .bdrv_reopen_prepare
= raw_reopen_prepare
,
3057 .bdrv_reopen_commit
= raw_reopen_commit
,
3058 .bdrv_reopen_abort
= raw_reopen_abort
,
3059 .bdrv_co_create_opts
= hdev_co_create_opts
,
3060 .create_opts
= &raw_create_opts
,
3062 .bdrv_co_preadv
= raw_co_preadv
,
3063 .bdrv_co_pwritev
= raw_co_pwritev
,
3064 .bdrv_aio_flush
= raw_aio_flush
,
3065 .bdrv_refresh_limits
= raw_refresh_limits
,
3066 .bdrv_io_plug
= raw_aio_plug
,
3067 .bdrv_io_unplug
= raw_aio_unplug
,
3069 .bdrv_truncate
= raw_truncate
,
3070 .bdrv_getlength
= raw_getlength
,
3071 .has_variable_length
= true,
3072 .bdrv_get_allocated_file_size
3073 = raw_get_allocated_file_size
,
3075 /* removable device support */
3076 .bdrv_is_inserted
= cdrom_is_inserted
,
3077 .bdrv_eject
= cdrom_eject
,
3078 .bdrv_lock_medium
= cdrom_lock_medium
,
3080 #endif /* __FreeBSD__ */
3082 static void bdrv_file_init(void)
3085 * Register all the drivers. Note that order is important, the driver
3086 * registered last will get probed first.
3088 bdrv_register(&bdrv_file
);
3089 bdrv_register(&bdrv_host_device
);
3091 bdrv_register(&bdrv_host_cdrom
);
3093 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3094 bdrv_register(&bdrv_host_cdrom
);
3098 block_init(bdrv_file_init
);