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
;
164 bool check_cache_dropped
;
169 typedef struct BDRVRawReopenState
{
172 bool check_cache_dropped
;
173 } BDRVRawReopenState
;
175 static int fd_open(BlockDriverState
*bs
);
176 static int64_t raw_getlength(BlockDriverState
*bs
);
178 typedef struct RawPosixAIOData
{
179 BlockDriverState
*bs
;
182 struct iovec
*aio_iov
;
187 #define aio_ioctl_cmd aio_nbytes /* for QEMU_AIO_IOCTL */
192 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
193 static int cdrom_reopen(BlockDriverState
*bs
);
196 #if defined(__NetBSD__)
197 static int raw_normalize_devicepath(const char **filename
)
199 static char namebuf
[PATH_MAX
];
200 const char *dp
, *fname
;
204 dp
= strrchr(fname
, '/');
205 if (lstat(fname
, &sb
) < 0) {
206 fprintf(stderr
, "%s: stat failed: %s\n",
207 fname
, strerror(errno
));
211 if (!S_ISBLK(sb
.st_mode
)) {
216 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
218 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
219 (int)(dp
- fname
), fname
, dp
+ 1);
221 fprintf(stderr
, "%s is a block device", fname
);
223 fprintf(stderr
, ", using %s\n", *filename
);
228 static int raw_normalize_devicepath(const char **filename
)
235 * Get logical block size via ioctl. On success store it in @sector_size_p.
237 static int probe_logical_blocksize(int fd
, unsigned int *sector_size_p
)
239 unsigned int sector_size
;
240 bool success
= false;
244 static const unsigned long ioctl_list
[] = {
248 #ifdef DKIOCGETBLOCKSIZE
251 #ifdef DIOCGSECTORSIZE
256 /* Try a few ioctls to get the right size */
257 for (i
= 0; i
< (int)ARRAY_SIZE(ioctl_list
); i
++) {
258 if (ioctl(fd
, ioctl_list
[i
], §or_size
) >= 0) {
259 *sector_size_p
= sector_size
;
264 return success
? 0 : -errno
;
268 * Get physical block size of @fd.
269 * On success, store it in @blk_size and return 0.
270 * On failure, return -errno.
272 static int probe_physical_blocksize(int fd
, unsigned int *blk_size
)
275 if (ioctl(fd
, BLKPBSZGET
, blk_size
) < 0) {
284 /* Check if read is allowed with given memory buffer and length.
286 * This function is used to check O_DIRECT memory buffer and request alignment.
288 static bool raw_is_io_aligned(int fd
, void *buf
, size_t len
)
290 ssize_t ret
= pread(fd
, buf
, len
, 0);
297 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
298 * other errors (e.g. real I/O error), which could happen on a failed
299 * drive, since we only care about probing alignment.
301 if (errno
!= EINVAL
) {
309 static void raw_probe_alignment(BlockDriverState
*bs
, int fd
, Error
**errp
)
311 BDRVRawState
*s
= bs
->opaque
;
313 size_t max_align
= MAX(MAX_BLOCKSIZE
, getpagesize());
315 /* For SCSI generic devices the alignment is not really used.
316 With buffered I/O, we don't have any restrictions. */
317 if (bdrv_is_sg(bs
) || !s
->needs_alignment
) {
318 bs
->bl
.request_alignment
= 1;
323 bs
->bl
.request_alignment
= 0;
325 /* Let's try to use the logical blocksize for the alignment. */
326 if (probe_logical_blocksize(fd
, &bs
->bl
.request_alignment
) < 0) {
327 bs
->bl
.request_alignment
= 0;
332 if (xfsctl(NULL
, fd
, XFS_IOC_DIOINFO
, &da
) >= 0) {
333 bs
->bl
.request_alignment
= da
.d_miniosz
;
334 /* The kernel returns wrong information for d_mem */
335 /* s->buf_align = da.d_mem; */
340 /* If we could not get the sizes so far, we can only guess them */
343 buf
= qemu_memalign(max_align
, 2 * max_align
);
344 for (align
= 512; align
<= max_align
; align
<<= 1) {
345 if (raw_is_io_aligned(fd
, buf
+ align
, max_align
)) {
346 s
->buf_align
= align
;
353 if (!bs
->bl
.request_alignment
) {
355 buf
= qemu_memalign(s
->buf_align
, max_align
);
356 for (align
= 512; align
<= max_align
; align
<<= 1) {
357 if (raw_is_io_aligned(fd
, buf
, align
)) {
358 bs
->bl
.request_alignment
= align
;
365 if (!s
->buf_align
|| !bs
->bl
.request_alignment
) {
366 error_setg(errp
, "Could not find working O_DIRECT alignment");
367 error_append_hint(errp
, "Try cache.direct=off\n");
371 static void raw_parse_flags(int bdrv_flags
, int *open_flags
)
373 assert(open_flags
!= NULL
);
375 *open_flags
|= O_BINARY
;
376 *open_flags
&= ~O_ACCMODE
;
377 if (bdrv_flags
& BDRV_O_RDWR
) {
378 *open_flags
|= O_RDWR
;
380 *open_flags
|= O_RDONLY
;
383 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
384 * and O_DIRECT for no caching. */
385 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
386 *open_flags
|= O_DIRECT
;
390 static void raw_parse_filename(const char *filename
, QDict
*options
,
393 bdrv_parse_filename_strip_prefix(filename
, "file:", options
);
396 static QemuOptsList raw_runtime_opts
= {
398 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
402 .type
= QEMU_OPT_STRING
,
403 .help
= "File name of the image",
407 .type
= QEMU_OPT_STRING
,
408 .help
= "host AIO implementation (threads, native)",
412 .type
= QEMU_OPT_STRING
,
413 .help
= "file locking mode (on/off/auto, default: auto)",
416 .name
= "pr-manager",
417 .type
= QEMU_OPT_STRING
,
418 .help
= "id of persistent reservation manager object (default: none)",
421 .name
= "x-check-cache-dropped",
422 .type
= QEMU_OPT_BOOL
,
423 .help
= "check that page cache was dropped on live migration (default: off)"
425 { /* end of list */ }
429 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
430 int bdrv_flags
, int open_flags
, Error
**errp
)
432 BDRVRawState
*s
= bs
->opaque
;
434 Error
*local_err
= NULL
;
435 const char *filename
= NULL
;
437 BlockdevAioOptions aio
, aio_default
;
442 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
443 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
445 error_propagate(errp
, local_err
);
450 filename
= qemu_opt_get(opts
, "filename");
452 ret
= raw_normalize_devicepath(&filename
);
454 error_setg_errno(errp
, -ret
, "Could not normalize device path");
458 aio_default
= (bdrv_flags
& BDRV_O_NATIVE_AIO
)
459 ? BLOCKDEV_AIO_OPTIONS_NATIVE
460 : BLOCKDEV_AIO_OPTIONS_THREADS
;
461 aio
= qapi_enum_parse(&BlockdevAioOptions_lookup
,
462 qemu_opt_get(opts
, "aio"),
463 aio_default
, &local_err
);
465 error_propagate(errp
, local_err
);
469 s
->use_linux_aio
= (aio
== BLOCKDEV_AIO_OPTIONS_NATIVE
);
471 locking
= qapi_enum_parse(&OnOffAuto_lookup
,
472 qemu_opt_get(opts
, "locking"),
473 ON_OFF_AUTO_AUTO
, &local_err
);
475 error_propagate(errp
, local_err
);
482 if (!qemu_has_ofd_lock()) {
484 "File lock requested but OFD locking syscall is "
485 "unavailable, falling back to POSIX file locks.\n"
486 "Due to the implementation, locks can be lost "
490 case ON_OFF_AUTO_OFF
:
493 case ON_OFF_AUTO_AUTO
:
494 s
->use_lock
= qemu_has_ofd_lock();
500 str
= qemu_opt_get(opts
, "pr-manager");
502 s
->pr_mgr
= pr_manager_lookup(str
, &local_err
);
504 error_propagate(errp
, local_err
);
510 s
->check_cache_dropped
= qemu_opt_get_bool(opts
, "x-check-cache-dropped",
513 s
->open_flags
= open_flags
;
514 raw_parse_flags(bdrv_flags
, &s
->open_flags
);
517 fd
= qemu_open(filename
, s
->open_flags
, 0644);
520 error_setg_errno(errp
, errno
, "Could not open '%s'", filename
);
530 fd
= qemu_open(filename
, s
->open_flags
);
533 error_setg_errno(errp
, errno
, "Could not open '%s' for locking",
541 s
->shared_perm
= BLK_PERM_ALL
;
543 #ifdef CONFIG_LINUX_AIO
544 /* Currently Linux does AIO only for files opened with O_DIRECT */
545 if (s
->use_linux_aio
&& !(s
->open_flags
& O_DIRECT
)) {
546 error_setg(errp
, "aio=native was specified, but it requires "
547 "cache.direct=on, which was not specified.");
552 if (s
->use_linux_aio
) {
553 error_setg(errp
, "aio=native was specified, but is not supported "
558 #endif /* !defined(CONFIG_LINUX_AIO) */
560 s
->has_discard
= true;
561 s
->has_write_zeroes
= true;
562 if ((bs
->open_flags
& BDRV_O_NOCACHE
) != 0) {
563 s
->needs_alignment
= true;
566 if (fstat(s
->fd
, &st
) < 0) {
568 error_setg_errno(errp
, errno
, "Could not stat file");
571 if (S_ISREG(st
.st_mode
)) {
572 s
->discard_zeroes
= true;
573 s
->has_fallocate
= true;
575 if (S_ISBLK(st
.st_mode
)) {
576 #ifdef BLKDISCARDZEROES
578 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
579 s
->discard_zeroes
= true;
583 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
584 * not rely on the contents of discarded blocks unless using O_DIRECT.
585 * Same for BLKZEROOUT.
587 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
588 s
->discard_zeroes
= false;
589 s
->has_write_zeroes
= false;
594 if (S_ISCHR(st
.st_mode
)) {
596 * The file is a char device (disk), which on FreeBSD isn't behind
597 * a pager, so force all requests to be aligned. This is needed
598 * so QEMU makes sure all IO operations on the device are aligned
599 * to sector size, or else FreeBSD will reject them with EINVAL.
601 s
->needs_alignment
= true;
606 if (platform_test_xfs_fd(s
->fd
)) {
611 bs
->supported_zero_flags
= s
->discard_zeroes
? BDRV_REQ_MAY_UNMAP
: 0;
614 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
621 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
624 BDRVRawState
*s
= bs
->opaque
;
626 s
->type
= FTYPE_FILE
;
627 return raw_open_common(bs
, options
, flags
, 0, errp
);
636 #define PERM_FOREACH(i) \
637 for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
639 /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
640 * file; if @unlock == true, also unlock the unneeded bytes.
641 * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
643 static int raw_apply_lock_bytes(BDRVRawState
*s
,
644 uint64_t perm_lock_bits
,
645 uint64_t shared_perm_lock_bits
,
646 bool unlock
, Error
**errp
)
652 int off
= RAW_LOCK_PERM_BASE
+ i
;
653 if (perm_lock_bits
& (1ULL << i
)) {
654 ret
= qemu_lock_fd(s
->lock_fd
, off
, 1, false);
656 error_setg(errp
, "Failed to lock byte %d", off
);
660 ret
= qemu_unlock_fd(s
->lock_fd
, off
, 1);
662 error_setg(errp
, "Failed to unlock byte %d", off
);
668 int off
= RAW_LOCK_SHARED_BASE
+ i
;
669 if (shared_perm_lock_bits
& (1ULL << i
)) {
670 ret
= qemu_lock_fd(s
->lock_fd
, off
, 1, false);
672 error_setg(errp
, "Failed to lock byte %d", off
);
676 ret
= qemu_unlock_fd(s
->lock_fd
, off
, 1);
678 error_setg(errp
, "Failed to unlock byte %d", off
);
686 /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
687 static int raw_check_lock_bytes(BDRVRawState
*s
,
688 uint64_t perm
, uint64_t shared_perm
,
695 int off
= RAW_LOCK_SHARED_BASE
+ i
;
696 uint64_t p
= 1ULL << i
;
698 ret
= qemu_lock_fd_test(s
->lock_fd
, off
, 1, true);
700 char *perm_name
= bdrv_perm_names(p
);
702 "Failed to get \"%s\" lock",
705 error_append_hint(errp
,
706 "Is another process using the image?\n");
712 int off
= RAW_LOCK_PERM_BASE
+ i
;
713 uint64_t p
= 1ULL << i
;
714 if (!(shared_perm
& p
)) {
715 ret
= qemu_lock_fd_test(s
->lock_fd
, off
, 1, true);
717 char *perm_name
= bdrv_perm_names(p
);
719 "Failed to get shared \"%s\" lock",
722 error_append_hint(errp
,
723 "Is another process using the image?\n");
731 static int raw_handle_perm_lock(BlockDriverState
*bs
,
733 uint64_t new_perm
, uint64_t new_shared
,
736 BDRVRawState
*s
= bs
->opaque
;
738 Error
*local_err
= NULL
;
744 if (bdrv_get_flags(bs
) & BDRV_O_INACTIVE
) {
748 assert(s
->lock_fd
> 0);
752 ret
= raw_apply_lock_bytes(s
, s
->perm
| new_perm
,
753 ~s
->shared_perm
| ~new_shared
,
756 ret
= raw_check_lock_bytes(s
, new_perm
, new_shared
, errp
);
762 /* fall through to unlock bytes. */
764 raw_apply_lock_bytes(s
, s
->perm
, ~s
->shared_perm
, true, &local_err
);
766 /* Theoretically the above call only unlocks bytes and it cannot
767 * fail. Something weird happened, report it.
769 error_report_err(local_err
);
773 raw_apply_lock_bytes(s
, new_perm
, ~new_shared
, true, &local_err
);
775 /* Theoretically the above call only unlocks bytes and it cannot
776 * fail. Something weird happened, report it.
778 error_report_err(local_err
);
785 static int raw_reopen_prepare(BDRVReopenState
*state
,
786 BlockReopenQueue
*queue
, Error
**errp
)
789 BDRVRawReopenState
*rs
;
792 Error
*local_err
= NULL
;
794 assert(state
!= NULL
);
795 assert(state
->bs
!= NULL
);
797 s
= state
->bs
->opaque
;
799 state
->opaque
= g_new0(BDRVRawReopenState
, 1);
803 /* Handle options changes */
804 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
805 qemu_opts_absorb_qdict(opts
, state
->options
, &local_err
);
807 error_propagate(errp
, local_err
);
812 rs
->check_cache_dropped
= qemu_opt_get_bool(opts
, "x-check-cache-dropped",
813 s
->check_cache_dropped
);
815 if (s
->type
== FTYPE_CD
) {
816 rs
->open_flags
|= O_NONBLOCK
;
819 raw_parse_flags(state
->flags
, &rs
->open_flags
);
821 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
823 fcntl_flags
|= O_NOATIME
;
827 /* Not all operating systems have O_ASYNC, and those that don't
828 * will not let us track the state into rs->open_flags (typically
829 * you achieve the same effect with an ioctl, for example I_SETSIG
830 * on Solaris). But we do not use O_ASYNC, so that's fine.
832 assert((s
->open_flags
& O_ASYNC
) == 0);
835 if ((rs
->open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
836 /* dup the original fd */
837 rs
->fd
= qemu_dup(s
->fd
);
839 ret
= fcntl_setfl(rs
->fd
, rs
->open_flags
);
847 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
849 const char *normalized_filename
= state
->bs
->filename
;
850 ret
= raw_normalize_devicepath(&normalized_filename
);
852 error_setg_errno(errp
, -ret
, "Could not normalize device path");
854 assert(!(rs
->open_flags
& O_CREAT
));
855 rs
->fd
= qemu_open(normalized_filename
, rs
->open_flags
);
857 error_setg_errno(errp
, errno
, "Could not reopen file");
863 /* Fail already reopen_prepare() if we can't get a working O_DIRECT
864 * alignment with the new fd. */
866 raw_probe_alignment(state
->bs
, rs
->fd
, &local_err
);
870 error_propagate(errp
, local_err
);
880 static void raw_reopen_commit(BDRVReopenState
*state
)
882 BDRVRawReopenState
*rs
= state
->opaque
;
883 BDRVRawState
*s
= state
->bs
->opaque
;
885 s
->check_cache_dropped
= rs
->check_cache_dropped
;
886 s
->open_flags
= rs
->open_flags
;
891 g_free(state
->opaque
);
892 state
->opaque
= NULL
;
896 static void raw_reopen_abort(BDRVReopenState
*state
)
898 BDRVRawReopenState
*rs
= state
->opaque
;
900 /* nothing to do if NULL, we didn't get far enough */
909 g_free(state
->opaque
);
910 state
->opaque
= NULL
;
913 static int hdev_get_max_transfer_length(BlockDriverState
*bs
, int fd
)
917 short max_sectors
= 0;
918 if (bs
->sg
&& ioctl(fd
, BLKSECTGET
, &max_bytes
) == 0) {
920 } else if (!bs
->sg
&& ioctl(fd
, BLKSECTGET
, &max_sectors
) == 0) {
921 return max_sectors
<< BDRV_SECTOR_BITS
;
930 static int hdev_get_max_segments(const struct stat
*st
)
940 sysfspath
= g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
941 major(st
->st_rdev
), minor(st
->st_rdev
));
942 fd
= open(sysfspath
, O_RDONLY
);
948 ret
= read(fd
, buf
, sizeof(buf
) - 1);
949 } while (ret
== -1 && errno
== EINTR
);
953 } else if (ret
== 0) {
958 /* The file is ended with '\n', pass 'end' to accept that. */
959 ret
= qemu_strtol(buf
, &end
, 10, &max_segments
);
960 if (ret
== 0 && end
&& *end
== '\n') {
975 static void raw_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
977 BDRVRawState
*s
= bs
->opaque
;
980 if (!fstat(s
->fd
, &st
)) {
981 if (S_ISBLK(st
.st_mode
) || S_ISCHR(st
.st_mode
)) {
982 int ret
= hdev_get_max_transfer_length(bs
, s
->fd
);
983 if (ret
> 0 && ret
<= BDRV_REQUEST_MAX_BYTES
) {
984 bs
->bl
.max_transfer
= pow2floor(ret
);
986 ret
= hdev_get_max_segments(&st
);
988 bs
->bl
.max_transfer
= MIN(bs
->bl
.max_transfer
,
989 ret
* getpagesize());
994 raw_probe_alignment(bs
, s
->fd
, errp
);
995 bs
->bl
.min_mem_alignment
= s
->buf_align
;
996 bs
->bl
.opt_mem_alignment
= MAX(s
->buf_align
, getpagesize());
999 static int check_for_dasd(int fd
)
1002 struct dasd_information2_t info
= {0};
1004 return ioctl(fd
, BIODASDINFO2
, &info
);
1011 * Try to get @bs's logical and physical block size.
1012 * On success, store them in @bsz and return zero.
1013 * On failure, return negative errno.
1015 static int hdev_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
1017 BDRVRawState
*s
= bs
->opaque
;
1020 /* If DASD, get blocksizes */
1021 if (check_for_dasd(s
->fd
) < 0) {
1024 ret
= probe_logical_blocksize(s
->fd
, &bsz
->log
);
1028 return probe_physical_blocksize(s
->fd
, &bsz
->phys
);
1032 * Try to get @bs's geometry: cyls, heads, sectors.
1033 * On success, store them in @geo and return 0.
1034 * On failure return -errno.
1035 * (Allows block driver to assign default geometry values that guest sees)
1038 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
1040 BDRVRawState
*s
= bs
->opaque
;
1041 struct hd_geometry ioctl_geo
= {0};
1043 /* If DASD, get its geometry */
1044 if (check_for_dasd(s
->fd
) < 0) {
1047 if (ioctl(s
->fd
, HDIO_GETGEO
, &ioctl_geo
) < 0) {
1050 /* HDIO_GETGEO may return success even though geo contains zeros
1051 (e.g. certain multipath setups) */
1052 if (!ioctl_geo
.heads
|| !ioctl_geo
.sectors
|| !ioctl_geo
.cylinders
) {
1055 /* Do not return a geometry for partition */
1056 if (ioctl_geo
.start
!= 0) {
1059 geo
->heads
= ioctl_geo
.heads
;
1060 geo
->sectors
= ioctl_geo
.sectors
;
1061 geo
->cylinders
= ioctl_geo
.cylinders
;
1065 #else /* __linux__ */
1066 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
1072 static ssize_t
handle_aiocb_ioctl(RawPosixAIOData
*aiocb
)
1076 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->aio_ioctl_cmd
, aiocb
->aio_ioctl_buf
);
1084 static ssize_t
handle_aiocb_flush(RawPosixAIOData
*aiocb
)
1086 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1089 if (s
->page_cache_inconsistent
) {
1093 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
1095 /* There is no clear definition of the semantics of a failing fsync(),
1096 * so we may have to assume the worst. The sad truth is that this
1097 * assumption is correct for Linux. Some pages are now probably marked
1098 * clean in the page cache even though they are inconsistent with the
1099 * on-disk contents. The next fdatasync() call would succeed, but no
1100 * further writeback attempt will be made. We can't get back to a state
1101 * in which we know what is on disk (we would have to rewrite
1102 * everything that was touched since the last fdatasync() at least), so
1103 * make bdrv_flush() fail permanently. Given that the behaviour isn't
1104 * really defined, I have little hope that other OSes are doing better.
1106 * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1108 if ((s
->open_flags
& O_DIRECT
) == 0) {
1109 s
->page_cache_inconsistent
= true;
1116 #ifdef CONFIG_PREADV
1118 static bool preadv_present
= true;
1121 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1123 return preadv(fd
, iov
, nr_iov
, offset
);
1127 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1129 return pwritev(fd
, iov
, nr_iov
, offset
);
1134 static bool preadv_present
= false;
1137 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1143 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1150 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
1155 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
1156 len
= qemu_pwritev(aiocb
->aio_fildes
,
1161 len
= qemu_preadv(aiocb
->aio_fildes
,
1165 } while (len
== -1 && errno
== EINTR
);
1174 * Read/writes the data to/from a given linear buffer.
1176 * Returns the number of bytes handles or -errno in case of an error. Short
1177 * reads are only returned if the end of the file is reached.
1179 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
1184 while (offset
< aiocb
->aio_nbytes
) {
1185 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1186 len
= pwrite(aiocb
->aio_fildes
,
1187 (const char *)buf
+ offset
,
1188 aiocb
->aio_nbytes
- offset
,
1189 aiocb
->aio_offset
+ offset
);
1191 len
= pread(aiocb
->aio_fildes
,
1193 aiocb
->aio_nbytes
- offset
,
1194 aiocb
->aio_offset
+ offset
);
1196 if (len
== -1 && errno
== EINTR
) {
1198 } else if (len
== -1 && errno
== EINVAL
&&
1199 (aiocb
->bs
->open_flags
& BDRV_O_NOCACHE
) &&
1200 !(aiocb
->aio_type
& QEMU_AIO_WRITE
) &&
1202 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1203 * after a short read. Assume that O_DIRECT short reads only occur
1204 * at EOF. Therefore this is a short read, not an I/O error.
1207 } else if (len
== -1) {
1210 } else if (len
== 0) {
1219 static ssize_t
handle_aiocb_rw(RawPosixAIOData
*aiocb
)
1224 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
1226 * If there is just a single buffer, and it is properly aligned
1227 * we can just use plain pread/pwrite without any problems.
1229 if (aiocb
->aio_niov
== 1) {
1230 return handle_aiocb_rw_linear(aiocb
, aiocb
->aio_iov
->iov_base
);
1233 * We have more than one iovec, and all are properly aligned.
1235 * Try preadv/pwritev first and fall back to linearizing the
1236 * buffer if it's not supported.
1238 if (preadv_present
) {
1239 nbytes
= handle_aiocb_rw_vector(aiocb
);
1240 if (nbytes
== aiocb
->aio_nbytes
||
1241 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
1244 preadv_present
= false;
1248 * XXX(hch): short read/write. no easy way to handle the reminder
1249 * using these interfaces. For now retry using plain
1255 * Ok, we have to do it the hard way, copy all segments into
1256 * a single aligned buffer.
1258 buf
= qemu_try_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
1263 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1267 for (i
= 0; i
< aiocb
->aio_niov
; ++i
) {
1268 memcpy(p
, aiocb
->aio_iov
[i
].iov_base
, aiocb
->aio_iov
[i
].iov_len
);
1269 p
+= aiocb
->aio_iov
[i
].iov_len
;
1271 assert(p
- buf
== aiocb
->aio_nbytes
);
1274 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
1275 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
1277 size_t count
= aiocb
->aio_nbytes
, copy
;
1280 for (i
= 0; i
< aiocb
->aio_niov
&& count
; ++i
) {
1282 if (copy
> aiocb
->aio_iov
[i
].iov_len
) {
1283 copy
= aiocb
->aio_iov
[i
].iov_len
;
1285 memcpy(aiocb
->aio_iov
[i
].iov_base
, p
, copy
);
1286 assert(count
>= copy
);
1298 static int xfs_write_zeroes(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1300 struct xfs_flock64 fl
;
1303 memset(&fl
, 0, sizeof(fl
));
1304 fl
.l_whence
= SEEK_SET
;
1305 fl
.l_start
= offset
;
1308 if (xfsctl(NULL
, s
->fd
, XFS_IOC_ZERO_RANGE
, &fl
) < 0) {
1310 DPRINTF("cannot write zero range (%s)\n", strerror(errno
));
1317 static int xfs_discard(BDRVRawState
*s
, int64_t offset
, uint64_t bytes
)
1319 struct xfs_flock64 fl
;
1322 memset(&fl
, 0, sizeof(fl
));
1323 fl
.l_whence
= SEEK_SET
;
1324 fl
.l_start
= offset
;
1327 if (xfsctl(NULL
, s
->fd
, XFS_IOC_UNRESVSP64
, &fl
) < 0) {
1329 DPRINTF("cannot punch hole (%s)\n", strerror(errno
));
1337 static int translate_err(int err
)
1339 if (err
== -ENODEV
|| err
== -ENOSYS
|| err
== -EOPNOTSUPP
||
1346 #ifdef CONFIG_FALLOCATE
1347 static int do_fallocate(int fd
, int mode
, off_t offset
, off_t len
)
1350 if (fallocate(fd
, mode
, offset
, len
) == 0) {
1353 } while (errno
== EINTR
);
1354 return translate_err(-errno
);
1358 static ssize_t
handle_aiocb_write_zeroes_block(RawPosixAIOData
*aiocb
)
1361 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1363 if (!s
->has_write_zeroes
) {
1369 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1370 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
1373 } while (errno
== EINTR
);
1375 ret
= translate_err(-errno
);
1378 if (ret
== -ENOTSUP
) {
1379 s
->has_write_zeroes
= false;
1384 static ssize_t
handle_aiocb_write_zeroes(RawPosixAIOData
*aiocb
)
1386 #if defined(CONFIG_FALLOCATE) || defined(CONFIG_XFS)
1387 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1389 #ifdef CONFIG_FALLOCATE
1393 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1394 return handle_aiocb_write_zeroes_block(aiocb
);
1399 return xfs_write_zeroes(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1403 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1404 if (s
->has_write_zeroes
) {
1405 int ret
= do_fallocate(s
->fd
, FALLOC_FL_ZERO_RANGE
,
1406 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1407 if (ret
== 0 || ret
!= -ENOTSUP
) {
1410 s
->has_write_zeroes
= false;
1414 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1415 if (s
->has_discard
&& s
->has_fallocate
) {
1416 int ret
= do_fallocate(s
->fd
,
1417 FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1418 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1420 ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1421 if (ret
== 0 || ret
!= -ENOTSUP
) {
1424 s
->has_fallocate
= false;
1425 } else if (ret
!= -ENOTSUP
) {
1428 s
->has_discard
= false;
1433 #ifdef CONFIG_FALLOCATE
1434 /* Last resort: we are trying to extend the file with zeroed data. This
1435 * can be done via fallocate(fd, 0) */
1436 len
= bdrv_getlength(aiocb
->bs
);
1437 if (s
->has_fallocate
&& len
>= 0 && aiocb
->aio_offset
>= len
) {
1438 int ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1439 if (ret
== 0 || ret
!= -ENOTSUP
) {
1442 s
->has_fallocate
= false;
1449 static ssize_t
handle_aiocb_discard(RawPosixAIOData
*aiocb
)
1451 int ret
= -EOPNOTSUPP
;
1452 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1454 if (!s
->has_discard
) {
1458 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1461 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1462 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
1465 } while (errno
== EINTR
);
1472 return xfs_discard(s
, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1476 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1477 ret
= do_fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1478 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1482 ret
= translate_err(ret
);
1483 if (ret
== -ENOTSUP
) {
1484 s
->has_discard
= false;
1489 static int aio_worker(void *arg
)
1491 RawPosixAIOData
*aiocb
= arg
;
1494 switch (aiocb
->aio_type
& QEMU_AIO_TYPE_MASK
) {
1496 ret
= handle_aiocb_rw(aiocb
);
1497 if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1498 iov_memset(aiocb
->aio_iov
, aiocb
->aio_niov
, ret
,
1499 0, aiocb
->aio_nbytes
- ret
);
1501 ret
= aiocb
->aio_nbytes
;
1503 if (ret
== aiocb
->aio_nbytes
) {
1505 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1509 case QEMU_AIO_WRITE
:
1510 ret
= handle_aiocb_rw(aiocb
);
1511 if (ret
== aiocb
->aio_nbytes
) {
1513 } else if (ret
>= 0 && ret
< aiocb
->aio_nbytes
) {
1517 case QEMU_AIO_FLUSH
:
1518 ret
= handle_aiocb_flush(aiocb
);
1520 case QEMU_AIO_IOCTL
:
1521 ret
= handle_aiocb_ioctl(aiocb
);
1523 case QEMU_AIO_DISCARD
:
1524 ret
= handle_aiocb_discard(aiocb
);
1526 case QEMU_AIO_WRITE_ZEROES
:
1527 ret
= handle_aiocb_write_zeroes(aiocb
);
1530 fprintf(stderr
, "invalid aio request (0x%x)\n", aiocb
->aio_type
);
1539 static int paio_submit_co(BlockDriverState
*bs
, int fd
,
1540 int64_t offset
, QEMUIOVector
*qiov
,
1541 int bytes
, 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
== bytes
);
1559 trace_paio_submit_co(offset
, bytes
, type
);
1560 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1561 return thread_pool_submit_co(pool
, aio_worker
, acb
);
1564 static BlockAIOCB
*paio_submit(BlockDriverState
*bs
, int fd
,
1565 int64_t offset
, QEMUIOVector
*qiov
, int bytes
,
1566 BlockCompletionFunc
*cb
, void *opaque
, int type
)
1568 RawPosixAIOData
*acb
= g_new(RawPosixAIOData
, 1);
1572 acb
->aio_type
= type
;
1573 acb
->aio_fildes
= fd
;
1575 acb
->aio_nbytes
= bytes
;
1576 acb
->aio_offset
= offset
;
1579 acb
->aio_iov
= qiov
->iov
;
1580 acb
->aio_niov
= qiov
->niov
;
1581 assert(qiov
->size
== acb
->aio_nbytes
);
1584 trace_paio_submit(acb
, opaque
, offset
, bytes
, type
);
1585 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
1586 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
1589 static int coroutine_fn
raw_co_prw(BlockDriverState
*bs
, uint64_t offset
,
1590 uint64_t bytes
, QEMUIOVector
*qiov
, int type
)
1592 BDRVRawState
*s
= bs
->opaque
;
1594 if (fd_open(bs
) < 0)
1598 * Check if the underlying device requires requests to be aligned,
1599 * and if the request we are trying to submit is aligned or not.
1600 * If this is the case tell the low-level driver that it needs
1601 * to copy the buffer.
1603 if (s
->needs_alignment
) {
1604 if (!bdrv_qiov_is_aligned(bs
, qiov
)) {
1605 type
|= QEMU_AIO_MISALIGNED
;
1606 #ifdef CONFIG_LINUX_AIO
1607 } else if (s
->use_linux_aio
) {
1608 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1609 assert(qiov
->size
== bytes
);
1610 return laio_co_submit(bs
, aio
, s
->fd
, offset
, qiov
, type
);
1615 return paio_submit_co(bs
, s
->fd
, offset
, qiov
, bytes
, type
);
1618 static int coroutine_fn
raw_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1619 uint64_t bytes
, QEMUIOVector
*qiov
,
1622 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_READ
);
1625 static int coroutine_fn
raw_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1626 uint64_t bytes
, QEMUIOVector
*qiov
,
1630 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_WRITE
);
1633 static void raw_aio_plug(BlockDriverState
*bs
)
1635 #ifdef CONFIG_LINUX_AIO
1636 BDRVRawState
*s
= bs
->opaque
;
1637 if (s
->use_linux_aio
) {
1638 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1639 laio_io_plug(bs
, aio
);
1644 static void raw_aio_unplug(BlockDriverState
*bs
)
1646 #ifdef CONFIG_LINUX_AIO
1647 BDRVRawState
*s
= bs
->opaque
;
1648 if (s
->use_linux_aio
) {
1649 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
1650 laio_io_unplug(bs
, aio
);
1655 static BlockAIOCB
*raw_aio_flush(BlockDriverState
*bs
,
1656 BlockCompletionFunc
*cb
, void *opaque
)
1658 BDRVRawState
*s
= bs
->opaque
;
1660 if (fd_open(bs
) < 0)
1663 return paio_submit(bs
, s
->fd
, 0, NULL
, 0, cb
, opaque
, QEMU_AIO_FLUSH
);
1666 static void raw_close(BlockDriverState
*bs
)
1668 BDRVRawState
*s
= bs
->opaque
;
1674 if (s
->lock_fd
>= 0) {
1675 qemu_close(s
->lock_fd
);
1681 * Truncates the given regular file @fd to @offset and, when growing, fills the
1682 * new space according to @prealloc.
1684 * Returns: 0 on success, -errno on failure.
1686 static int raw_regular_truncate(int fd
, int64_t offset
, PreallocMode prealloc
,
1690 int64_t current_length
= 0;
1694 if (fstat(fd
, &st
) < 0) {
1696 error_setg_errno(errp
, -result
, "Could not stat file");
1700 current_length
= st
.st_size
;
1701 if (current_length
> offset
&& prealloc
!= PREALLOC_MODE_OFF
) {
1702 error_setg(errp
, "Cannot use preallocation for shrinking files");
1707 #ifdef CONFIG_POSIX_FALLOCATE
1708 case PREALLOC_MODE_FALLOC
:
1710 * Truncating before posix_fallocate() makes it about twice slower on
1711 * file systems that do not support fallocate(), trying to check if a
1712 * block is allocated before allocating it, so don't do that here.
1714 if (offset
!= current_length
) {
1715 result
= -posix_fallocate(fd
, current_length
, offset
- current_length
);
1717 /* posix_fallocate() doesn't set errno. */
1718 error_setg_errno(errp
, -result
,
1719 "Could not preallocate new data");
1726 case PREALLOC_MODE_FULL
:
1728 int64_t num
= 0, left
= offset
- current_length
;
1732 * Knowing the final size from the beginning could allow the file
1733 * system driver to do less allocations and possibly avoid
1734 * fragmentation of the file.
1736 if (ftruncate(fd
, offset
) != 0) {
1738 error_setg_errno(errp
, -result
, "Could not resize file");
1742 buf
= g_malloc0(65536);
1744 seek_result
= lseek(fd
, current_length
, SEEK_SET
);
1745 if (seek_result
< 0) {
1747 error_setg_errno(errp
, -result
,
1748 "Failed to seek to the old end of file");
1753 num
= MIN(left
, 65536);
1754 result
= write(fd
, buf
, num
);
1757 error_setg_errno(errp
, -result
,
1758 "Could not write zeros for preallocation");
1767 error_setg_errno(errp
, -result
,
1768 "Could not flush file to disk");
1774 case PREALLOC_MODE_OFF
:
1775 if (ftruncate(fd
, offset
) != 0) {
1777 error_setg_errno(errp
, -result
, "Could not resize file");
1782 error_setg(errp
, "Unsupported preallocation mode: %s",
1783 PreallocMode_str(prealloc
));
1789 if (ftruncate(fd
, current_length
) < 0) {
1790 error_report("Failed to restore old file length: %s",
1799 static int raw_truncate(BlockDriverState
*bs
, int64_t offset
,
1800 PreallocMode prealloc
, Error
**errp
)
1802 BDRVRawState
*s
= bs
->opaque
;
1806 if (fstat(s
->fd
, &st
)) {
1808 error_setg_errno(errp
, -ret
, "Failed to fstat() the file");
1812 if (S_ISREG(st
.st_mode
)) {
1813 return raw_regular_truncate(s
->fd
, offset
, prealloc
, errp
);
1816 if (prealloc
!= PREALLOC_MODE_OFF
) {
1817 error_setg(errp
, "Preallocation mode '%s' unsupported for this "
1818 "non-regular file", PreallocMode_str(prealloc
));
1822 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1823 if (offset
> raw_getlength(bs
)) {
1824 error_setg(errp
, "Cannot grow device files");
1828 error_setg(errp
, "Resizing this file is not supported");
1836 static int64_t raw_getlength(BlockDriverState
*bs
)
1838 BDRVRawState
*s
= bs
->opaque
;
1844 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1845 struct disklabel dl
;
1847 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1849 return (uint64_t)dl
.d_secsize
*
1850 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1854 #elif defined(__NetBSD__)
1855 static int64_t raw_getlength(BlockDriverState
*bs
)
1857 BDRVRawState
*s
= bs
->opaque
;
1863 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
1864 struct dkwedge_info dkw
;
1866 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
1867 return dkw
.dkw_size
* 512;
1869 struct disklabel dl
;
1871 if (ioctl(fd
, DIOCGDINFO
, &dl
))
1873 return (uint64_t)dl
.d_secsize
*
1874 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
1879 #elif defined(__sun__)
1880 static int64_t raw_getlength(BlockDriverState
*bs
)
1882 BDRVRawState
*s
= bs
->opaque
;
1883 struct dk_minfo minfo
;
1893 * Use the DKIOCGMEDIAINFO ioctl to read the size.
1895 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
1897 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
1901 * There are reports that lseek on some devices fails, but
1902 * irc discussion said that contingency on contingency was overkill.
1904 size
= lseek(s
->fd
, 0, SEEK_END
);
1910 #elif defined(CONFIG_BSD)
1911 static int64_t raw_getlength(BlockDriverState
*bs
)
1913 BDRVRawState
*s
= bs
->opaque
;
1917 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1926 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
1929 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
1930 #ifdef DIOCGMEDIASIZE
1931 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
))
1932 #elif defined(DIOCGPART)
1935 if (ioctl(fd
, DIOCGPART
, &pi
) == 0)
1936 size
= pi
.media_size
;
1942 #if defined(__APPLE__) && defined(__MACH__)
1944 uint64_t sectors
= 0;
1945 uint32_t sector_size
= 0;
1947 if (ioctl(fd
, DKIOCGETBLOCKCOUNT
, §ors
) == 0
1948 && ioctl(fd
, DKIOCGETBLOCKSIZE
, §or_size
) == 0) {
1949 size
= sectors
* sector_size
;
1951 size
= lseek(fd
, 0LL, SEEK_END
);
1958 size
= lseek(fd
, 0LL, SEEK_END
);
1963 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
1966 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
1967 if (size
== 2048LL * (unsigned)-1)
1969 /* XXX no disc? maybe we need to reopen... */
1970 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
1977 size
= lseek(fd
, 0, SEEK_END
);
1985 static int64_t raw_getlength(BlockDriverState
*bs
)
1987 BDRVRawState
*s
= bs
->opaque
;
1996 size
= lseek(s
->fd
, 0, SEEK_END
);
2004 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
2007 BDRVRawState
*s
= bs
->opaque
;
2009 if (fstat(s
->fd
, &st
) < 0) {
2012 return (int64_t)st
.st_blocks
* 512;
2015 static int raw_co_create(BlockdevCreateOptions
*options
, Error
**errp
)
2017 BlockdevCreateOptionsFile
*file_opts
;
2021 /* Validate options and set default values */
2022 assert(options
->driver
== BLOCKDEV_DRIVER_FILE
);
2023 file_opts
= &options
->u
.file
;
2025 if (!file_opts
->has_nocow
) {
2026 file_opts
->nocow
= false;
2028 if (!file_opts
->has_preallocation
) {
2029 file_opts
->preallocation
= PREALLOC_MODE_OFF
;
2033 fd
= qemu_open(file_opts
->filename
, O_RDWR
| O_CREAT
| O_TRUNC
| O_BINARY
,
2037 error_setg_errno(errp
, -result
, "Could not create file");
2041 if (file_opts
->nocow
) {
2043 /* Set NOCOW flag to solve performance issue on fs like btrfs.
2044 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2045 * will be ignored since any failure of this operation should not
2046 * block the left work.
2049 if (ioctl(fd
, FS_IOC_GETFLAGS
, &attr
) == 0) {
2050 attr
|= FS_NOCOW_FL
;
2051 ioctl(fd
, FS_IOC_SETFLAGS
, &attr
);
2056 result
= raw_regular_truncate(fd
, file_opts
->size
, file_opts
->preallocation
,
2063 if (qemu_close(fd
) != 0 && result
== 0) {
2065 error_setg_errno(errp
, -result
, "Could not close the new file");
2071 static int coroutine_fn
raw_co_create_opts(const char *filename
, QemuOpts
*opts
,
2074 BlockdevCreateOptions options
;
2075 int64_t total_size
= 0;
2077 PreallocMode prealloc
;
2079 Error
*local_err
= NULL
;
2081 /* Skip file: protocol prefix */
2082 strstart(filename
, "file:", &filename
);
2084 /* Read out options */
2085 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2087 nocow
= qemu_opt_get_bool(opts
, BLOCK_OPT_NOCOW
, false);
2088 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
2089 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
2090 PREALLOC_MODE_OFF
, &local_err
);
2093 error_propagate(errp
, local_err
);
2097 options
= (BlockdevCreateOptions
) {
2098 .driver
= BLOCKDEV_DRIVER_FILE
,
2100 .filename
= (char *) filename
,
2102 .has_preallocation
= true,
2103 .preallocation
= prealloc
,
2108 return raw_co_create(&options
, errp
);
2112 * Find allocation range in @bs around offset @start.
2113 * May change underlying file descriptor's file offset.
2114 * If @start is not in a hole, store @start in @data, and the
2115 * beginning of the next hole in @hole, and return 0.
2116 * If @start is in a non-trailing hole, store @start in @hole and the
2117 * beginning of the next non-hole in @data, and return 0.
2118 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
2119 * If we can't find out, return a negative errno other than -ENXIO.
2121 static int find_allocation(BlockDriverState
*bs
, off_t start
,
2122 off_t
*data
, off_t
*hole
)
2124 #if defined SEEK_HOLE && defined SEEK_DATA
2125 BDRVRawState
*s
= bs
->opaque
;
2130 * D1. offs == start: start is in data
2131 * D2. offs > start: start is in a hole, next data at offs
2132 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
2133 * or start is beyond EOF
2134 * If the latter happens, the file has been truncated behind
2135 * our back since we opened it. All bets are off then.
2136 * Treating like a trailing hole is simplest.
2137 * D4. offs < 0, errno != ENXIO: we learned nothing
2139 offs
= lseek(s
->fd
, start
, SEEK_DATA
);
2141 return -errno
; /* D3 or D4 */
2145 /* This is not a valid return by lseek(). We are safe to just return
2146 * -EIO in this case, and we'll treat it like D4. */
2151 /* D2: in hole, next data at offs */
2157 /* D1: in data, end not yet known */
2161 * H1. offs == start: start is in a hole
2162 * If this happens here, a hole has been dug behind our back
2163 * since the previous lseek().
2164 * H2. offs > start: either start is in data, next hole at offs,
2165 * or start is in trailing hole, EOF at offs
2166 * Linux treats trailing holes like any other hole: offs ==
2167 * start. Solaris seeks to EOF instead: offs > start (blech).
2168 * If that happens here, a hole has been dug behind our back
2169 * since the previous lseek().
2170 * H3. offs < 0, errno = ENXIO: start is beyond EOF
2171 * If this happens, the file has been truncated behind our
2172 * back since we opened it. Treat it like a trailing hole.
2173 * H4. offs < 0, errno != ENXIO: we learned nothing
2174 * Pretend we know nothing at all, i.e. "forget" about D1.
2176 offs
= lseek(s
->fd
, start
, SEEK_HOLE
);
2178 return -errno
; /* D1 and (H3 or H4) */
2182 /* This is not a valid return by lseek(). We are safe to just return
2183 * -EIO in this case, and we'll treat it like H4. */
2189 * D1 and H2: either in data, next hole at offs, or it was in
2190 * data but is now in a trailing hole. In the latter case,
2191 * all bets are off. Treating it as if it there was data all
2192 * the way to EOF is safe, so simply do that.
2207 * Returns the allocation status of the specified offset.
2209 * The block layer guarantees 'offset' and 'bytes' are within bounds.
2211 * 'pnum' is set to the number of bytes (including and immediately following
2212 * the specified offset) that are known to be in the same
2213 * allocated/unallocated state.
2215 * 'bytes' is the max value 'pnum' should be set to.
2217 static int coroutine_fn
raw_co_block_status(BlockDriverState
*bs
,
2220 int64_t bytes
, int64_t *pnum
,
2222 BlockDriverState
**file
)
2224 off_t data
= 0, hole
= 0;
2236 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
2239 ret
= find_allocation(bs
, offset
, &data
, &hole
);
2240 if (ret
== -ENXIO
) {
2243 ret
= BDRV_BLOCK_ZERO
;
2244 } else if (ret
< 0) {
2245 /* No info available, so pretend there are no holes */
2247 ret
= BDRV_BLOCK_DATA
;
2248 } else if (data
== offset
) {
2249 /* On a data extent, compute bytes to the end of the extent,
2250 * possibly including a partial sector at EOF. */
2251 *pnum
= MIN(bytes
, hole
- offset
);
2252 ret
= BDRV_BLOCK_DATA
;
2254 /* On a hole, compute bytes to the beginning of the next extent. */
2255 assert(hole
== offset
);
2256 *pnum
= MIN(bytes
, data
- offset
);
2257 ret
= BDRV_BLOCK_ZERO
;
2261 return ret
| BDRV_BLOCK_OFFSET_VALID
;
2264 #if defined(__linux__)
2265 /* Verify that the file is not in the page cache */
2266 static void check_cache_dropped(BlockDriverState
*bs
, Error
**errp
)
2268 const size_t window_size
= 128 * 1024 * 1024;
2269 BDRVRawState
*s
= bs
->opaque
;
2270 void *window
= NULL
;
2277 /* mincore(2) page status information requires 1 byte per page */
2278 page_size
= sysconf(_SC_PAGESIZE
);
2279 vec
= g_malloc(DIV_ROUND_UP(window_size
, page_size
));
2281 end
= raw_getlength(bs
);
2283 for (offset
= 0; offset
< end
; offset
+= window_size
) {
2290 /* Unmap previous window if size has changed */
2291 new_length
= MIN(end
- offset
, window_size
);
2292 if (new_length
!= length
) {
2293 munmap(window
, length
);
2298 new_window
= mmap(window
, new_length
, PROT_NONE
, MAP_PRIVATE
,
2300 if (new_window
== MAP_FAILED
) {
2301 error_setg_errno(errp
, errno
, "mmap failed");
2305 window
= new_window
;
2306 length
= new_length
;
2308 ret
= mincore(window
, length
, vec
);
2310 error_setg_errno(errp
, errno
, "mincore failed");
2314 vec_end
= DIV_ROUND_UP(length
, page_size
);
2315 for (i
= 0; i
< vec_end
; i
++) {
2317 error_setg(errp
, "page cache still in use!");
2324 munmap(window
, length
);
2329 #endif /* __linux__ */
2331 static void coroutine_fn
raw_co_invalidate_cache(BlockDriverState
*bs
,
2334 BDRVRawState
*s
= bs
->opaque
;
2339 error_setg_errno(errp
, -ret
, "The file descriptor is not open");
2343 if (s
->open_flags
& O_DIRECT
) {
2344 return; /* No host kernel page cache */
2347 #if defined(__linux__)
2348 /* This sets the scene for the next syscall... */
2349 ret
= bdrv_co_flush(bs
);
2351 error_setg_errno(errp
, -ret
, "flush failed");
2355 /* Linux does not invalidate pages that are dirty, locked, or mmapped by a
2356 * process. These limitations are okay because we just fsynced the file,
2357 * we don't use mmap, and the file should not be in use by other processes.
2359 ret
= posix_fadvise(s
->fd
, 0, 0, POSIX_FADV_DONTNEED
);
2360 if (ret
!= 0) { /* the return value is a positive errno */
2361 error_setg_errno(errp
, ret
, "fadvise failed");
2365 if (s
->check_cache_dropped
) {
2366 check_cache_dropped(bs
, errp
);
2368 #else /* __linux__ */
2369 /* Do nothing. Live migration to a remote host with cache.direct=off is
2370 * unsupported on other host operating systems. Cache consistency issues
2371 * may occur but no error is reported here, partly because that's the
2372 * historical behavior and partly because it's hard to differentiate valid
2373 * configurations that should not cause errors.
2375 #endif /* !__linux__ */
2378 static coroutine_fn BlockAIOCB
*raw_aio_pdiscard(BlockDriverState
*bs
,
2379 int64_t offset
, int bytes
,
2380 BlockCompletionFunc
*cb
, void *opaque
)
2382 BDRVRawState
*s
= bs
->opaque
;
2384 return paio_submit(bs
, s
->fd
, offset
, NULL
, bytes
,
2385 cb
, opaque
, QEMU_AIO_DISCARD
);
2388 static int coroutine_fn
raw_co_pwrite_zeroes(
2389 BlockDriverState
*bs
, int64_t offset
,
2390 int bytes
, BdrvRequestFlags flags
)
2392 BDRVRawState
*s
= bs
->opaque
;
2394 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
2395 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, bytes
,
2396 QEMU_AIO_WRITE_ZEROES
);
2397 } else if (s
->discard_zeroes
) {
2398 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, bytes
,
2404 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
2406 BDRVRawState
*s
= bs
->opaque
;
2408 bdi
->unallocated_blocks_are_zero
= s
->discard_zeroes
;
2412 static QemuOptsList raw_create_opts
= {
2413 .name
= "raw-create-opts",
2414 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
2417 .name
= BLOCK_OPT_SIZE
,
2418 .type
= QEMU_OPT_SIZE
,
2419 .help
= "Virtual disk size"
2422 .name
= BLOCK_OPT_NOCOW
,
2423 .type
= QEMU_OPT_BOOL
,
2424 .help
= "Turn off copy-on-write (valid only on btrfs)"
2427 .name
= BLOCK_OPT_PREALLOC
,
2428 .type
= QEMU_OPT_STRING
,
2429 .help
= "Preallocation mode (allowed values: off, falloc, full)"
2431 { /* end of list */ }
2435 static int raw_check_perm(BlockDriverState
*bs
, uint64_t perm
, uint64_t shared
,
2438 return raw_handle_perm_lock(bs
, RAW_PL_PREPARE
, perm
, shared
, errp
);
2441 static void raw_set_perm(BlockDriverState
*bs
, uint64_t perm
, uint64_t shared
)
2443 BDRVRawState
*s
= bs
->opaque
;
2444 raw_handle_perm_lock(bs
, RAW_PL_COMMIT
, perm
, shared
, NULL
);
2446 s
->shared_perm
= shared
;
2449 static void raw_abort_perm_update(BlockDriverState
*bs
)
2451 raw_handle_perm_lock(bs
, RAW_PL_ABORT
, 0, 0, NULL
);
2454 BlockDriver bdrv_file
= {
2455 .format_name
= "file",
2456 .protocol_name
= "file",
2457 .instance_size
= sizeof(BDRVRawState
),
2458 .bdrv_needs_filename
= true,
2459 .bdrv_probe
= NULL
, /* no probe for protocols */
2460 .bdrv_parse_filename
= raw_parse_filename
,
2461 .bdrv_file_open
= raw_open
,
2462 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2463 .bdrv_reopen_commit
= raw_reopen_commit
,
2464 .bdrv_reopen_abort
= raw_reopen_abort
,
2465 .bdrv_close
= raw_close
,
2466 .bdrv_co_create
= raw_co_create
,
2467 .bdrv_co_create_opts
= raw_co_create_opts
,
2468 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
2469 .bdrv_co_block_status
= raw_co_block_status
,
2470 .bdrv_co_invalidate_cache
= raw_co_invalidate_cache
,
2471 .bdrv_co_pwrite_zeroes
= raw_co_pwrite_zeroes
,
2473 .bdrv_co_preadv
= raw_co_preadv
,
2474 .bdrv_co_pwritev
= raw_co_pwritev
,
2475 .bdrv_aio_flush
= raw_aio_flush
,
2476 .bdrv_aio_pdiscard
= raw_aio_pdiscard
,
2477 .bdrv_refresh_limits
= raw_refresh_limits
,
2478 .bdrv_io_plug
= raw_aio_plug
,
2479 .bdrv_io_unplug
= raw_aio_unplug
,
2481 .bdrv_truncate
= raw_truncate
,
2482 .bdrv_getlength
= raw_getlength
,
2483 .bdrv_get_info
= raw_get_info
,
2484 .bdrv_get_allocated_file_size
2485 = raw_get_allocated_file_size
,
2486 .bdrv_check_perm
= raw_check_perm
,
2487 .bdrv_set_perm
= raw_set_perm
,
2488 .bdrv_abort_perm_update
= raw_abort_perm_update
,
2489 .create_opts
= &raw_create_opts
,
2492 /***********************************************/
2495 #if defined(__APPLE__) && defined(__MACH__)
2496 static kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
2497 CFIndex maxPathSize
, int flags
);
2498 static char *FindEjectableOpticalMedia(io_iterator_t
*mediaIterator
)
2500 kern_return_t kernResult
= KERN_FAILURE
;
2501 mach_port_t masterPort
;
2502 CFMutableDictionaryRef classesToMatch
;
2503 const char *matching_array
[] = {kIODVDMediaClass
, kIOCDMediaClass
};
2504 char *mediaType
= NULL
;
2506 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
2507 if ( KERN_SUCCESS
!= kernResult
) {
2508 printf( "IOMasterPort returned %d\n", kernResult
);
2512 for (index
= 0; index
< ARRAY_SIZE(matching_array
); index
++) {
2513 classesToMatch
= IOServiceMatching(matching_array
[index
]);
2514 if (classesToMatch
== NULL
) {
2515 error_report("IOServiceMatching returned NULL for %s",
2516 matching_array
[index
]);
2519 CFDictionarySetValue(classesToMatch
, CFSTR(kIOMediaEjectableKey
),
2521 kernResult
= IOServiceGetMatchingServices(masterPort
, classesToMatch
,
2523 if (kernResult
!= KERN_SUCCESS
) {
2524 error_report("Note: IOServiceGetMatchingServices returned %d",
2529 /* If a match was found, leave the loop */
2530 if (*mediaIterator
!= 0) {
2531 DPRINTF("Matching using %s\n", matching_array
[index
]);
2532 mediaType
= g_strdup(matching_array
[index
]);
2539 kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
2540 CFIndex maxPathSize
, int flags
)
2542 io_object_t nextMedia
;
2543 kern_return_t kernResult
= KERN_FAILURE
;
2545 nextMedia
= IOIteratorNext( mediaIterator
);
2548 CFTypeRef bsdPathAsCFString
;
2549 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
2550 if ( bsdPathAsCFString
) {
2551 size_t devPathLength
;
2552 strcpy( bsdPath
, _PATH_DEV
);
2553 if (flags
& BDRV_O_NOCACHE
) {
2554 strcat(bsdPath
, "r");
2556 devPathLength
= strlen( bsdPath
);
2557 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
2558 kernResult
= KERN_SUCCESS
;
2560 CFRelease( bsdPathAsCFString
);
2562 IOObjectRelease( nextMedia
);
2568 /* Sets up a real cdrom for use in QEMU */
2569 static bool setup_cdrom(char *bsd_path
, Error
**errp
)
2571 int index
, num_of_test_partitions
= 2, fd
;
2572 char test_partition
[MAXPATHLEN
];
2573 bool partition_found
= false;
2575 /* look for a working partition */
2576 for (index
= 0; index
< num_of_test_partitions
; index
++) {
2577 snprintf(test_partition
, sizeof(test_partition
), "%ss%d", bsd_path
,
2579 fd
= qemu_open(test_partition
, O_RDONLY
| O_BINARY
| O_LARGEFILE
);
2581 partition_found
= true;
2587 /* if a working partition on the device was not found */
2588 if (partition_found
== false) {
2589 error_setg(errp
, "Failed to find a working partition on disc");
2591 DPRINTF("Using %s as optical disc\n", test_partition
);
2592 pstrcpy(bsd_path
, MAXPATHLEN
, test_partition
);
2594 return partition_found
;
2597 /* Prints directions on mounting and unmounting a device */
2598 static void print_unmounting_directions(const char *file_name
)
2600 error_report("If device %s is mounted on the desktop, unmount"
2601 " it first before using it in QEMU", file_name
);
2602 error_report("Command to unmount device: diskutil unmountDisk %s",
2604 error_report("Command to mount device: diskutil mountDisk %s", file_name
);
2607 #endif /* defined(__APPLE__) && defined(__MACH__) */
2609 static int hdev_probe_device(const char *filename
)
2613 /* allow a dedicated CD-ROM driver to match with a higher priority */
2614 if (strstart(filename
, "/dev/cdrom", NULL
))
2617 if (stat(filename
, &st
) >= 0 &&
2618 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
2625 static int check_hdev_writable(BDRVRawState
*s
)
2627 #if defined(BLKROGET)
2628 /* Linux block devices can be configured "read-only" using blockdev(8).
2629 * This is independent of device node permissions and therefore open(2)
2630 * with O_RDWR succeeds. Actual writes fail with EPERM.
2632 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
2633 * check for read-only block devices so that Linux block devices behave
2639 if (fstat(s
->fd
, &st
)) {
2643 if (!S_ISBLK(st
.st_mode
)) {
2647 if (ioctl(s
->fd
, BLKROGET
, &readonly
) < 0) {
2654 #endif /* defined(BLKROGET) */
2658 static void hdev_parse_filename(const char *filename
, QDict
*options
,
2661 bdrv_parse_filename_strip_prefix(filename
, "host_device:", options
);
2664 static bool hdev_is_sg(BlockDriverState
*bs
)
2667 #if defined(__linux__)
2669 BDRVRawState
*s
= bs
->opaque
;
2671 struct sg_scsi_id scsiid
;
2675 if (stat(bs
->filename
, &st
) < 0 || !S_ISCHR(st
.st_mode
)) {
2679 ret
= ioctl(s
->fd
, SG_GET_VERSION_NUM
, &sg_version
);
2684 ret
= ioctl(s
->fd
, SG_GET_SCSI_ID
, &scsiid
);
2686 DPRINTF("SG device found: type=%d, version=%d\n",
2687 scsiid
.scsi_type
, sg_version
);
2696 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2699 BDRVRawState
*s
= bs
->opaque
;
2700 Error
*local_err
= NULL
;
2703 #if defined(__APPLE__) && defined(__MACH__)
2705 * Caution: while qdict_get_str() is fine, getting non-string types
2706 * would require more care. When @options come from -blockdev or
2707 * blockdev_add, its members are typed according to the QAPI
2708 * schema, but when they come from -drive, they're all QString.
2710 const char *filename
= qdict_get_str(options
, "filename");
2711 char bsd_path
[MAXPATHLEN
] = "";
2712 bool error_occurred
= false;
2714 /* If using a real cdrom */
2715 if (strcmp(filename
, "/dev/cdrom") == 0) {
2716 char *mediaType
= NULL
;
2717 kern_return_t ret_val
;
2718 io_iterator_t mediaIterator
= 0;
2720 mediaType
= FindEjectableOpticalMedia(&mediaIterator
);
2721 if (mediaType
== NULL
) {
2722 error_setg(errp
, "Please make sure your CD/DVD is in the optical"
2724 error_occurred
= true;
2725 goto hdev_open_Mac_error
;
2728 ret_val
= GetBSDPath(mediaIterator
, bsd_path
, sizeof(bsd_path
), flags
);
2729 if (ret_val
!= KERN_SUCCESS
) {
2730 error_setg(errp
, "Could not get BSD path for optical drive");
2731 error_occurred
= true;
2732 goto hdev_open_Mac_error
;
2735 /* If a real optical drive was not found */
2736 if (bsd_path
[0] == '\0') {
2737 error_setg(errp
, "Failed to obtain bsd path for optical drive");
2738 error_occurred
= true;
2739 goto hdev_open_Mac_error
;
2742 /* If using a cdrom disc and finding a partition on the disc failed */
2743 if (strncmp(mediaType
, kIOCDMediaClass
, 9) == 0 &&
2744 setup_cdrom(bsd_path
, errp
) == false) {
2745 print_unmounting_directions(bsd_path
);
2746 error_occurred
= true;
2747 goto hdev_open_Mac_error
;
2750 qdict_put_str(options
, "filename", bsd_path
);
2752 hdev_open_Mac_error
:
2754 if (mediaIterator
) {
2755 IOObjectRelease(mediaIterator
);
2757 if (error_occurred
) {
2761 #endif /* defined(__APPLE__) && defined(__MACH__) */
2763 s
->type
= FTYPE_FILE
;
2765 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
2767 error_propagate(errp
, local_err
);
2768 #if defined(__APPLE__) && defined(__MACH__)
2770 filename
= bsd_path
;
2772 /* if a physical device experienced an error while being opened */
2773 if (strncmp(filename
, "/dev/", 5) == 0) {
2774 print_unmounting_directions(filename
);
2776 #endif /* defined(__APPLE__) && defined(__MACH__) */
2780 /* Since this does ioctl the device must be already opened */
2781 bs
->sg
= hdev_is_sg(bs
);
2783 if (flags
& BDRV_O_RDWR
) {
2784 ret
= check_hdev_writable(s
);
2787 error_setg_errno(errp
, -ret
, "The device is not writable");
2795 #if defined(__linux__)
2797 static BlockAIOCB
*hdev_aio_ioctl(BlockDriverState
*bs
,
2798 unsigned long int req
, void *buf
,
2799 BlockCompletionFunc
*cb
, void *opaque
)
2801 BDRVRawState
*s
= bs
->opaque
;
2802 RawPosixAIOData
*acb
;
2805 if (fd_open(bs
) < 0)
2808 if (req
== SG_IO
&& s
->pr_mgr
) {
2809 struct sg_io_hdr
*io_hdr
= buf
;
2810 if (io_hdr
->cmdp
[0] == PERSISTENT_RESERVE_OUT
||
2811 io_hdr
->cmdp
[0] == PERSISTENT_RESERVE_IN
) {
2812 return pr_manager_execute(s
->pr_mgr
, bdrv_get_aio_context(bs
),
2813 s
->fd
, io_hdr
, cb
, opaque
);
2817 acb
= g_new(RawPosixAIOData
, 1);
2819 acb
->aio_type
= QEMU_AIO_IOCTL
;
2820 acb
->aio_fildes
= s
->fd
;
2821 acb
->aio_offset
= 0;
2822 acb
->aio_ioctl_buf
= buf
;
2823 acb
->aio_ioctl_cmd
= req
;
2824 pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
2825 return thread_pool_submit_aio(pool
, aio_worker
, acb
, cb
, opaque
);
2829 static int fd_open(BlockDriverState
*bs
)
2831 BDRVRawState
*s
= bs
->opaque
;
2833 /* this is just to ensure s->fd is sane (its called by io ops) */
2839 static coroutine_fn BlockAIOCB
*hdev_aio_pdiscard(BlockDriverState
*bs
,
2840 int64_t offset
, int bytes
,
2841 BlockCompletionFunc
*cb
, void *opaque
)
2843 BDRVRawState
*s
= bs
->opaque
;
2845 if (fd_open(bs
) < 0) {
2848 return paio_submit(bs
, s
->fd
, offset
, NULL
, bytes
,
2849 cb
, opaque
, QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2852 static coroutine_fn
int hdev_co_pwrite_zeroes(BlockDriverState
*bs
,
2853 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
2855 BDRVRawState
*s
= bs
->opaque
;
2862 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
2863 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, bytes
,
2864 QEMU_AIO_WRITE_ZEROES
|QEMU_AIO_BLKDEV
);
2865 } else if (s
->discard_zeroes
) {
2866 return paio_submit_co(bs
, s
->fd
, offset
, NULL
, bytes
,
2867 QEMU_AIO_DISCARD
|QEMU_AIO_BLKDEV
);
2872 static int coroutine_fn
hdev_co_create_opts(const char *filename
, QemuOpts
*opts
,
2877 struct stat stat_buf
;
2878 int64_t total_size
= 0;
2881 /* This function is used by both protocol block drivers and therefore either
2882 * of these prefixes may be given.
2883 * The return value has to be stored somewhere, otherwise this is an error
2884 * due to -Werror=unused-value. */
2886 strstart(filename
, "host_device:", &filename
) ||
2887 strstart(filename
, "host_cdrom:" , &filename
);
2891 ret
= raw_normalize_devicepath(&filename
);
2893 error_setg_errno(errp
, -ret
, "Could not normalize device path");
2897 /* Read out options */
2898 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2901 fd
= qemu_open(filename
, O_WRONLY
| O_BINARY
);
2904 error_setg_errno(errp
, -ret
, "Could not open device");
2908 if (fstat(fd
, &stat_buf
) < 0) {
2910 error_setg_errno(errp
, -ret
, "Could not stat device");
2911 } else if (!S_ISBLK(stat_buf
.st_mode
) && !S_ISCHR(stat_buf
.st_mode
)) {
2913 "The given file is neither a block nor a character device");
2915 } else if (lseek(fd
, 0, SEEK_END
) < total_size
) {
2916 error_setg(errp
, "Device is too small");
2920 if (!ret
&& total_size
) {
2921 uint8_t buf
[BDRV_SECTOR_SIZE
] = { 0 };
2922 int64_t zero_size
= MIN(BDRV_SECTOR_SIZE
, total_size
);
2923 if (lseek(fd
, 0, SEEK_SET
) == -1) {
2926 ret
= qemu_write_full(fd
, buf
, zero_size
);
2927 ret
= ret
== zero_size
? 0 : -errno
;
2934 static BlockDriver bdrv_host_device
= {
2935 .format_name
= "host_device",
2936 .protocol_name
= "host_device",
2937 .instance_size
= sizeof(BDRVRawState
),
2938 .bdrv_needs_filename
= true,
2939 .bdrv_probe_device
= hdev_probe_device
,
2940 .bdrv_parse_filename
= hdev_parse_filename
,
2941 .bdrv_file_open
= hdev_open
,
2942 .bdrv_close
= raw_close
,
2943 .bdrv_reopen_prepare
= raw_reopen_prepare
,
2944 .bdrv_reopen_commit
= raw_reopen_commit
,
2945 .bdrv_reopen_abort
= raw_reopen_abort
,
2946 .bdrv_co_create_opts
= hdev_co_create_opts
,
2947 .create_opts
= &raw_create_opts
,
2948 .bdrv_co_invalidate_cache
= raw_co_invalidate_cache
,
2949 .bdrv_co_pwrite_zeroes
= hdev_co_pwrite_zeroes
,
2951 .bdrv_co_preadv
= raw_co_preadv
,
2952 .bdrv_co_pwritev
= raw_co_pwritev
,
2953 .bdrv_aio_flush
= raw_aio_flush
,
2954 .bdrv_aio_pdiscard
= hdev_aio_pdiscard
,
2955 .bdrv_refresh_limits
= raw_refresh_limits
,
2956 .bdrv_io_plug
= raw_aio_plug
,
2957 .bdrv_io_unplug
= raw_aio_unplug
,
2959 .bdrv_truncate
= raw_truncate
,
2960 .bdrv_getlength
= raw_getlength
,
2961 .bdrv_get_info
= raw_get_info
,
2962 .bdrv_get_allocated_file_size
2963 = raw_get_allocated_file_size
,
2964 .bdrv_check_perm
= raw_check_perm
,
2965 .bdrv_set_perm
= raw_set_perm
,
2966 .bdrv_abort_perm_update
= raw_abort_perm_update
,
2967 .bdrv_probe_blocksizes
= hdev_probe_blocksizes
,
2968 .bdrv_probe_geometry
= hdev_probe_geometry
,
2970 /* generic scsi device */
2972 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
2976 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2977 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
2980 bdrv_parse_filename_strip_prefix(filename
, "host_cdrom:", options
);
2985 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2988 BDRVRawState
*s
= bs
->opaque
;
2992 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
2993 return raw_open_common(bs
, options
, flags
, O_NONBLOCK
, errp
);
2996 static int cdrom_probe_device(const char *filename
)
3002 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
);
3006 ret
= fstat(fd
, &st
);
3007 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
3011 /* Attempt to detect via a CDROM specific ioctl */
3012 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
3022 static bool cdrom_is_inserted(BlockDriverState
*bs
)
3024 BDRVRawState
*s
= bs
->opaque
;
3027 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
3028 return ret
== CDS_DISC_OK
;
3031 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
3033 BDRVRawState
*s
= bs
->opaque
;
3036 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
3037 perror("CDROMEJECT");
3039 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
3040 perror("CDROMEJECT");
3044 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
3046 BDRVRawState
*s
= bs
->opaque
;
3048 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
3050 * Note: an error can happen if the distribution automatically
3053 /* perror("CDROM_LOCKDOOR"); */
3057 static BlockDriver bdrv_host_cdrom
= {
3058 .format_name
= "host_cdrom",
3059 .protocol_name
= "host_cdrom",
3060 .instance_size
= sizeof(BDRVRawState
),
3061 .bdrv_needs_filename
= true,
3062 .bdrv_probe_device
= cdrom_probe_device
,
3063 .bdrv_parse_filename
= cdrom_parse_filename
,
3064 .bdrv_file_open
= cdrom_open
,
3065 .bdrv_close
= raw_close
,
3066 .bdrv_reopen_prepare
= raw_reopen_prepare
,
3067 .bdrv_reopen_commit
= raw_reopen_commit
,
3068 .bdrv_reopen_abort
= raw_reopen_abort
,
3069 .bdrv_co_create_opts
= hdev_co_create_opts
,
3070 .create_opts
= &raw_create_opts
,
3071 .bdrv_co_invalidate_cache
= raw_co_invalidate_cache
,
3074 .bdrv_co_preadv
= raw_co_preadv
,
3075 .bdrv_co_pwritev
= raw_co_pwritev
,
3076 .bdrv_aio_flush
= raw_aio_flush
,
3077 .bdrv_refresh_limits
= raw_refresh_limits
,
3078 .bdrv_io_plug
= raw_aio_plug
,
3079 .bdrv_io_unplug
= raw_aio_unplug
,
3081 .bdrv_truncate
= raw_truncate
,
3082 .bdrv_getlength
= raw_getlength
,
3083 .has_variable_length
= true,
3084 .bdrv_get_allocated_file_size
3085 = raw_get_allocated_file_size
,
3087 /* removable device support */
3088 .bdrv_is_inserted
= cdrom_is_inserted
,
3089 .bdrv_eject
= cdrom_eject
,
3090 .bdrv_lock_medium
= cdrom_lock_medium
,
3092 /* generic scsi device */
3093 .bdrv_aio_ioctl
= hdev_aio_ioctl
,
3095 #endif /* __linux__ */
3097 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
3098 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
3101 BDRVRawState
*s
= bs
->opaque
;
3102 Error
*local_err
= NULL
;
3107 ret
= raw_open_common(bs
, options
, flags
, 0, &local_err
);
3109 error_propagate(errp
, local_err
);
3113 /* make sure the door isn't locked at this time */
3114 ioctl(s
->fd
, CDIOCALLOW
);
3118 static int cdrom_probe_device(const char *filename
)
3120 if (strstart(filename
, "/dev/cd", NULL
) ||
3121 strstart(filename
, "/dev/acd", NULL
))
3126 static int cdrom_reopen(BlockDriverState
*bs
)
3128 BDRVRawState
*s
= bs
->opaque
;
3132 * Force reread of possibly changed/newly loaded disc,
3133 * FreeBSD seems to not notice sometimes...
3137 fd
= qemu_open(bs
->filename
, s
->open_flags
, 0644);
3144 /* make sure the door isn't locked at this time */
3145 ioctl(s
->fd
, CDIOCALLOW
);
3149 static bool cdrom_is_inserted(BlockDriverState
*bs
)
3151 return raw_getlength(bs
) > 0;
3154 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
3156 BDRVRawState
*s
= bs
->opaque
;
3161 (void) ioctl(s
->fd
, CDIOCALLOW
);
3164 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
3165 perror("CDIOCEJECT");
3167 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
3168 perror("CDIOCCLOSE");
3174 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
3176 BDRVRawState
*s
= bs
->opaque
;
3180 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
3182 * Note: an error can happen if the distribution automatically
3185 /* perror("CDROM_LOCKDOOR"); */
3189 static BlockDriver bdrv_host_cdrom
= {
3190 .format_name
= "host_cdrom",
3191 .protocol_name
= "host_cdrom",
3192 .instance_size
= sizeof(BDRVRawState
),
3193 .bdrv_needs_filename
= true,
3194 .bdrv_probe_device
= cdrom_probe_device
,
3195 .bdrv_parse_filename
= cdrom_parse_filename
,
3196 .bdrv_file_open
= cdrom_open
,
3197 .bdrv_close
= raw_close
,
3198 .bdrv_reopen_prepare
= raw_reopen_prepare
,
3199 .bdrv_reopen_commit
= raw_reopen_commit
,
3200 .bdrv_reopen_abort
= raw_reopen_abort
,
3201 .bdrv_co_create_opts
= hdev_co_create_opts
,
3202 .create_opts
= &raw_create_opts
,
3204 .bdrv_co_preadv
= raw_co_preadv
,
3205 .bdrv_co_pwritev
= raw_co_pwritev
,
3206 .bdrv_aio_flush
= raw_aio_flush
,
3207 .bdrv_refresh_limits
= raw_refresh_limits
,
3208 .bdrv_io_plug
= raw_aio_plug
,
3209 .bdrv_io_unplug
= raw_aio_unplug
,
3211 .bdrv_truncate
= raw_truncate
,
3212 .bdrv_getlength
= raw_getlength
,
3213 .has_variable_length
= true,
3214 .bdrv_get_allocated_file_size
3215 = raw_get_allocated_file_size
,
3217 /* removable device support */
3218 .bdrv_is_inserted
= cdrom_is_inserted
,
3219 .bdrv_eject
= cdrom_eject
,
3220 .bdrv_lock_medium
= cdrom_lock_medium
,
3222 #endif /* __FreeBSD__ */
3224 static void bdrv_file_init(void)
3227 * Register all the drivers. Note that order is important, the driver
3228 * registered last will get probed first.
3230 bdrv_register(&bdrv_file
);
3231 bdrv_register(&bdrv_host_device
);
3233 bdrv_register(&bdrv_host_cdrom
);
3235 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3236 bdrv_register(&bdrv_host_cdrom
);
3240 block_init(bdrv_file_init
);