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-io.h"
30 #include "block/block_int.h"
31 #include "qemu/module.h"
32 #include "qemu/option.h"
33 #include "qemu/units.h"
34 #include "qemu/memalign.h"
36 #include "block/thread-pool.h"
38 #include "block/raw-aio.h"
39 #include "qapi/qmp/qdict.h"
40 #include "qapi/qmp/qstring.h"
42 #include "scsi/pr-manager.h"
43 #include "scsi/constants.h"
45 #if defined(__APPLE__) && (__MACH__)
46 #include <sys/ioctl.h>
47 #if defined(HAVE_HOST_BLOCK_DEVICE)
49 #include <sys/param.h>
50 #include <sys/mount.h>
51 #include <IOKit/IOKitLib.h>
52 #include <IOKit/IOBSD.h>
53 #include <IOKit/storage/IOMediaBSDClient.h>
54 #include <IOKit/storage/IOMedia.h>
55 #include <IOKit/storage/IOCDMedia.h>
56 //#include <IOKit/storage/IOCDTypes.h>
57 #include <IOKit/storage/IODVDMedia.h>
58 #include <CoreFoundation/CoreFoundation.h>
59 #endif /* defined(HAVE_HOST_BLOCK_DEVICE) */
63 #define _POSIX_PTHREAD_SEMANTICS 1
67 #include <sys/ioctl.h>
68 #include <sys/param.h>
69 #include <sys/syscall.h>
71 #include <linux/cdrom.h>
74 #include <linux/hdreg.h>
75 #include <linux/magic.h>
81 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
84 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
85 #include <linux/falloc.h>
87 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
93 #include <sys/ioctl.h>
94 #include <sys/disklabel.h>
99 #include <sys/ioctl.h>
100 #include <sys/disklabel.h>
101 #include <sys/dkio.h>
102 #include <sys/disk.h>
106 #include <sys/ioctl.h>
107 #include <sys/diskslice.h>
110 /* OS X does not have O_DSYNC */
113 #define O_DSYNC O_SYNC
114 #elif defined(O_FSYNC)
115 #define O_DSYNC O_FSYNC
119 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
121 #define O_DIRECT O_DSYNC
127 #define MAX_BLOCKSIZE 4096
129 /* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
130 * leaving a few more bytes for its future use. */
131 #define RAW_LOCK_PERM_BASE 100
132 #define RAW_LOCK_SHARED_BASE 200
134 typedef struct BDRVRawState
{
141 /* The current permissions. */
143 uint64_t shared_perm
;
145 /* The perms bits whose corresponding bytes are already locked in
147 uint64_t locked_perm
;
148 uint64_t locked_shared_perm
;
150 uint64_t aio_max_batch
;
153 int perm_change_flags
;
154 BDRVReopenState
*reopen_state
;
157 bool has_write_zeroes
:1;
158 bool use_linux_aio
:1;
159 bool use_linux_io_uring
:1;
160 int page_cache_inconsistent
; /* errno from fdatasync failure */
162 bool needs_alignment
;
163 bool force_alignment
;
165 bool check_cache_dropped
;
167 uint64_t discard_nb_ok
;
168 uint64_t discard_nb_failed
;
169 uint64_t discard_bytes_ok
;
175 typedef struct BDRVRawReopenState
{
178 bool check_cache_dropped
;
179 } BDRVRawReopenState
;
181 static int fd_open(BlockDriverState
*bs
)
183 BDRVRawState
*s
= bs
->opaque
;
185 /* this is just to ensure s->fd is sane (its called by io ops) */
192 static int64_t coroutine_fn
raw_co_getlength(BlockDriverState
*bs
);
194 typedef struct RawPosixAIOData
{
195 BlockDriverState
*bs
;
216 PreallocMode prealloc
;
222 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
223 static int cdrom_reopen(BlockDriverState
*bs
);
227 * Elide EAGAIN and EACCES details when failing to lock, as this
228 * indicates that the specified file region is already locked by
229 * another process, which is considered a common scenario.
231 #define raw_lock_error_setg_errno(errp, err, fmt, ...) \
233 if ((err) == EAGAIN || (err) == EACCES) { \
234 error_setg((errp), (fmt), ## __VA_ARGS__); \
236 error_setg_errno((errp), (err), (fmt), ## __VA_ARGS__); \
240 #if defined(__NetBSD__)
241 static int raw_normalize_devicepath(const char **filename
, Error
**errp
)
243 static char namebuf
[PATH_MAX
];
244 const char *dp
, *fname
;
248 dp
= strrchr(fname
, '/');
249 if (lstat(fname
, &sb
) < 0) {
250 error_setg_file_open(errp
, errno
, fname
);
254 if (!S_ISBLK(sb
.st_mode
)) {
259 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
261 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
262 (int)(dp
- fname
), fname
, dp
+ 1);
265 warn_report("%s is a block device, using %s", fname
, *filename
);
270 static int raw_normalize_devicepath(const char **filename
, Error
**errp
)
277 * Get logical block size via ioctl. On success store it in @sector_size_p.
279 static int probe_logical_blocksize(int fd
, unsigned int *sector_size_p
)
281 unsigned int sector_size
;
282 bool success
= false;
286 static const unsigned long ioctl_list
[] = {
290 #ifdef DKIOCGETBLOCKSIZE
293 #ifdef DIOCGSECTORSIZE
298 /* Try a few ioctls to get the right size */
299 for (i
= 0; i
< (int)ARRAY_SIZE(ioctl_list
); i
++) {
300 if (ioctl(fd
, ioctl_list
[i
], §or_size
) >= 0) {
301 *sector_size_p
= sector_size
;
306 return success
? 0 : -errno
;
310 * Get physical block size of @fd.
311 * On success, store it in @blk_size and return 0.
312 * On failure, return -errno.
314 static int probe_physical_blocksize(int fd
, unsigned int *blk_size
)
317 if (ioctl(fd
, BLKPBSZGET
, blk_size
) < 0) {
327 * Returns true if no alignment restrictions are necessary even for files
328 * opened with O_DIRECT.
330 * raw_probe_alignment() probes the required alignment and assume that 1 means
331 * the probing failed, so it falls back to a safe default of 4k. This can be
332 * avoided if we know that byte alignment is okay for the file.
334 static bool dio_byte_aligned(int fd
)
340 ret
= fstatfs(fd
, &buf
);
341 if (ret
== 0 && buf
.f_type
== NFS_SUPER_MAGIC
) {
348 static bool raw_needs_alignment(BlockDriverState
*bs
)
350 BDRVRawState
*s
= bs
->opaque
;
352 if ((bs
->open_flags
& BDRV_O_NOCACHE
) != 0 && !dio_byte_aligned(s
->fd
)) {
356 return s
->force_alignment
;
359 /* Check if read is allowed with given memory buffer and length.
361 * This function is used to check O_DIRECT memory buffer and request alignment.
363 static bool raw_is_io_aligned(int fd
, void *buf
, size_t len
)
365 ssize_t ret
= pread(fd
, buf
, len
, 0);
372 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
373 * other errors (e.g. real I/O error), which could happen on a failed
374 * drive, since we only care about probing alignment.
376 if (errno
!= EINVAL
) {
384 static void raw_probe_alignment(BlockDriverState
*bs
, int fd
, Error
**errp
)
386 BDRVRawState
*s
= bs
->opaque
;
388 size_t max_align
= MAX(MAX_BLOCKSIZE
, qemu_real_host_page_size());
389 size_t alignments
[] = {1, 512, 1024, 2048, 4096};
391 /* For SCSI generic devices the alignment is not really used.
392 With buffered I/O, we don't have any restrictions. */
393 if (bdrv_is_sg(bs
) || !s
->needs_alignment
) {
394 bs
->bl
.request_alignment
= 1;
399 bs
->bl
.request_alignment
= 0;
401 /* Let's try to use the logical blocksize for the alignment. */
402 if (probe_logical_blocksize(fd
, &bs
->bl
.request_alignment
) < 0) {
403 bs
->bl
.request_alignment
= 0;
408 * The XFS ioctl definitions are shipped in extra packages that might
409 * not always be available. Since we just need the XFS_IOC_DIOINFO ioctl
410 * here, we simply use our own definition instead:
417 if (ioctl(fd
, _IOR('X', 30, struct xfs_dioattr
), &da
) >= 0) {
418 bs
->bl
.request_alignment
= da
.d_miniosz
;
419 /* The kernel returns wrong information for d_mem */
420 /* s->buf_align = da.d_mem; */
425 * If we could not get the sizes so far, we can only guess them. First try
426 * to detect request alignment, since it is more likely to succeed. Then
427 * try to detect buf_align, which cannot be detected in some cases (e.g.
428 * Gluster). If buf_align cannot be detected, we fallback to the value of
432 if (!bs
->bl
.request_alignment
) {
435 buf
= qemu_memalign(max_align
, max_align
);
436 for (i
= 0; i
< ARRAY_SIZE(alignments
); i
++) {
437 align
= alignments
[i
];
438 if (raw_is_io_aligned(fd
, buf
, align
)) {
439 /* Fallback to safe value. */
440 bs
->bl
.request_alignment
= (align
!= 1) ? align
: max_align
;
450 buf
= qemu_memalign(max_align
, 2 * max_align
);
451 for (i
= 0; i
< ARRAY_SIZE(alignments
); i
++) {
452 align
= alignments
[i
];
453 if (raw_is_io_aligned(fd
, buf
+ align
, max_align
)) {
454 /* Fallback to request_alignment. */
455 s
->buf_align
= (align
!= 1) ? align
: bs
->bl
.request_alignment
;
462 if (!s
->buf_align
|| !bs
->bl
.request_alignment
) {
463 error_setg(errp
, "Could not find working O_DIRECT alignment");
464 error_append_hint(errp
, "Try cache.direct=off\n");
468 static int check_hdev_writable(int fd
)
470 #if defined(BLKROGET)
471 /* Linux block devices can be configured "read-only" using blockdev(8).
472 * This is independent of device node permissions and therefore open(2)
473 * with O_RDWR succeeds. Actual writes fail with EPERM.
475 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
476 * check for read-only block devices so that Linux block devices behave
482 if (fstat(fd
, &st
)) {
486 if (!S_ISBLK(st
.st_mode
)) {
490 if (ioctl(fd
, BLKROGET
, &readonly
) < 0) {
497 #endif /* defined(BLKROGET) */
501 static void raw_parse_flags(int bdrv_flags
, int *open_flags
, bool has_writers
)
503 bool read_write
= false;
504 assert(open_flags
!= NULL
);
506 *open_flags
|= O_BINARY
;
507 *open_flags
&= ~O_ACCMODE
;
509 if (bdrv_flags
& BDRV_O_AUTO_RDONLY
) {
510 read_write
= has_writers
;
511 } else if (bdrv_flags
& BDRV_O_RDWR
) {
516 *open_flags
|= O_RDWR
;
518 *open_flags
|= O_RDONLY
;
521 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
522 * and O_DIRECT for no caching. */
523 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
524 *open_flags
|= O_DIRECT
;
528 static void raw_parse_filename(const char *filename
, QDict
*options
,
531 bdrv_parse_filename_strip_prefix(filename
, "file:", options
);
534 static QemuOptsList raw_runtime_opts
= {
536 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
540 .type
= QEMU_OPT_STRING
,
541 .help
= "File name of the image",
545 .type
= QEMU_OPT_STRING
,
546 .help
= "host AIO implementation (threads, native, io_uring)",
549 .name
= "aio-max-batch",
550 .type
= QEMU_OPT_NUMBER
,
551 .help
= "AIO max batch size (0 = auto handled by AIO backend, default: 0)",
555 .type
= QEMU_OPT_STRING
,
556 .help
= "file locking mode (on/off/auto, default: auto)",
559 .name
= "pr-manager",
560 .type
= QEMU_OPT_STRING
,
561 .help
= "id of persistent reservation manager object (default: none)",
563 #if defined(__linux__)
565 .name
= "drop-cache",
566 .type
= QEMU_OPT_BOOL
,
567 .help
= "invalidate page cache during live migration (default: on)",
571 .name
= "x-check-cache-dropped",
572 .type
= QEMU_OPT_BOOL
,
573 .help
= "check that page cache was dropped on live migration (default: off)"
575 { /* end of list */ }
579 static const char *const mutable_opts
[] = { "x-check-cache-dropped", NULL
};
581 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
582 int bdrv_flags
, int open_flags
,
583 bool device
, Error
**errp
)
585 BDRVRawState
*s
= bs
->opaque
;
587 Error
*local_err
= NULL
;
588 const char *filename
= NULL
;
590 BlockdevAioOptions aio
, aio_default
;
595 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
596 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
601 filename
= qemu_opt_get(opts
, "filename");
603 ret
= raw_normalize_devicepath(&filename
, errp
);
608 if (bdrv_flags
& BDRV_O_NATIVE_AIO
) {
609 aio_default
= BLOCKDEV_AIO_OPTIONS_NATIVE
;
610 #ifdef CONFIG_LINUX_IO_URING
611 } else if (bdrv_flags
& BDRV_O_IO_URING
) {
612 aio_default
= BLOCKDEV_AIO_OPTIONS_IO_URING
;
615 aio_default
= BLOCKDEV_AIO_OPTIONS_THREADS
;
618 aio
= qapi_enum_parse(&BlockdevAioOptions_lookup
,
619 qemu_opt_get(opts
, "aio"),
620 aio_default
, &local_err
);
622 error_propagate(errp
, local_err
);
627 s
->use_linux_aio
= (aio
== BLOCKDEV_AIO_OPTIONS_NATIVE
);
628 #ifdef CONFIG_LINUX_IO_URING
629 s
->use_linux_io_uring
= (aio
== BLOCKDEV_AIO_OPTIONS_IO_URING
);
632 s
->aio_max_batch
= qemu_opt_get_number(opts
, "aio-max-batch", 0);
634 locking
= qapi_enum_parse(&OnOffAuto_lookup
,
635 qemu_opt_get(opts
, "locking"),
636 ON_OFF_AUTO_AUTO
, &local_err
);
638 error_propagate(errp
, local_err
);
645 if (!qemu_has_ofd_lock()) {
646 warn_report("File lock requested but OFD locking syscall is "
647 "unavailable, falling back to POSIX file locks");
648 error_printf("Due to the implementation, locks can be lost "
652 case ON_OFF_AUTO_OFF
:
655 case ON_OFF_AUTO_AUTO
:
656 s
->use_lock
= qemu_has_ofd_lock();
662 str
= qemu_opt_get(opts
, "pr-manager");
664 s
->pr_mgr
= pr_manager_lookup(str
, &local_err
);
666 error_propagate(errp
, local_err
);
672 s
->drop_cache
= qemu_opt_get_bool(opts
, "drop-cache", true);
673 s
->check_cache_dropped
= qemu_opt_get_bool(opts
, "x-check-cache-dropped",
676 s
->open_flags
= open_flags
;
677 raw_parse_flags(bdrv_flags
, &s
->open_flags
, false);
680 fd
= qemu_open(filename
, s
->open_flags
, errp
);
681 ret
= fd
< 0 ? -errno
: 0;
691 /* Check s->open_flags rather than bdrv_flags due to auto-read-only */
692 if (s
->open_flags
& O_RDWR
) {
693 ret
= check_hdev_writable(s
->fd
);
695 error_setg_errno(errp
, -ret
, "The device is not writable");
701 s
->shared_perm
= BLK_PERM_ALL
;
703 #ifdef CONFIG_LINUX_AIO
704 /* Currently Linux does AIO only for files opened with O_DIRECT */
705 if (s
->use_linux_aio
) {
706 if (!(s
->open_flags
& O_DIRECT
)) {
707 error_setg(errp
, "aio=native was specified, but it requires "
708 "cache.direct=on, which was not specified.");
712 if (!aio_setup_linux_aio(bdrv_get_aio_context(bs
), errp
)) {
713 error_prepend(errp
, "Unable to use native AIO: ");
718 if (s
->use_linux_aio
) {
719 error_setg(errp
, "aio=native was specified, but is not supported "
724 #endif /* !defined(CONFIG_LINUX_AIO) */
726 #ifdef CONFIG_LINUX_IO_URING
727 if (s
->use_linux_io_uring
) {
728 if (!aio_setup_linux_io_uring(bdrv_get_aio_context(bs
), errp
)) {
729 error_prepend(errp
, "Unable to use io_uring: ");
734 if (s
->use_linux_io_uring
) {
735 error_setg(errp
, "aio=io_uring was specified, but is not supported "
740 #endif /* !defined(CONFIG_LINUX_IO_URING) */
742 s
->has_discard
= true;
743 s
->has_write_zeroes
= true;
745 if (fstat(s
->fd
, &st
) < 0) {
747 error_setg_errno(errp
, errno
, "Could not stat file");
752 if (!S_ISREG(st
.st_mode
)) {
753 error_setg(errp
, "'%s' driver requires '%s' to be a regular file",
754 bs
->drv
->format_name
, bs
->filename
);
758 s
->has_fallocate
= true;
761 if (!(S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
762 error_setg(errp
, "'%s' driver requires '%s' to be either "
763 "a character or block device",
764 bs
->drv
->format_name
, bs
->filename
);
770 if (S_ISBLK(st
.st_mode
)) {
772 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
773 * not rely on the contents of discarded blocks unless using O_DIRECT.
774 * Same for BLKZEROOUT.
776 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
777 s
->has_write_zeroes
= false;
782 if (S_ISCHR(st
.st_mode
)) {
784 * The file is a char device (disk), which on FreeBSD isn't behind
785 * a pager, so force all requests to be aligned. This is needed
786 * so QEMU makes sure all IO operations on the device are aligned
787 * to sector size, or else FreeBSD will reject them with EINVAL.
789 s
->force_alignment
= true;
792 s
->needs_alignment
= raw_needs_alignment(bs
);
794 bs
->supported_zero_flags
= BDRV_REQ_MAY_UNMAP
| BDRV_REQ_NO_FALLBACK
;
795 if (S_ISREG(st
.st_mode
)) {
796 /* When extending regular files, we get zeros from the OS */
797 bs
->supported_truncate_flags
= BDRV_REQ_ZERO_WRITE
;
801 if (ret
< 0 && s
->fd
!= -1) {
804 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
811 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
814 BDRVRawState
*s
= bs
->opaque
;
816 s
->type
= FTYPE_FILE
;
817 return raw_open_common(bs
, options
, flags
, 0, false, errp
);
826 #define PERM_FOREACH(i) \
827 for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
829 /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
830 * file; if @unlock == true, also unlock the unneeded bytes.
831 * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
833 static int raw_apply_lock_bytes(BDRVRawState
*s
, int fd
,
834 uint64_t perm_lock_bits
,
835 uint64_t shared_perm_lock_bits
,
836 bool unlock
, Error
**errp
)
840 uint64_t locked_perm
, locked_shared_perm
;
843 locked_perm
= s
->locked_perm
;
844 locked_shared_perm
= s
->locked_shared_perm
;
847 * We don't have the previous bits, just lock/unlock for each of the
851 locked_perm
= BLK_PERM_ALL
;
852 locked_shared_perm
= BLK_PERM_ALL
;
855 locked_shared_perm
= 0;
860 int off
= RAW_LOCK_PERM_BASE
+ i
;
861 uint64_t bit
= (1ULL << i
);
862 if ((perm_lock_bits
& bit
) && !(locked_perm
& bit
)) {
863 ret
= qemu_lock_fd(fd
, off
, 1, false);
865 raw_lock_error_setg_errno(errp
, -ret
, "Failed to lock byte %d",
869 s
->locked_perm
|= bit
;
871 } else if (unlock
&& (locked_perm
& bit
) && !(perm_lock_bits
& bit
)) {
872 ret
= qemu_unlock_fd(fd
, off
, 1);
874 error_setg_errno(errp
, -ret
, "Failed to unlock byte %d", off
);
877 s
->locked_perm
&= ~bit
;
882 int off
= RAW_LOCK_SHARED_BASE
+ i
;
883 uint64_t bit
= (1ULL << i
);
884 if ((shared_perm_lock_bits
& bit
) && !(locked_shared_perm
& bit
)) {
885 ret
= qemu_lock_fd(fd
, off
, 1, false);
887 raw_lock_error_setg_errno(errp
, -ret
, "Failed to lock byte %d",
891 s
->locked_shared_perm
|= bit
;
893 } else if (unlock
&& (locked_shared_perm
& bit
) &&
894 !(shared_perm_lock_bits
& bit
)) {
895 ret
= qemu_unlock_fd(fd
, off
, 1);
897 error_setg_errno(errp
, -ret
, "Failed to unlock byte %d", off
);
900 s
->locked_shared_perm
&= ~bit
;
907 /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
908 static int raw_check_lock_bytes(int fd
, uint64_t perm
, uint64_t shared_perm
,
915 int off
= RAW_LOCK_SHARED_BASE
+ i
;
916 uint64_t p
= 1ULL << i
;
918 ret
= qemu_lock_fd_test(fd
, off
, 1, true);
920 char *perm_name
= bdrv_perm_names(p
);
922 raw_lock_error_setg_errno(errp
, -ret
,
923 "Failed to get \"%s\" lock",
931 int off
= RAW_LOCK_PERM_BASE
+ i
;
932 uint64_t p
= 1ULL << i
;
933 if (!(shared_perm
& p
)) {
934 ret
= qemu_lock_fd_test(fd
, off
, 1, true);
936 char *perm_name
= bdrv_perm_names(p
);
938 raw_lock_error_setg_errno(errp
, -ret
,
939 "Failed to get shared \"%s\" lock",
949 static int raw_handle_perm_lock(BlockDriverState
*bs
,
951 uint64_t new_perm
, uint64_t new_shared
,
954 BDRVRawState
*s
= bs
->opaque
;
956 Error
*local_err
= NULL
;
962 if (bdrv_get_flags(bs
) & BDRV_O_INACTIVE
) {
968 if ((s
->perm
| new_perm
) == s
->perm
&&
969 (s
->shared_perm
& new_shared
) == s
->shared_perm
)
972 * We are going to unlock bytes, it should not fail. If it fail due
973 * to some fs-dependent permission-unrelated reasons (which occurs
974 * sometimes on NFS and leads to abort in bdrv_replace_child) we
975 * can't prevent such errors by any check here. And we ignore them
976 * anyway in ABORT and COMMIT.
980 ret
= raw_apply_lock_bytes(s
, s
->fd
, s
->perm
| new_perm
,
981 ~s
->shared_perm
| ~new_shared
,
984 ret
= raw_check_lock_bytes(s
->fd
, new_perm
, new_shared
, errp
);
988 error_append_hint(errp
,
989 "Is another process using the image [%s]?\n",
992 /* fall through to unlock bytes. */
994 raw_apply_lock_bytes(s
, s
->fd
, s
->perm
, ~s
->shared_perm
,
997 /* Theoretically the above call only unlocks bytes and it cannot
998 * fail. Something weird happened, report it.
1000 warn_report_err(local_err
);
1004 raw_apply_lock_bytes(s
, s
->fd
, new_perm
, ~new_shared
,
1007 /* Theoretically the above call only unlocks bytes and it cannot
1008 * fail. Something weird happened, report it.
1010 warn_report_err(local_err
);
1017 /* Sets a specific flag */
1018 static int fcntl_setfl(int fd
, int flag
)
1022 flags
= fcntl(fd
, F_GETFL
);
1026 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1) {
1032 static int raw_reconfigure_getfd(BlockDriverState
*bs
, int flags
,
1033 int *open_flags
, uint64_t perm
, bool force_dup
,
1036 BDRVRawState
*s
= bs
->opaque
;
1039 bool has_writers
= perm
&
1040 (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_RESIZE
);
1041 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
1043 fcntl_flags
|= O_NOATIME
;
1047 if (s
->type
== FTYPE_CD
) {
1048 *open_flags
|= O_NONBLOCK
;
1051 raw_parse_flags(flags
, open_flags
, has_writers
);
1054 /* Not all operating systems have O_ASYNC, and those that don't
1055 * will not let us track the state into rs->open_flags (typically
1056 * you achieve the same effect with an ioctl, for example I_SETSIG
1057 * on Solaris). But we do not use O_ASYNC, so that's fine.
1059 assert((s
->open_flags
& O_ASYNC
) == 0);
1062 if (!force_dup
&& *open_flags
== s
->open_flags
) {
1063 /* We're lucky, the existing fd is fine */
1067 if ((*open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
1068 /* dup the original fd */
1069 fd
= qemu_dup(s
->fd
);
1071 ret
= fcntl_setfl(fd
, *open_flags
);
1079 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
1081 const char *normalized_filename
= bs
->filename
;
1082 ret
= raw_normalize_devicepath(&normalized_filename
, errp
);
1084 fd
= qemu_open(normalized_filename
, *open_flags
, errp
);
1091 if (fd
!= -1 && (*open_flags
& O_RDWR
)) {
1092 ret
= check_hdev_writable(fd
);
1095 error_setg_errno(errp
, -ret
, "The device is not writable");
1103 static int raw_reopen_prepare(BDRVReopenState
*state
,
1104 BlockReopenQueue
*queue
, Error
**errp
)
1107 BDRVRawReopenState
*rs
;
1111 assert(state
!= NULL
);
1112 assert(state
->bs
!= NULL
);
1114 s
= state
->bs
->opaque
;
1116 state
->opaque
= g_new0(BDRVRawReopenState
, 1);
1119 /* Handle options changes */
1120 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
1121 if (!qemu_opts_absorb_qdict(opts
, state
->options
, errp
)) {
1126 rs
->drop_cache
= qemu_opt_get_bool_del(opts
, "drop-cache", true);
1127 rs
->check_cache_dropped
=
1128 qemu_opt_get_bool_del(opts
, "x-check-cache-dropped", false);
1130 /* This driver's reopen function doesn't currently allow changing
1131 * other options, so let's put them back in the original QDict and
1132 * bdrv_reopen_prepare() will detect changes and complain. */
1133 qemu_opts_to_qdict(opts
, state
->options
);
1136 * As part of reopen prepare we also want to create new fd by
1137 * raw_reconfigure_getfd(). But it wants updated "perm", when in
1138 * bdrv_reopen_multiple() .bdrv_reopen_prepare() callback called prior to
1139 * permission update. Happily, permission update is always a part (a seprate
1140 * stage) of bdrv_reopen_multiple() so we can rely on this fact and
1141 * reconfigure fd in raw_check_perm().
1144 s
->reopen_state
= state
;
1148 qemu_opts_del(opts
);
1152 static void raw_reopen_commit(BDRVReopenState
*state
)
1154 BDRVRawReopenState
*rs
= state
->opaque
;
1155 BDRVRawState
*s
= state
->bs
->opaque
;
1157 s
->drop_cache
= rs
->drop_cache
;
1158 s
->check_cache_dropped
= rs
->check_cache_dropped
;
1159 s
->open_flags
= rs
->open_flags
;
1160 g_free(state
->opaque
);
1161 state
->opaque
= NULL
;
1163 assert(s
->reopen_state
== state
);
1164 s
->reopen_state
= NULL
;
1168 static void raw_reopen_abort(BDRVReopenState
*state
)
1170 BDRVRawReopenState
*rs
= state
->opaque
;
1171 BDRVRawState
*s
= state
->bs
->opaque
;
1173 /* nothing to do if NULL, we didn't get far enough */
1178 g_free(state
->opaque
);
1179 state
->opaque
= NULL
;
1181 assert(s
->reopen_state
== state
);
1182 s
->reopen_state
= NULL
;
1185 static int hdev_get_max_hw_transfer(int fd
, struct stat
*st
)
1188 if (S_ISBLK(st
->st_mode
)) {
1189 unsigned short max_sectors
= 0;
1190 if (ioctl(fd
, BLKSECTGET
, &max_sectors
) == 0) {
1191 return max_sectors
* 512;
1195 if (ioctl(fd
, BLKSECTGET
, &max_bytes
) == 0) {
1205 static int hdev_get_max_segments(int fd
, struct stat
*st
)
1210 char *sysfspath
= NULL
;
1215 if (S_ISCHR(st
->st_mode
)) {
1216 if (ioctl(fd
, SG_GET_SG_TABLESIZE
, &ret
) == 0) {
1222 if (!S_ISBLK(st
->st_mode
)) {
1226 sysfspath
= g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
1227 major(st
->st_rdev
), minor(st
->st_rdev
));
1228 sysfd
= open(sysfspath
, O_RDONLY
);
1233 ret
= RETRY_ON_EINTR(read(sysfd
, buf
, sizeof(buf
) - 1));
1237 } else if (ret
== 0) {
1242 /* The file is ended with '\n', pass 'end' to accept that. */
1243 ret
= qemu_strtol(buf
, &end
, 10, &max_segments
);
1244 if (ret
== 0 && end
&& *end
== '\n') {
1259 static void raw_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1261 BDRVRawState
*s
= bs
->opaque
;
1264 s
->needs_alignment
= raw_needs_alignment(bs
);
1265 raw_probe_alignment(bs
, s
->fd
, errp
);
1267 bs
->bl
.min_mem_alignment
= s
->buf_align
;
1268 bs
->bl
.opt_mem_alignment
= MAX(s
->buf_align
, qemu_real_host_page_size());
1271 * Maximum transfers are best effort, so it is okay to ignore any
1272 * errors. That said, based on the man page errors in fstat would be
1273 * very much unexpected; the only possible case seems to be ENOMEM.
1275 if (fstat(s
->fd
, &st
)) {
1279 #if defined(__APPLE__) && (__MACH__)
1282 if (!fstatfs(s
->fd
, &buf
)) {
1283 bs
->bl
.opt_transfer
= buf
.f_iosize
;
1284 bs
->bl
.pdiscard_alignment
= buf
.f_bsize
;
1288 if (bdrv_is_sg(bs
) || S_ISBLK(st
.st_mode
)) {
1289 int ret
= hdev_get_max_hw_transfer(s
->fd
, &st
);
1291 if (ret
> 0 && ret
<= BDRV_REQUEST_MAX_BYTES
) {
1292 bs
->bl
.max_hw_transfer
= ret
;
1295 ret
= hdev_get_max_segments(s
->fd
, &st
);
1297 bs
->bl
.max_hw_iov
= ret
;
1302 static int check_for_dasd(int fd
)
1305 struct dasd_information2_t info
= {0};
1307 return ioctl(fd
, BIODASDINFO2
, &info
);
1314 * Try to get @bs's logical and physical block size.
1315 * On success, store them in @bsz and return zero.
1316 * On failure, return negative errno.
1318 static int hdev_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
1320 BDRVRawState
*s
= bs
->opaque
;
1323 /* If DASD, get blocksizes */
1324 if (check_for_dasd(s
->fd
) < 0) {
1327 ret
= probe_logical_blocksize(s
->fd
, &bsz
->log
);
1331 return probe_physical_blocksize(s
->fd
, &bsz
->phys
);
1335 * Try to get @bs's geometry: cyls, heads, sectors.
1336 * On success, store them in @geo and return 0.
1337 * On failure return -errno.
1338 * (Allows block driver to assign default geometry values that guest sees)
1341 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
1343 BDRVRawState
*s
= bs
->opaque
;
1344 struct hd_geometry ioctl_geo
= {0};
1346 /* If DASD, get its geometry */
1347 if (check_for_dasd(s
->fd
) < 0) {
1350 if (ioctl(s
->fd
, HDIO_GETGEO
, &ioctl_geo
) < 0) {
1353 /* HDIO_GETGEO may return success even though geo contains zeros
1354 (e.g. certain multipath setups) */
1355 if (!ioctl_geo
.heads
|| !ioctl_geo
.sectors
|| !ioctl_geo
.cylinders
) {
1358 /* Do not return a geometry for partition */
1359 if (ioctl_geo
.start
!= 0) {
1362 geo
->heads
= ioctl_geo
.heads
;
1363 geo
->sectors
= ioctl_geo
.sectors
;
1364 geo
->cylinders
= ioctl_geo
.cylinders
;
1368 #else /* __linux__ */
1369 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
1375 #if defined(__linux__)
1376 static int handle_aiocb_ioctl(void *opaque
)
1378 RawPosixAIOData
*aiocb
= opaque
;
1381 ret
= RETRY_ON_EINTR(
1382 ioctl(aiocb
->aio_fildes
, aiocb
->ioctl
.cmd
, aiocb
->ioctl
.buf
)
1392 static int handle_aiocb_flush(void *opaque
)
1394 RawPosixAIOData
*aiocb
= opaque
;
1395 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1398 if (s
->page_cache_inconsistent
) {
1399 return -s
->page_cache_inconsistent
;
1402 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
1404 trace_file_flush_fdatasync_failed(errno
);
1406 /* There is no clear definition of the semantics of a failing fsync(),
1407 * so we may have to assume the worst. The sad truth is that this
1408 * assumption is correct for Linux. Some pages are now probably marked
1409 * clean in the page cache even though they are inconsistent with the
1410 * on-disk contents. The next fdatasync() call would succeed, but no
1411 * further writeback attempt will be made. We can't get back to a state
1412 * in which we know what is on disk (we would have to rewrite
1413 * everything that was touched since the last fdatasync() at least), so
1414 * make bdrv_flush() fail permanently. Given that the behaviour isn't
1415 * really defined, I have little hope that other OSes are doing better.
1417 * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1419 if ((s
->open_flags
& O_DIRECT
) == 0) {
1420 s
->page_cache_inconsistent
= errno
;
1427 #ifdef CONFIG_PREADV
1429 static bool preadv_present
= true;
1432 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1434 return preadv(fd
, iov
, nr_iov
, offset
);
1438 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1440 return pwritev(fd
, iov
, nr_iov
, offset
);
1445 static bool preadv_present
= false;
1448 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1454 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1461 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
1465 len
= RETRY_ON_EINTR(
1466 (aiocb
->aio_type
& QEMU_AIO_WRITE
) ?
1467 qemu_pwritev(aiocb
->aio_fildes
,
1470 aiocb
->aio_offset
) :
1471 qemu_preadv(aiocb
->aio_fildes
,
1484 * Read/writes the data to/from a given linear buffer.
1486 * Returns the number of bytes handles or -errno in case of an error. Short
1487 * reads are only returned if the end of the file is reached.
1489 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
1494 while (offset
< aiocb
->aio_nbytes
) {
1495 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1496 len
= pwrite(aiocb
->aio_fildes
,
1497 (const char *)buf
+ offset
,
1498 aiocb
->aio_nbytes
- offset
,
1499 aiocb
->aio_offset
+ offset
);
1501 len
= pread(aiocb
->aio_fildes
,
1503 aiocb
->aio_nbytes
- offset
,
1504 aiocb
->aio_offset
+ offset
);
1506 if (len
== -1 && errno
== EINTR
) {
1508 } else if (len
== -1 && errno
== EINVAL
&&
1509 (aiocb
->bs
->open_flags
& BDRV_O_NOCACHE
) &&
1510 !(aiocb
->aio_type
& QEMU_AIO_WRITE
) &&
1512 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1513 * after a short read. Assume that O_DIRECT short reads only occur
1514 * at EOF. Therefore this is a short read, not an I/O error.
1517 } else if (len
== -1) {
1520 } else if (len
== 0) {
1529 static int handle_aiocb_rw(void *opaque
)
1531 RawPosixAIOData
*aiocb
= opaque
;
1535 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
1537 * If there is just a single buffer, and it is properly aligned
1538 * we can just use plain pread/pwrite without any problems.
1540 if (aiocb
->io
.niov
== 1) {
1541 nbytes
= handle_aiocb_rw_linear(aiocb
, aiocb
->io
.iov
->iov_base
);
1545 * We have more than one iovec, and all are properly aligned.
1547 * Try preadv/pwritev first and fall back to linearizing the
1548 * buffer if it's not supported.
1550 if (preadv_present
) {
1551 nbytes
= handle_aiocb_rw_vector(aiocb
);
1552 if (nbytes
== aiocb
->aio_nbytes
||
1553 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
1556 preadv_present
= false;
1560 * XXX(hch): short read/write. no easy way to handle the reminder
1561 * using these interfaces. For now retry using plain
1567 * Ok, we have to do it the hard way, copy all segments into
1568 * a single aligned buffer.
1570 buf
= qemu_try_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
1576 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1580 for (i
= 0; i
< aiocb
->io
.niov
; ++i
) {
1581 memcpy(p
, aiocb
->io
.iov
[i
].iov_base
, aiocb
->io
.iov
[i
].iov_len
);
1582 p
+= aiocb
->io
.iov
[i
].iov_len
;
1584 assert(p
- buf
== aiocb
->aio_nbytes
);
1587 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
1588 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
1590 size_t count
= aiocb
->aio_nbytes
, copy
;
1593 for (i
= 0; i
< aiocb
->io
.niov
&& count
; ++i
) {
1595 if (copy
> aiocb
->io
.iov
[i
].iov_len
) {
1596 copy
= aiocb
->io
.iov
[i
].iov_len
;
1598 memcpy(aiocb
->io
.iov
[i
].iov_base
, p
, copy
);
1599 assert(count
>= copy
);
1608 if (nbytes
== aiocb
->aio_nbytes
) {
1610 } else if (nbytes
>= 0 && nbytes
< aiocb
->aio_nbytes
) {
1611 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1614 iov_memset(aiocb
->io
.iov
, aiocb
->io
.niov
, nbytes
,
1615 0, aiocb
->aio_nbytes
- nbytes
);
1624 #if defined(CONFIG_FALLOCATE) || defined(BLKZEROOUT) || defined(BLKDISCARD)
1625 static int translate_err(int err
)
1627 if (err
== -ENODEV
|| err
== -ENOSYS
|| err
== -EOPNOTSUPP
||
1635 #ifdef CONFIG_FALLOCATE
1636 static int do_fallocate(int fd
, int mode
, off_t offset
, off_t len
)
1639 if (fallocate(fd
, mode
, offset
, len
) == 0) {
1642 } while (errno
== EINTR
);
1643 return translate_err(-errno
);
1647 static ssize_t
handle_aiocb_write_zeroes_block(RawPosixAIOData
*aiocb
)
1650 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1652 if (!s
->has_write_zeroes
) {
1657 /* The BLKZEROOUT implementation in the kernel doesn't set
1658 * BLKDEV_ZERO_NOFALLBACK, so we can't call this if we have to avoid slow
1660 if (!(aiocb
->aio_type
& QEMU_AIO_NO_FALLBACK
)) {
1662 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1663 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
1666 } while (errno
== EINTR
);
1668 ret
= translate_err(-errno
);
1669 if (ret
== -ENOTSUP
) {
1670 s
->has_write_zeroes
= false;
1678 static int handle_aiocb_write_zeroes(void *opaque
)
1680 RawPosixAIOData
*aiocb
= opaque
;
1681 #ifdef CONFIG_FALLOCATE
1682 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1686 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1687 return handle_aiocb_write_zeroes_block(aiocb
);
1690 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1691 if (s
->has_write_zeroes
) {
1692 int ret
= do_fallocate(s
->fd
, FALLOC_FL_ZERO_RANGE
,
1693 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1694 if (ret
== -ENOTSUP
) {
1695 s
->has_write_zeroes
= false;
1696 } else if (ret
== 0 || ret
!= -EINVAL
) {
1700 * Note: Some file systems do not like unaligned byte ranges, and
1701 * return EINVAL in such a case, though they should not do it according
1702 * to the man-page of fallocate(). Thus we simply ignore this return
1703 * value and try the other fallbacks instead.
1708 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1709 if (s
->has_discard
&& s
->has_fallocate
) {
1710 int ret
= do_fallocate(s
->fd
,
1711 FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1712 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1714 ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1715 if (ret
== 0 || ret
!= -ENOTSUP
) {
1718 s
->has_fallocate
= false;
1719 } else if (ret
== -EINVAL
) {
1721 * Some file systems like older versions of GPFS do not like un-
1722 * aligned byte ranges, and return EINVAL in such a case, though
1723 * they should not do it according to the man-page of fallocate().
1724 * Warn about the bad filesystem and try the final fallback instead.
1726 warn_report_once("Your file system is misbehaving: "
1727 "fallocate(FALLOC_FL_PUNCH_HOLE) returned EINVAL. "
1728 "Please report this bug to your file system "
1730 } else if (ret
!= -ENOTSUP
) {
1733 s
->has_discard
= false;
1738 #ifdef CONFIG_FALLOCATE
1739 /* Last resort: we are trying to extend the file with zeroed data. This
1740 * can be done via fallocate(fd, 0) */
1741 len
= raw_co_getlength(aiocb
->bs
);
1742 if (s
->has_fallocate
&& len
>= 0 && aiocb
->aio_offset
>= len
) {
1743 int ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1744 if (ret
== 0 || ret
!= -ENOTSUP
) {
1747 s
->has_fallocate
= false;
1754 static int handle_aiocb_write_zeroes_unmap(void *opaque
)
1756 RawPosixAIOData
*aiocb
= opaque
;
1757 BDRVRawState
*s G_GNUC_UNUSED
= aiocb
->bs
->opaque
;
1759 /* First try to write zeros and unmap at the same time */
1761 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1762 int ret
= do_fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1763 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1774 /* If we couldn't manage to unmap while guaranteed that the area reads as
1775 * all-zero afterwards, just write zeroes without unmapping */
1776 return handle_aiocb_write_zeroes(aiocb
);
1779 #ifndef HAVE_COPY_FILE_RANGE
1780 static off_t
copy_file_range(int in_fd
, off_t
*in_off
, int out_fd
,
1781 off_t
*out_off
, size_t len
, unsigned int flags
)
1783 #ifdef __NR_copy_file_range
1784 return syscall(__NR_copy_file_range
, in_fd
, in_off
, out_fd
,
1785 out_off
, len
, flags
);
1793 static int handle_aiocb_copy_range(void *opaque
)
1795 RawPosixAIOData
*aiocb
= opaque
;
1796 uint64_t bytes
= aiocb
->aio_nbytes
;
1797 off_t in_off
= aiocb
->aio_offset
;
1798 off_t out_off
= aiocb
->copy_range
.aio_offset2
;
1801 ssize_t ret
= copy_file_range(aiocb
->aio_fildes
, &in_off
,
1802 aiocb
->copy_range
.aio_fd2
, &out_off
,
1804 trace_file_copy_file_range(aiocb
->bs
, aiocb
->aio_fildes
, in_off
,
1805 aiocb
->copy_range
.aio_fd2
, out_off
, bytes
,
1808 /* No progress (e.g. when beyond EOF), let the caller fall back to
1827 static int handle_aiocb_discard(void *opaque
)
1829 RawPosixAIOData
*aiocb
= opaque
;
1831 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1833 if (!s
->has_discard
) {
1837 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1840 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1841 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
1844 } while (errno
== EINTR
);
1846 ret
= translate_err(-errno
);
1849 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1850 ret
= do_fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1851 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1852 ret
= translate_err(ret
);
1853 #elif defined(__APPLE__) && (__MACH__)
1854 fpunchhole_t fpunchhole
;
1855 fpunchhole
.fp_flags
= 0;
1856 fpunchhole
.reserved
= 0;
1857 fpunchhole
.fp_offset
= aiocb
->aio_offset
;
1858 fpunchhole
.fp_length
= aiocb
->aio_nbytes
;
1859 if (fcntl(s
->fd
, F_PUNCHHOLE
, &fpunchhole
) == -1) {
1860 ret
= errno
== ENODEV
? -ENOTSUP
: -errno
;
1867 if (ret
== -ENOTSUP
) {
1868 s
->has_discard
= false;
1874 * Help alignment probing by allocating the first block.
1876 * When reading with direct I/O from unallocated area on Gluster backed by XFS,
1877 * reading succeeds regardless of request length. In this case we fallback to
1878 * safe alignment which is not optimal. Allocating the first block avoids this
1881 * fd may be opened with O_DIRECT, but we don't know the buffer alignment or
1882 * request alignment, so we use safe values.
1884 * Returns: 0 on success, -errno on failure. Since this is an optimization,
1885 * caller may ignore failures.
1887 static int allocate_first_block(int fd
, size_t max_size
)
1889 size_t write_size
= (max_size
< MAX_BLOCKSIZE
)
1892 size_t max_align
= MAX(MAX_BLOCKSIZE
, qemu_real_host_page_size());
1897 buf
= qemu_memalign(max_align
, write_size
);
1898 memset(buf
, 0, write_size
);
1900 n
= RETRY_ON_EINTR(pwrite(fd
, buf
, write_size
, 0));
1902 ret
= (n
== -1) ? -errno
: 0;
1908 static int handle_aiocb_truncate(void *opaque
)
1910 RawPosixAIOData
*aiocb
= opaque
;
1912 int64_t current_length
= 0;
1915 int fd
= aiocb
->aio_fildes
;
1916 int64_t offset
= aiocb
->aio_offset
;
1917 PreallocMode prealloc
= aiocb
->truncate
.prealloc
;
1918 Error
**errp
= aiocb
->truncate
.errp
;
1920 if (fstat(fd
, &st
) < 0) {
1922 error_setg_errno(errp
, -result
, "Could not stat file");
1926 current_length
= st
.st_size
;
1927 if (current_length
> offset
&& prealloc
!= PREALLOC_MODE_OFF
) {
1928 error_setg(errp
, "Cannot use preallocation for shrinking files");
1933 #ifdef CONFIG_POSIX_FALLOCATE
1934 case PREALLOC_MODE_FALLOC
:
1936 * Truncating before posix_fallocate() makes it about twice slower on
1937 * file systems that do not support fallocate(), trying to check if a
1938 * block is allocated before allocating it, so don't do that here.
1940 if (offset
!= current_length
) {
1941 result
= -posix_fallocate(fd
, current_length
,
1942 offset
- current_length
);
1944 /* posix_fallocate() doesn't set errno. */
1945 error_setg_errno(errp
, -result
,
1946 "Could not preallocate new data");
1947 } else if (current_length
== 0) {
1949 * posix_fallocate() uses fallocate() if the filesystem
1950 * supports it, or fallback to manually writing zeroes. If
1951 * fallocate() was used, unaligned reads from the fallocated
1952 * area in raw_probe_alignment() will succeed, hence we need to
1953 * allocate the first block.
1955 * Optimize future alignment probing; ignore failures.
1957 allocate_first_block(fd
, offset
);
1964 case PREALLOC_MODE_FULL
:
1966 int64_t num
= 0, left
= offset
- current_length
;
1970 * Knowing the final size from the beginning could allow the file
1971 * system driver to do less allocations and possibly avoid
1972 * fragmentation of the file.
1974 if (ftruncate(fd
, offset
) != 0) {
1976 error_setg_errno(errp
, -result
, "Could not resize file");
1980 buf
= g_malloc0(65536);
1982 seek_result
= lseek(fd
, current_length
, SEEK_SET
);
1983 if (seek_result
< 0) {
1985 error_setg_errno(errp
, -result
,
1986 "Failed to seek to the old end of file");
1991 num
= MIN(left
, 65536);
1992 result
= write(fd
, buf
, num
);
1994 if (errno
== EINTR
) {
1998 error_setg_errno(errp
, -result
,
1999 "Could not write zeros for preallocation");
2008 error_setg_errno(errp
, -result
,
2009 "Could not flush file to disk");
2015 case PREALLOC_MODE_OFF
:
2016 if (ftruncate(fd
, offset
) != 0) {
2018 error_setg_errno(errp
, -result
, "Could not resize file");
2019 } else if (current_length
== 0 && offset
> current_length
) {
2020 /* Optimize future alignment probing; ignore failures. */
2021 allocate_first_block(fd
, offset
);
2026 error_setg(errp
, "Unsupported preallocation mode: %s",
2027 PreallocMode_str(prealloc
));
2033 if (ftruncate(fd
, current_length
) < 0) {
2034 error_report("Failed to restore old file length: %s",
2043 static int coroutine_fn
raw_thread_pool_submit(ThreadPoolFunc func
, void *arg
)
2045 return thread_pool_submit_co(func
, arg
);
2049 * Check if all memory in this vector is sector aligned.
2051 static bool bdrv_qiov_is_aligned(BlockDriverState
*bs
, QEMUIOVector
*qiov
)
2054 size_t alignment
= bdrv_min_mem_align(bs
);
2055 size_t len
= bs
->bl
.request_alignment
;
2058 for (i
= 0; i
< qiov
->niov
; i
++) {
2059 if ((uintptr_t) qiov
->iov
[i
].iov_base
% alignment
) {
2062 if (qiov
->iov
[i
].iov_len
% len
) {
2070 static int coroutine_fn
raw_co_prw(BlockDriverState
*bs
, uint64_t offset
,
2071 uint64_t bytes
, QEMUIOVector
*qiov
, int type
)
2073 BDRVRawState
*s
= bs
->opaque
;
2074 RawPosixAIOData acb
;
2076 if (fd_open(bs
) < 0)
2080 * When using O_DIRECT, the request must be aligned to be able to use
2081 * either libaio or io_uring interface. If not fail back to regular thread
2082 * pool read/write code which emulates this for us if we
2083 * set QEMU_AIO_MISALIGNED.
2085 if (s
->needs_alignment
&& !bdrv_qiov_is_aligned(bs
, qiov
)) {
2086 type
|= QEMU_AIO_MISALIGNED
;
2087 #ifdef CONFIG_LINUX_IO_URING
2088 } else if (s
->use_linux_io_uring
) {
2089 assert(qiov
->size
== bytes
);
2090 return luring_co_submit(bs
, s
->fd
, offset
, qiov
, type
);
2092 #ifdef CONFIG_LINUX_AIO
2093 } else if (s
->use_linux_aio
) {
2094 assert(qiov
->size
== bytes
);
2095 return laio_co_submit(s
->fd
, offset
, qiov
, type
, s
->aio_max_batch
);
2099 acb
= (RawPosixAIOData
) {
2101 .aio_fildes
= s
->fd
,
2103 .aio_offset
= offset
,
2104 .aio_nbytes
= bytes
,
2111 assert(qiov
->size
== bytes
);
2112 return raw_thread_pool_submit(handle_aiocb_rw
, &acb
);
2115 static int coroutine_fn
raw_co_preadv(BlockDriverState
*bs
, int64_t offset
,
2116 int64_t bytes
, QEMUIOVector
*qiov
,
2117 BdrvRequestFlags flags
)
2119 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_READ
);
2122 static int coroutine_fn
raw_co_pwritev(BlockDriverState
*bs
, int64_t offset
,
2123 int64_t bytes
, QEMUIOVector
*qiov
,
2124 BdrvRequestFlags flags
)
2126 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_WRITE
);
2129 static void coroutine_fn
raw_co_io_plug(BlockDriverState
*bs
)
2131 BDRVRawState
__attribute__((unused
)) *s
= bs
->opaque
;
2132 #ifdef CONFIG_LINUX_AIO
2133 if (s
->use_linux_aio
) {
2137 #ifdef CONFIG_LINUX_IO_URING
2138 if (s
->use_linux_io_uring
) {
2144 static void coroutine_fn
raw_co_io_unplug(BlockDriverState
*bs
)
2146 BDRVRawState
__attribute__((unused
)) *s
= bs
->opaque
;
2147 #ifdef CONFIG_LINUX_AIO
2148 if (s
->use_linux_aio
) {
2149 laio_io_unplug(s
->aio_max_batch
);
2152 #ifdef CONFIG_LINUX_IO_URING
2153 if (s
->use_linux_io_uring
) {
2159 static int coroutine_fn
raw_co_flush_to_disk(BlockDriverState
*bs
)
2161 BDRVRawState
*s
= bs
->opaque
;
2162 RawPosixAIOData acb
;
2170 acb
= (RawPosixAIOData
) {
2172 .aio_fildes
= s
->fd
,
2173 .aio_type
= QEMU_AIO_FLUSH
,
2176 #ifdef CONFIG_LINUX_IO_URING
2177 if (s
->use_linux_io_uring
) {
2178 return luring_co_submit(bs
, s
->fd
, 0, NULL
, QEMU_AIO_FLUSH
);
2181 return raw_thread_pool_submit(handle_aiocb_flush
, &acb
);
2184 static void raw_aio_attach_aio_context(BlockDriverState
*bs
,
2185 AioContext
*new_context
)
2187 BDRVRawState
__attribute__((unused
)) *s
= bs
->opaque
;
2188 #ifdef CONFIG_LINUX_AIO
2189 if (s
->use_linux_aio
) {
2190 Error
*local_err
= NULL
;
2191 if (!aio_setup_linux_aio(new_context
, &local_err
)) {
2192 error_reportf_err(local_err
, "Unable to use native AIO, "
2193 "falling back to thread pool: ");
2194 s
->use_linux_aio
= false;
2198 #ifdef CONFIG_LINUX_IO_URING
2199 if (s
->use_linux_io_uring
) {
2200 Error
*local_err
= NULL
;
2201 if (!aio_setup_linux_io_uring(new_context
, &local_err
)) {
2202 error_reportf_err(local_err
, "Unable to use linux io_uring, "
2203 "falling back to thread pool: ");
2204 s
->use_linux_io_uring
= false;
2210 static void raw_close(BlockDriverState
*bs
)
2212 BDRVRawState
*s
= bs
->opaque
;
2221 * Truncates the given regular file @fd to @offset and, when growing, fills the
2222 * new space according to @prealloc.
2224 * Returns: 0 on success, -errno on failure.
2226 static int coroutine_fn
2227 raw_regular_truncate(BlockDriverState
*bs
, int fd
, int64_t offset
,
2228 PreallocMode prealloc
, Error
**errp
)
2230 RawPosixAIOData acb
;
2232 acb
= (RawPosixAIOData
) {
2235 .aio_type
= QEMU_AIO_TRUNCATE
,
2236 .aio_offset
= offset
,
2238 .prealloc
= prealloc
,
2243 return raw_thread_pool_submit(handle_aiocb_truncate
, &acb
);
2246 static int coroutine_fn
raw_co_truncate(BlockDriverState
*bs
, int64_t offset
,
2247 bool exact
, PreallocMode prealloc
,
2248 BdrvRequestFlags flags
, Error
**errp
)
2250 BDRVRawState
*s
= bs
->opaque
;
2254 if (fstat(s
->fd
, &st
)) {
2256 error_setg_errno(errp
, -ret
, "Failed to fstat() the file");
2260 if (S_ISREG(st
.st_mode
)) {
2261 /* Always resizes to the exact @offset */
2262 return raw_regular_truncate(bs
, s
->fd
, offset
, prealloc
, errp
);
2265 if (prealloc
!= PREALLOC_MODE_OFF
) {
2266 error_setg(errp
, "Preallocation mode '%s' unsupported for this "
2267 "non-regular file", PreallocMode_str(prealloc
));
2271 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
2272 int64_t cur_length
= raw_co_getlength(bs
);
2274 if (offset
!= cur_length
&& exact
) {
2275 error_setg(errp
, "Cannot resize device files");
2277 } else if (offset
> cur_length
) {
2278 error_setg(errp
, "Cannot grow device files");
2282 error_setg(errp
, "Resizing this file is not supported");
2290 static int64_t coroutine_fn
raw_co_getlength(BlockDriverState
*bs
)
2292 BDRVRawState
*s
= bs
->opaque
;
2298 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
2299 struct disklabel dl
;
2301 if (ioctl(fd
, DIOCGDINFO
, &dl
))
2303 return (uint64_t)dl
.d_secsize
*
2304 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
2308 #elif defined(__NetBSD__)
2309 static int64_t coroutine_fn
raw_co_getlength(BlockDriverState
*bs
)
2311 BDRVRawState
*s
= bs
->opaque
;
2317 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
2318 struct dkwedge_info dkw
;
2320 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
2321 return dkw
.dkw_size
* 512;
2323 struct disklabel dl
;
2325 if (ioctl(fd
, DIOCGDINFO
, &dl
))
2327 return (uint64_t)dl
.d_secsize
*
2328 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
2333 #elif defined(__sun__)
2334 static int64_t coroutine_fn
raw_co_getlength(BlockDriverState
*bs
)
2336 BDRVRawState
*s
= bs
->opaque
;
2337 struct dk_minfo minfo
;
2347 * Use the DKIOCGMEDIAINFO ioctl to read the size.
2349 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
2351 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
2355 * There are reports that lseek on some devices fails, but
2356 * irc discussion said that contingency on contingency was overkill.
2358 size
= lseek(s
->fd
, 0, SEEK_END
);
2364 #elif defined(CONFIG_BSD)
2365 static int64_t coroutine_fn
raw_co_getlength(BlockDriverState
*bs
)
2367 BDRVRawState
*s
= bs
->opaque
;
2371 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2380 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2383 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
2385 #ifdef DIOCGMEDIASIZE
2386 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
)) {
2393 if (ioctl(fd
, DIOCGPART
, &pi
) == 0) {
2394 size
= pi
.media_size
;
2398 #if defined(DKIOCGETBLOCKCOUNT) && defined(DKIOCGETBLOCKSIZE)
2400 uint64_t sectors
= 0;
2401 uint32_t sector_size
= 0;
2403 if (ioctl(fd
, DKIOCGETBLOCKCOUNT
, §ors
) == 0
2404 && ioctl(fd
, DKIOCGETBLOCKSIZE
, §or_size
) == 0) {
2405 size
= sectors
* sector_size
;
2410 size
= lseek(fd
, 0LL, SEEK_END
);
2415 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2418 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
2419 if (size
== 2048LL * (unsigned)-1)
2421 /* XXX no disc? maybe we need to reopen... */
2422 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
2429 size
= lseek(fd
, 0, SEEK_END
);
2437 static int64_t coroutine_fn
raw_co_getlength(BlockDriverState
*bs
)
2439 BDRVRawState
*s
= bs
->opaque
;
2448 size
= lseek(s
->fd
, 0, SEEK_END
);
2456 static int64_t coroutine_fn
raw_co_get_allocated_file_size(BlockDriverState
*bs
)
2459 BDRVRawState
*s
= bs
->opaque
;
2461 if (fstat(s
->fd
, &st
) < 0) {
2464 return (int64_t)st
.st_blocks
* 512;
2467 static int coroutine_fn
2468 raw_co_create(BlockdevCreateOptions
*options
, Error
**errp
)
2470 BlockdevCreateOptionsFile
*file_opts
;
2471 Error
*local_err
= NULL
;
2473 uint64_t perm
, shared
;
2476 /* Validate options and set default values */
2477 assert(options
->driver
== BLOCKDEV_DRIVER_FILE
);
2478 file_opts
= &options
->u
.file
;
2480 if (!file_opts
->has_nocow
) {
2481 file_opts
->nocow
= false;
2483 if (!file_opts
->has_preallocation
) {
2484 file_opts
->preallocation
= PREALLOC_MODE_OFF
;
2486 if (!file_opts
->has_extent_size_hint
) {
2487 file_opts
->extent_size_hint
= 1 * MiB
;
2489 if (file_opts
->extent_size_hint
> UINT32_MAX
) {
2491 error_setg(errp
, "Extent size hint is too large");
2496 fd
= qemu_create(file_opts
->filename
, O_RDWR
| O_BINARY
, 0644, errp
);
2502 /* Take permissions: We want to discard everything, so we need
2503 * BLK_PERM_WRITE; and truncation to the desired size requires
2505 * On the other hand, we cannot share the RESIZE permission
2506 * because we promise that after this function, the file has the
2507 * size given in the options. If someone else were to resize it
2508 * concurrently, we could not guarantee that.
2509 * Note that after this function, we can no longer guarantee that
2510 * the file is not touched by a third party, so it may be resized
2512 perm
= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2513 shared
= BLK_PERM_ALL
& ~BLK_PERM_RESIZE
;
2515 /* Step one: Take locks */
2516 result
= raw_apply_lock_bytes(NULL
, fd
, perm
, ~shared
, false, errp
);
2521 /* Step two: Check that nobody else has taken conflicting locks */
2522 result
= raw_check_lock_bytes(fd
, perm
, shared
, errp
);
2524 error_append_hint(errp
,
2525 "Is another process using the image [%s]?\n",
2526 file_opts
->filename
);
2530 /* Clear the file by truncating it to 0 */
2531 result
= raw_regular_truncate(NULL
, fd
, 0, PREALLOC_MODE_OFF
, errp
);
2536 if (file_opts
->nocow
) {
2538 /* Set NOCOW flag to solve performance issue on fs like btrfs.
2539 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2540 * will be ignored since any failure of this operation should not
2541 * block the left work.
2544 if (ioctl(fd
, FS_IOC_GETFLAGS
, &attr
) == 0) {
2545 attr
|= FS_NOCOW_FL
;
2546 ioctl(fd
, FS_IOC_SETFLAGS
, &attr
);
2550 #ifdef FS_IOC_FSSETXATTR
2552 * Try to set the extent size hint. Failure is not fatal, and a warning is
2553 * only printed if the option was explicitly specified.
2556 struct fsxattr attr
;
2557 result
= ioctl(fd
, FS_IOC_FSGETXATTR
, &attr
);
2559 attr
.fsx_xflags
|= FS_XFLAG_EXTSIZE
;
2560 attr
.fsx_extsize
= file_opts
->extent_size_hint
;
2561 result
= ioctl(fd
, FS_IOC_FSSETXATTR
, &attr
);
2563 if (result
< 0 && file_opts
->has_extent_size_hint
&&
2564 file_opts
->extent_size_hint
)
2566 warn_report("Failed to set extent size hint: %s",
2572 /* Resize and potentially preallocate the file to the desired
2574 result
= raw_regular_truncate(NULL
, fd
, file_opts
->size
,
2575 file_opts
->preallocation
, errp
);
2581 raw_apply_lock_bytes(NULL
, fd
, 0, 0, true, &local_err
);
2583 /* The above call should not fail, and if it does, that does
2584 * not mean the whole creation operation has failed. So
2585 * report it the user for their convenience, but do not report
2586 * it to the caller. */
2587 warn_report_err(local_err
);
2591 if (qemu_close(fd
) != 0 && result
== 0) {
2593 error_setg_errno(errp
, -result
, "Could not close the new file");
2599 static int coroutine_fn GRAPH_RDLOCK
2600 raw_co_create_opts(BlockDriver
*drv
, const char *filename
,
2601 QemuOpts
*opts
, Error
**errp
)
2603 BlockdevCreateOptions options
;
2604 int64_t total_size
= 0;
2605 int64_t extent_size_hint
= 0;
2606 bool has_extent_size_hint
= false;
2608 PreallocMode prealloc
;
2610 Error
*local_err
= NULL
;
2612 /* Skip file: protocol prefix */
2613 strstart(filename
, "file:", &filename
);
2615 /* Read out options */
2616 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2618 if (qemu_opt_get(opts
, BLOCK_OPT_EXTENT_SIZE_HINT
)) {
2619 has_extent_size_hint
= true;
2621 qemu_opt_get_size_del(opts
, BLOCK_OPT_EXTENT_SIZE_HINT
, -1);
2623 nocow
= qemu_opt_get_bool(opts
, BLOCK_OPT_NOCOW
, false);
2624 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
2625 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
2626 PREALLOC_MODE_OFF
, &local_err
);
2629 error_propagate(errp
, local_err
);
2633 options
= (BlockdevCreateOptions
) {
2634 .driver
= BLOCKDEV_DRIVER_FILE
,
2636 .filename
= (char *) filename
,
2638 .has_preallocation
= true,
2639 .preallocation
= prealloc
,
2642 .has_extent_size_hint
= has_extent_size_hint
,
2643 .extent_size_hint
= extent_size_hint
,
2646 return raw_co_create(&options
, errp
);
2649 static int coroutine_fn
raw_co_delete_file(BlockDriverState
*bs
,
2655 if (!(stat(bs
->filename
, &st
) == 0) || !S_ISREG(st
.st_mode
)) {
2656 error_setg_errno(errp
, ENOENT
, "%s is not a regular file",
2661 ret
= unlink(bs
->filename
);
2664 error_setg_errno(errp
, -ret
, "Error when deleting file %s",
2672 * Find allocation range in @bs around offset @start.
2673 * May change underlying file descriptor's file offset.
2674 * If @start is not in a hole, store @start in @data, and the
2675 * beginning of the next hole in @hole, and return 0.
2676 * If @start is in a non-trailing hole, store @start in @hole and the
2677 * beginning of the next non-hole in @data, and return 0.
2678 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
2679 * If we can't find out, return a negative errno other than -ENXIO.
2681 static int find_allocation(BlockDriverState
*bs
, off_t start
,
2682 off_t
*data
, off_t
*hole
)
2684 #if defined SEEK_HOLE && defined SEEK_DATA
2685 BDRVRawState
*s
= bs
->opaque
;
2690 * D1. offs == start: start is in data
2691 * D2. offs > start: start is in a hole, next data at offs
2692 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
2693 * or start is beyond EOF
2694 * If the latter happens, the file has been truncated behind
2695 * our back since we opened it. All bets are off then.
2696 * Treating like a trailing hole is simplest.
2697 * D4. offs < 0, errno != ENXIO: we learned nothing
2699 offs
= lseek(s
->fd
, start
, SEEK_DATA
);
2701 return -errno
; /* D3 or D4 */
2705 /* This is not a valid return by lseek(). We are safe to just return
2706 * -EIO in this case, and we'll treat it like D4. */
2711 /* D2: in hole, next data at offs */
2717 /* D1: in data, end not yet known */
2721 * H1. offs == start: start is in a hole
2722 * If this happens here, a hole has been dug behind our back
2723 * since the previous lseek().
2724 * H2. offs > start: either start is in data, next hole at offs,
2725 * or start is in trailing hole, EOF at offs
2726 * Linux treats trailing holes like any other hole: offs ==
2727 * start. Solaris seeks to EOF instead: offs > start (blech).
2728 * If that happens here, a hole has been dug behind our back
2729 * since the previous lseek().
2730 * H3. offs < 0, errno = ENXIO: start is beyond EOF
2731 * If this happens, the file has been truncated behind our
2732 * back since we opened it. Treat it like a trailing hole.
2733 * H4. offs < 0, errno != ENXIO: we learned nothing
2734 * Pretend we know nothing at all, i.e. "forget" about D1.
2736 offs
= lseek(s
->fd
, start
, SEEK_HOLE
);
2738 return -errno
; /* D1 and (H3 or H4) */
2742 /* This is not a valid return by lseek(). We are safe to just return
2743 * -EIO in this case, and we'll treat it like H4. */
2749 * D1 and H2: either in data, next hole at offs, or it was in
2750 * data but is now in a trailing hole. In the latter case,
2751 * all bets are off. Treating it as if it there was data all
2752 * the way to EOF is safe, so simply do that.
2767 * Returns the allocation status of the specified offset.
2769 * The block layer guarantees 'offset' and 'bytes' are within bounds.
2771 * 'pnum' is set to the number of bytes (including and immediately following
2772 * the specified offset) that are known to be in the same
2773 * allocated/unallocated state.
2775 * 'bytes' is a soft cap for 'pnum'. If the information is free, 'pnum' may
2778 static int coroutine_fn
raw_co_block_status(BlockDriverState
*bs
,
2781 int64_t bytes
, int64_t *pnum
,
2783 BlockDriverState
**file
)
2785 off_t data
= 0, hole
= 0;
2788 assert(QEMU_IS_ALIGNED(offset
| bytes
, bs
->bl
.request_alignment
));
2799 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
2802 ret
= find_allocation(bs
, offset
, &data
, &hole
);
2803 if (ret
== -ENXIO
) {
2806 ret
= BDRV_BLOCK_ZERO
;
2807 } else if (ret
< 0) {
2808 /* No info available, so pretend there are no holes */
2810 ret
= BDRV_BLOCK_DATA
;
2811 } else if (data
== offset
) {
2812 /* On a data extent, compute bytes to the end of the extent,
2813 * possibly including a partial sector at EOF. */
2814 *pnum
= hole
- offset
;
2817 * We are not allowed to return partial sectors, though, so
2818 * round up if necessary.
2820 if (!QEMU_IS_ALIGNED(*pnum
, bs
->bl
.request_alignment
)) {
2821 int64_t file_length
= raw_co_getlength(bs
);
2822 if (file_length
> 0) {
2823 /* Ignore errors, this is just a safeguard */
2824 assert(hole
== file_length
);
2826 *pnum
= ROUND_UP(*pnum
, bs
->bl
.request_alignment
);
2829 ret
= BDRV_BLOCK_DATA
;
2831 /* On a hole, compute bytes to the beginning of the next extent. */
2832 assert(hole
== offset
);
2833 *pnum
= data
- offset
;
2834 ret
= BDRV_BLOCK_ZERO
;
2838 return ret
| BDRV_BLOCK_OFFSET_VALID
;
2841 #if defined(__linux__)
2842 /* Verify that the file is not in the page cache */
2843 static void coroutine_fn
check_cache_dropped(BlockDriverState
*bs
, Error
**errp
)
2845 const size_t window_size
= 128 * 1024 * 1024;
2846 BDRVRawState
*s
= bs
->opaque
;
2847 void *window
= NULL
;
2854 /* mincore(2) page status information requires 1 byte per page */
2855 page_size
= sysconf(_SC_PAGESIZE
);
2856 vec
= g_malloc(DIV_ROUND_UP(window_size
, page_size
));
2858 end
= raw_co_getlength(bs
);
2860 for (offset
= 0; offset
< end
; offset
+= window_size
) {
2867 /* Unmap previous window if size has changed */
2868 new_length
= MIN(end
- offset
, window_size
);
2869 if (new_length
!= length
) {
2870 munmap(window
, length
);
2875 new_window
= mmap(window
, new_length
, PROT_NONE
, MAP_PRIVATE
,
2877 if (new_window
== MAP_FAILED
) {
2878 error_setg_errno(errp
, errno
, "mmap failed");
2882 window
= new_window
;
2883 length
= new_length
;
2885 ret
= mincore(window
, length
, vec
);
2887 error_setg_errno(errp
, errno
, "mincore failed");
2891 vec_end
= DIV_ROUND_UP(length
, page_size
);
2892 for (i
= 0; i
< vec_end
; i
++) {
2898 error_setg(errp
, "page cache still in use!");
2904 munmap(window
, length
);
2909 #endif /* __linux__ */
2911 static void coroutine_fn GRAPH_RDLOCK
2912 raw_co_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
2914 BDRVRawState
*s
= bs
->opaque
;
2919 error_setg_errno(errp
, -ret
, "The file descriptor is not open");
2923 if (!s
->drop_cache
) {
2927 if (s
->open_flags
& O_DIRECT
) {
2928 return; /* No host kernel page cache */
2931 #if defined(__linux__)
2932 /* This sets the scene for the next syscall... */
2933 ret
= bdrv_co_flush(bs
);
2935 error_setg_errno(errp
, -ret
, "flush failed");
2939 /* Linux does not invalidate pages that are dirty, locked, or mmapped by a
2940 * process. These limitations are okay because we just fsynced the file,
2941 * we don't use mmap, and the file should not be in use by other processes.
2943 ret
= posix_fadvise(s
->fd
, 0, 0, POSIX_FADV_DONTNEED
);
2944 if (ret
!= 0) { /* the return value is a positive errno */
2945 error_setg_errno(errp
, ret
, "fadvise failed");
2949 if (s
->check_cache_dropped
) {
2950 check_cache_dropped(bs
, errp
);
2952 #else /* __linux__ */
2953 /* Do nothing. Live migration to a remote host with cache.direct=off is
2954 * unsupported on other host operating systems. Cache consistency issues
2955 * may occur but no error is reported here, partly because that's the
2956 * historical behavior and partly because it's hard to differentiate valid
2957 * configurations that should not cause errors.
2959 #endif /* !__linux__ */
2962 static void raw_account_discard(BDRVRawState
*s
, uint64_t nbytes
, int ret
)
2965 s
->stats
.discard_nb_failed
++;
2967 s
->stats
.discard_nb_ok
++;
2968 s
->stats
.discard_bytes_ok
+= nbytes
;
2972 static coroutine_fn
int
2973 raw_do_pdiscard(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2976 BDRVRawState
*s
= bs
->opaque
;
2977 RawPosixAIOData acb
;
2980 acb
= (RawPosixAIOData
) {
2982 .aio_fildes
= s
->fd
,
2983 .aio_type
= QEMU_AIO_DISCARD
,
2984 .aio_offset
= offset
,
2985 .aio_nbytes
= bytes
,
2989 acb
.aio_type
|= QEMU_AIO_BLKDEV
;
2992 ret
= raw_thread_pool_submit(handle_aiocb_discard
, &acb
);
2993 raw_account_discard(s
, bytes
, ret
);
2997 static coroutine_fn
int
2998 raw_co_pdiscard(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3000 return raw_do_pdiscard(bs
, offset
, bytes
, false);
3003 static int coroutine_fn
3004 raw_do_pwrite_zeroes(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
3005 BdrvRequestFlags flags
, bool blkdev
)
3007 BDRVRawState
*s
= bs
->opaque
;
3008 RawPosixAIOData acb
;
3009 ThreadPoolFunc
*handler
;
3011 #ifdef CONFIG_FALLOCATE
3012 if (offset
+ bytes
> bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3013 BdrvTrackedRequest
*req
;
3016 * This is a workaround for a bug in the Linux XFS driver,
3017 * where writes submitted through the AIO interface will be
3018 * discarded if they happen beyond a concurrently running
3019 * fallocate() that increases the file length (i.e., both the
3020 * write and the fallocate() happen beyond the EOF).
3022 * To work around it, we extend the tracked request for this
3023 * zero write until INT64_MAX (effectively infinity), and mark
3024 * it as serializing.
3026 * We have to enable this workaround for all filesystems and
3027 * AIO modes (not just XFS with aio=native), because for
3028 * remote filesystems we do not know the host configuration.
3031 req
= bdrv_co_get_self_request(bs
);
3033 assert(req
->type
== BDRV_TRACKED_WRITE
);
3034 assert(req
->offset
<= offset
);
3035 assert(req
->offset
+ req
->bytes
>= offset
+ bytes
);
3037 req
->bytes
= BDRV_MAX_LENGTH
- req
->offset
;
3039 bdrv_check_request(req
->offset
, req
->bytes
, &error_abort
);
3041 bdrv_make_request_serialising(req
, bs
->bl
.request_alignment
);
3045 acb
= (RawPosixAIOData
) {
3047 .aio_fildes
= s
->fd
,
3048 .aio_type
= QEMU_AIO_WRITE_ZEROES
,
3049 .aio_offset
= offset
,
3050 .aio_nbytes
= bytes
,
3054 acb
.aio_type
|= QEMU_AIO_BLKDEV
;
3056 if (flags
& BDRV_REQ_NO_FALLBACK
) {
3057 acb
.aio_type
|= QEMU_AIO_NO_FALLBACK
;
3060 if (flags
& BDRV_REQ_MAY_UNMAP
) {
3061 acb
.aio_type
|= QEMU_AIO_DISCARD
;
3062 handler
= handle_aiocb_write_zeroes_unmap
;
3064 handler
= handle_aiocb_write_zeroes
;
3067 return raw_thread_pool_submit(handler
, &acb
);
3070 static int coroutine_fn
raw_co_pwrite_zeroes(
3071 BlockDriverState
*bs
, int64_t offset
,
3072 int64_t bytes
, BdrvRequestFlags flags
)
3074 return raw_do_pwrite_zeroes(bs
, offset
, bytes
, flags
, false);
3077 static int coroutine_fn
3078 raw_co_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
3083 static ImageInfoSpecific
*raw_get_specific_info(BlockDriverState
*bs
,
3086 ImageInfoSpecificFile
*file_info
= g_new0(ImageInfoSpecificFile
, 1);
3087 ImageInfoSpecific
*spec_info
= g_new(ImageInfoSpecific
, 1);
3089 *spec_info
= (ImageInfoSpecific
){
3090 .type
= IMAGE_INFO_SPECIFIC_KIND_FILE
,
3091 .u
.file
.data
= file_info
,
3094 #ifdef FS_IOC_FSGETXATTR
3096 BDRVRawState
*s
= bs
->opaque
;
3097 struct fsxattr attr
;
3100 ret
= ioctl(s
->fd
, FS_IOC_FSGETXATTR
, &attr
);
3101 if (!ret
&& attr
.fsx_extsize
!= 0) {
3102 file_info
->has_extent_size_hint
= true;
3103 file_info
->extent_size_hint
= attr
.fsx_extsize
;
3111 static BlockStatsSpecificFile
get_blockstats_specific_file(BlockDriverState
*bs
)
3113 BDRVRawState
*s
= bs
->opaque
;
3114 return (BlockStatsSpecificFile
) {
3115 .discard_nb_ok
= s
->stats
.discard_nb_ok
,
3116 .discard_nb_failed
= s
->stats
.discard_nb_failed
,
3117 .discard_bytes_ok
= s
->stats
.discard_bytes_ok
,
3121 static BlockStatsSpecific
*raw_get_specific_stats(BlockDriverState
*bs
)
3123 BlockStatsSpecific
*stats
= g_new(BlockStatsSpecific
, 1);
3125 stats
->driver
= BLOCKDEV_DRIVER_FILE
;
3126 stats
->u
.file
= get_blockstats_specific_file(bs
);
3131 #if defined(HAVE_HOST_BLOCK_DEVICE)
3132 static BlockStatsSpecific
*hdev_get_specific_stats(BlockDriverState
*bs
)
3134 BlockStatsSpecific
*stats
= g_new(BlockStatsSpecific
, 1);
3136 stats
->driver
= BLOCKDEV_DRIVER_HOST_DEVICE
;
3137 stats
->u
.host_device
= get_blockstats_specific_file(bs
);
3141 #endif /* HAVE_HOST_BLOCK_DEVICE */
3143 static QemuOptsList raw_create_opts
= {
3144 .name
= "raw-create-opts",
3145 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
3148 .name
= BLOCK_OPT_SIZE
,
3149 .type
= QEMU_OPT_SIZE
,
3150 .help
= "Virtual disk size"
3153 .name
= BLOCK_OPT_NOCOW
,
3154 .type
= QEMU_OPT_BOOL
,
3155 .help
= "Turn off copy-on-write (valid only on btrfs)"
3158 .name
= BLOCK_OPT_PREALLOC
,
3159 .type
= QEMU_OPT_STRING
,
3160 .help
= "Preallocation mode (allowed values: off"
3161 #ifdef CONFIG_POSIX_FALLOCATE
3167 .name
= BLOCK_OPT_EXTENT_SIZE_HINT
,
3168 .type
= QEMU_OPT_SIZE
,
3169 .help
= "Extent size hint for the image file, 0 to disable"
3171 { /* end of list */ }
3175 static int raw_check_perm(BlockDriverState
*bs
, uint64_t perm
, uint64_t shared
,
3178 BDRVRawState
*s
= bs
->opaque
;
3179 int input_flags
= s
->reopen_state
? s
->reopen_state
->flags
: bs
->open_flags
;
3183 /* We may need a new fd if auto-read-only switches the mode */
3184 ret
= raw_reconfigure_getfd(bs
, input_flags
, &open_flags
, perm
,
3188 } else if (ret
!= s
->fd
) {
3189 Error
*local_err
= NULL
;
3192 * Fail already check_perm() if we can't get a working O_DIRECT
3193 * alignment with the new fd.
3195 raw_probe_alignment(bs
, ret
, &local_err
);
3197 error_propagate(errp
, local_err
);
3201 s
->perm_change_fd
= ret
;
3202 s
->perm_change_flags
= open_flags
;
3205 /* Prepare permissions on old fd to avoid conflicts between old and new,
3206 * but keep everything locked that new will need. */
3207 ret
= raw_handle_perm_lock(bs
, RAW_PL_PREPARE
, perm
, shared
, errp
);
3212 /* Copy locks to the new fd */
3213 if (s
->perm_change_fd
&& s
->use_lock
) {
3214 ret
= raw_apply_lock_bytes(NULL
, s
->perm_change_fd
, perm
, ~shared
,
3217 raw_handle_perm_lock(bs
, RAW_PL_ABORT
, 0, 0, NULL
);
3224 if (s
->perm_change_fd
) {
3225 qemu_close(s
->perm_change_fd
);
3227 s
->perm_change_fd
= 0;
3231 static void raw_set_perm(BlockDriverState
*bs
, uint64_t perm
, uint64_t shared
)
3233 BDRVRawState
*s
= bs
->opaque
;
3235 /* For reopen, we have already switched to the new fd (.bdrv_set_perm is
3236 * called after .bdrv_reopen_commit) */
3237 if (s
->perm_change_fd
&& s
->fd
!= s
->perm_change_fd
) {
3239 s
->fd
= s
->perm_change_fd
;
3240 s
->open_flags
= s
->perm_change_flags
;
3242 s
->perm_change_fd
= 0;
3244 raw_handle_perm_lock(bs
, RAW_PL_COMMIT
, perm
, shared
, NULL
);
3246 s
->shared_perm
= shared
;
3249 static void raw_abort_perm_update(BlockDriverState
*bs
)
3251 BDRVRawState
*s
= bs
->opaque
;
3253 /* For reopen, .bdrv_reopen_abort is called afterwards and will close
3254 * the file descriptor. */
3255 if (s
->perm_change_fd
) {
3256 qemu_close(s
->perm_change_fd
);
3258 s
->perm_change_fd
= 0;
3260 raw_handle_perm_lock(bs
, RAW_PL_ABORT
, 0, 0, NULL
);
3263 static int coroutine_fn GRAPH_RDLOCK
raw_co_copy_range_from(
3264 BlockDriverState
*bs
, BdrvChild
*src
, int64_t src_offset
,
3265 BdrvChild
*dst
, int64_t dst_offset
, int64_t bytes
,
3266 BdrvRequestFlags read_flags
, BdrvRequestFlags write_flags
)
3268 return bdrv_co_copy_range_to(src
, src_offset
, dst
, dst_offset
, bytes
,
3269 read_flags
, write_flags
);
3272 static int coroutine_fn GRAPH_RDLOCK
3273 raw_co_copy_range_to(BlockDriverState
*bs
,
3274 BdrvChild
*src
, int64_t src_offset
,
3275 BdrvChild
*dst
, int64_t dst_offset
,
3276 int64_t bytes
, BdrvRequestFlags read_flags
,
3277 BdrvRequestFlags write_flags
)
3279 RawPosixAIOData acb
;
3280 BDRVRawState
*s
= bs
->opaque
;
3281 BDRVRawState
*src_s
;
3283 assert(dst
->bs
== bs
);
3284 if (src
->bs
->drv
->bdrv_co_copy_range_to
!= raw_co_copy_range_to
) {
3288 src_s
= src
->bs
->opaque
;
3289 if (fd_open(src
->bs
) < 0 || fd_open(dst
->bs
) < 0) {
3293 acb
= (RawPosixAIOData
) {
3295 .aio_type
= QEMU_AIO_COPY_RANGE
,
3296 .aio_fildes
= src_s
->fd
,
3297 .aio_offset
= src_offset
,
3298 .aio_nbytes
= bytes
,
3301 .aio_offset2
= dst_offset
,
3305 return raw_thread_pool_submit(handle_aiocb_copy_range
, &acb
);
3308 BlockDriver bdrv_file
= {
3309 .format_name
= "file",
3310 .protocol_name
= "file",
3311 .instance_size
= sizeof(BDRVRawState
),
3312 .bdrv_needs_filename
= true,
3313 .bdrv_probe
= NULL
, /* no probe for protocols */
3314 .bdrv_parse_filename
= raw_parse_filename
,
3315 .bdrv_file_open
= raw_open
,
3316 .bdrv_reopen_prepare
= raw_reopen_prepare
,
3317 .bdrv_reopen_commit
= raw_reopen_commit
,
3318 .bdrv_reopen_abort
= raw_reopen_abort
,
3319 .bdrv_close
= raw_close
,
3320 .bdrv_co_create
= raw_co_create
,
3321 .bdrv_co_create_opts
= raw_co_create_opts
,
3322 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
3323 .bdrv_co_block_status
= raw_co_block_status
,
3324 .bdrv_co_invalidate_cache
= raw_co_invalidate_cache
,
3325 .bdrv_co_pwrite_zeroes
= raw_co_pwrite_zeroes
,
3326 .bdrv_co_delete_file
= raw_co_delete_file
,
3328 .bdrv_co_preadv
= raw_co_preadv
,
3329 .bdrv_co_pwritev
= raw_co_pwritev
,
3330 .bdrv_co_flush_to_disk
= raw_co_flush_to_disk
,
3331 .bdrv_co_pdiscard
= raw_co_pdiscard
,
3332 .bdrv_co_copy_range_from
= raw_co_copy_range_from
,
3333 .bdrv_co_copy_range_to
= raw_co_copy_range_to
,
3334 .bdrv_refresh_limits
= raw_refresh_limits
,
3335 .bdrv_co_io_plug
= raw_co_io_plug
,
3336 .bdrv_co_io_unplug
= raw_co_io_unplug
,
3337 .bdrv_attach_aio_context
= raw_aio_attach_aio_context
,
3339 .bdrv_co_truncate
= raw_co_truncate
,
3340 .bdrv_co_getlength
= raw_co_getlength
,
3341 .bdrv_co_get_info
= raw_co_get_info
,
3342 .bdrv_get_specific_info
= raw_get_specific_info
,
3343 .bdrv_co_get_allocated_file_size
= raw_co_get_allocated_file_size
,
3344 .bdrv_get_specific_stats
= raw_get_specific_stats
,
3345 .bdrv_check_perm
= raw_check_perm
,
3346 .bdrv_set_perm
= raw_set_perm
,
3347 .bdrv_abort_perm_update
= raw_abort_perm_update
,
3348 .create_opts
= &raw_create_opts
,
3349 .mutable_opts
= mutable_opts
,
3352 /***********************************************/
3355 #if defined(HAVE_HOST_BLOCK_DEVICE)
3357 #if defined(__APPLE__) && defined(__MACH__)
3358 static kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
3359 CFIndex maxPathSize
, int flags
);
3361 #if !defined(MAC_OS_VERSION_12_0) \
3362 || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_12_0)
3363 #define IOMainPort IOMasterPort
3366 static char *FindEjectableOpticalMedia(io_iterator_t
*mediaIterator
)
3368 kern_return_t kernResult
= KERN_FAILURE
;
3369 mach_port_t mainPort
;
3370 CFMutableDictionaryRef classesToMatch
;
3371 const char *matching_array
[] = {kIODVDMediaClass
, kIOCDMediaClass
};
3372 char *mediaType
= NULL
;
3374 kernResult
= IOMainPort(MACH_PORT_NULL
, &mainPort
);
3375 if ( KERN_SUCCESS
!= kernResult
) {
3376 printf("IOMainPort returned %d\n", kernResult
);
3380 for (index
= 0; index
< ARRAY_SIZE(matching_array
); index
++) {
3381 classesToMatch
= IOServiceMatching(matching_array
[index
]);
3382 if (classesToMatch
== NULL
) {
3383 error_report("IOServiceMatching returned NULL for %s",
3384 matching_array
[index
]);
3387 CFDictionarySetValue(classesToMatch
, CFSTR(kIOMediaEjectableKey
),
3389 kernResult
= IOServiceGetMatchingServices(mainPort
, classesToMatch
,
3391 if (kernResult
!= KERN_SUCCESS
) {
3392 error_report("Note: IOServiceGetMatchingServices returned %d",
3397 /* If a match was found, leave the loop */
3398 if (*mediaIterator
!= 0) {
3399 trace_file_FindEjectableOpticalMedia(matching_array
[index
]);
3400 mediaType
= g_strdup(matching_array
[index
]);
3407 kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
3408 CFIndex maxPathSize
, int flags
)
3410 io_object_t nextMedia
;
3411 kern_return_t kernResult
= KERN_FAILURE
;
3413 nextMedia
= IOIteratorNext( mediaIterator
);
3416 CFTypeRef bsdPathAsCFString
;
3417 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
3418 if ( bsdPathAsCFString
) {
3419 size_t devPathLength
;
3420 strcpy( bsdPath
, _PATH_DEV
);
3421 if (flags
& BDRV_O_NOCACHE
) {
3422 strcat(bsdPath
, "r");
3424 devPathLength
= strlen( bsdPath
);
3425 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
3426 kernResult
= KERN_SUCCESS
;
3428 CFRelease( bsdPathAsCFString
);
3430 IOObjectRelease( nextMedia
);
3436 /* Sets up a real cdrom for use in QEMU */
3437 static bool setup_cdrom(char *bsd_path
, Error
**errp
)
3439 int index
, num_of_test_partitions
= 2, fd
;
3440 char test_partition
[MAXPATHLEN
];
3441 bool partition_found
= false;
3443 /* look for a working partition */
3444 for (index
= 0; index
< num_of_test_partitions
; index
++) {
3445 snprintf(test_partition
, sizeof(test_partition
), "%ss%d", bsd_path
,
3447 fd
= qemu_open(test_partition
, O_RDONLY
| O_BINARY
| O_LARGEFILE
, NULL
);
3449 partition_found
= true;
3455 /* if a working partition on the device was not found */
3456 if (partition_found
== false) {
3457 error_setg(errp
, "Failed to find a working partition on disc");
3459 trace_file_setup_cdrom(test_partition
);
3460 pstrcpy(bsd_path
, MAXPATHLEN
, test_partition
);
3462 return partition_found
;
3465 /* Prints directions on mounting and unmounting a device */
3466 static void print_unmounting_directions(const char *file_name
)
3468 error_report("If device %s is mounted on the desktop, unmount"
3469 " it first before using it in QEMU", file_name
);
3470 error_report("Command to unmount device: diskutil unmountDisk %s",
3472 error_report("Command to mount device: diskutil mountDisk %s", file_name
);
3475 #endif /* defined(__APPLE__) && defined(__MACH__) */
3477 static int hdev_probe_device(const char *filename
)
3481 /* allow a dedicated CD-ROM driver to match with a higher priority */
3482 if (strstart(filename
, "/dev/cdrom", NULL
))
3485 if (stat(filename
, &st
) >= 0 &&
3486 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
3493 static void hdev_parse_filename(const char *filename
, QDict
*options
,
3496 bdrv_parse_filename_strip_prefix(filename
, "host_device:", options
);
3499 static bool hdev_is_sg(BlockDriverState
*bs
)
3502 #if defined(__linux__)
3504 BDRVRawState
*s
= bs
->opaque
;
3506 struct sg_scsi_id scsiid
;
3510 if (stat(bs
->filename
, &st
) < 0 || !S_ISCHR(st
.st_mode
)) {
3514 ret
= ioctl(s
->fd
, SG_GET_VERSION_NUM
, &sg_version
);
3519 ret
= ioctl(s
->fd
, SG_GET_SCSI_ID
, &scsiid
);
3521 trace_file_hdev_is_sg(scsiid
.scsi_type
, sg_version
);
3530 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
3533 BDRVRawState
*s
= bs
->opaque
;
3536 #if defined(__APPLE__) && defined(__MACH__)
3538 * Caution: while qdict_get_str() is fine, getting non-string types
3539 * would require more care. When @options come from -blockdev or
3540 * blockdev_add, its members are typed according to the QAPI
3541 * schema, but when they come from -drive, they're all QString.
3543 const char *filename
= qdict_get_str(options
, "filename");
3544 char bsd_path
[MAXPATHLEN
] = "";
3545 bool error_occurred
= false;
3547 /* If using a real cdrom */
3548 if (strcmp(filename
, "/dev/cdrom") == 0) {
3549 char *mediaType
= NULL
;
3550 kern_return_t ret_val
;
3551 io_iterator_t mediaIterator
= 0;
3553 mediaType
= FindEjectableOpticalMedia(&mediaIterator
);
3554 if (mediaType
== NULL
) {
3555 error_setg(errp
, "Please make sure your CD/DVD is in the optical"
3557 error_occurred
= true;
3558 goto hdev_open_Mac_error
;
3561 ret_val
= GetBSDPath(mediaIterator
, bsd_path
, sizeof(bsd_path
), flags
);
3562 if (ret_val
!= KERN_SUCCESS
) {
3563 error_setg(errp
, "Could not get BSD path for optical drive");
3564 error_occurred
= true;
3565 goto hdev_open_Mac_error
;
3568 /* If a real optical drive was not found */
3569 if (bsd_path
[0] == '\0') {
3570 error_setg(errp
, "Failed to obtain bsd path for optical drive");
3571 error_occurred
= true;
3572 goto hdev_open_Mac_error
;
3575 /* If using a cdrom disc and finding a partition on the disc failed */
3576 if (strncmp(mediaType
, kIOCDMediaClass
, 9) == 0 &&
3577 setup_cdrom(bsd_path
, errp
) == false) {
3578 print_unmounting_directions(bsd_path
);
3579 error_occurred
= true;
3580 goto hdev_open_Mac_error
;
3583 qdict_put_str(options
, "filename", bsd_path
);
3585 hdev_open_Mac_error
:
3587 if (mediaIterator
) {
3588 IOObjectRelease(mediaIterator
);
3590 if (error_occurred
) {
3594 #endif /* defined(__APPLE__) && defined(__MACH__) */
3596 s
->type
= FTYPE_FILE
;
3598 ret
= raw_open_common(bs
, options
, flags
, 0, true, errp
);
3600 #if defined(__APPLE__) && defined(__MACH__)
3602 filename
= bsd_path
;
3604 /* if a physical device experienced an error while being opened */
3605 if (strncmp(filename
, "/dev/", 5) == 0) {
3606 print_unmounting_directions(filename
);
3608 #endif /* defined(__APPLE__) && defined(__MACH__) */
3612 /* Since this does ioctl the device must be already opened */
3613 bs
->sg
= hdev_is_sg(bs
);
3618 #if defined(__linux__)
3619 static int coroutine_fn
3620 hdev_co_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
3622 BDRVRawState
*s
= bs
->opaque
;
3623 RawPosixAIOData acb
;
3631 if (req
== SG_IO
&& s
->pr_mgr
) {
3632 struct sg_io_hdr
*io_hdr
= buf
;
3633 if (io_hdr
->cmdp
[0] == PERSISTENT_RESERVE_OUT
||
3634 io_hdr
->cmdp
[0] == PERSISTENT_RESERVE_IN
) {
3635 return pr_manager_execute(s
->pr_mgr
, qemu_get_current_aio_context(),
3640 acb
= (RawPosixAIOData
) {
3642 .aio_type
= QEMU_AIO_IOCTL
,
3643 .aio_fildes
= s
->fd
,
3651 return raw_thread_pool_submit(handle_aiocb_ioctl
, &acb
);
3655 static coroutine_fn
int
3656 hdev_co_pdiscard(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3658 BDRVRawState
*s
= bs
->opaque
;
3663 raw_account_discard(s
, bytes
, ret
);
3666 return raw_do_pdiscard(bs
, offset
, bytes
, true);
3669 static coroutine_fn
int hdev_co_pwrite_zeroes(BlockDriverState
*bs
,
3670 int64_t offset
, int64_t bytes
, BdrvRequestFlags flags
)
3679 return raw_do_pwrite_zeroes(bs
, offset
, bytes
, flags
, true);
3682 static BlockDriver bdrv_host_device
= {
3683 .format_name
= "host_device",
3684 .protocol_name
= "host_device",
3685 .instance_size
= sizeof(BDRVRawState
),
3686 .bdrv_needs_filename
= true,
3687 .bdrv_probe_device
= hdev_probe_device
,
3688 .bdrv_parse_filename
= hdev_parse_filename
,
3689 .bdrv_file_open
= hdev_open
,
3690 .bdrv_close
= raw_close
,
3691 .bdrv_reopen_prepare
= raw_reopen_prepare
,
3692 .bdrv_reopen_commit
= raw_reopen_commit
,
3693 .bdrv_reopen_abort
= raw_reopen_abort
,
3694 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
3695 .create_opts
= &bdrv_create_opts_simple
,
3696 .mutable_opts
= mutable_opts
,
3697 .bdrv_co_invalidate_cache
= raw_co_invalidate_cache
,
3698 .bdrv_co_pwrite_zeroes
= hdev_co_pwrite_zeroes
,
3700 .bdrv_co_preadv
= raw_co_preadv
,
3701 .bdrv_co_pwritev
= raw_co_pwritev
,
3702 .bdrv_co_flush_to_disk
= raw_co_flush_to_disk
,
3703 .bdrv_co_pdiscard
= hdev_co_pdiscard
,
3704 .bdrv_co_copy_range_from
= raw_co_copy_range_from
,
3705 .bdrv_co_copy_range_to
= raw_co_copy_range_to
,
3706 .bdrv_refresh_limits
= raw_refresh_limits
,
3707 .bdrv_co_io_plug
= raw_co_io_plug
,
3708 .bdrv_co_io_unplug
= raw_co_io_unplug
,
3709 .bdrv_attach_aio_context
= raw_aio_attach_aio_context
,
3711 .bdrv_co_truncate
= raw_co_truncate
,
3712 .bdrv_co_getlength
= raw_co_getlength
,
3713 .bdrv_co_get_info
= raw_co_get_info
,
3714 .bdrv_get_specific_info
= raw_get_specific_info
,
3715 .bdrv_co_get_allocated_file_size
= raw_co_get_allocated_file_size
,
3716 .bdrv_get_specific_stats
= hdev_get_specific_stats
,
3717 .bdrv_check_perm
= raw_check_perm
,
3718 .bdrv_set_perm
= raw_set_perm
,
3719 .bdrv_abort_perm_update
= raw_abort_perm_update
,
3720 .bdrv_probe_blocksizes
= hdev_probe_blocksizes
,
3721 .bdrv_probe_geometry
= hdev_probe_geometry
,
3723 /* generic scsi device */
3725 .bdrv_co_ioctl
= hdev_co_ioctl
,
3729 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3730 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
3733 bdrv_parse_filename_strip_prefix(filename
, "host_cdrom:", options
);
3736 static void cdrom_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
3738 bs
->bl
.has_variable_length
= true;
3739 raw_refresh_limits(bs
, errp
);
3744 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
3747 BDRVRawState
*s
= bs
->opaque
;
3751 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
3752 return raw_open_common(bs
, options
, flags
, O_NONBLOCK
, true, errp
);
3755 static int cdrom_probe_device(const char *filename
)
3761 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
, NULL
);
3765 ret
= fstat(fd
, &st
);
3766 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
3770 /* Attempt to detect via a CDROM specific ioctl */
3771 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
3781 static bool coroutine_fn
cdrom_co_is_inserted(BlockDriverState
*bs
)
3783 BDRVRawState
*s
= bs
->opaque
;
3786 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
3787 return ret
== CDS_DISC_OK
;
3790 static void coroutine_fn
cdrom_co_eject(BlockDriverState
*bs
, bool eject_flag
)
3792 BDRVRawState
*s
= bs
->opaque
;
3795 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
3796 perror("CDROMEJECT");
3798 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
3799 perror("CDROMEJECT");
3803 static void coroutine_fn
cdrom_co_lock_medium(BlockDriverState
*bs
, bool locked
)
3805 BDRVRawState
*s
= bs
->opaque
;
3807 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
3809 * Note: an error can happen if the distribution automatically
3812 /* perror("CDROM_LOCKDOOR"); */
3816 static BlockDriver bdrv_host_cdrom
= {
3817 .format_name
= "host_cdrom",
3818 .protocol_name
= "host_cdrom",
3819 .instance_size
= sizeof(BDRVRawState
),
3820 .bdrv_needs_filename
= true,
3821 .bdrv_probe_device
= cdrom_probe_device
,
3822 .bdrv_parse_filename
= cdrom_parse_filename
,
3823 .bdrv_file_open
= cdrom_open
,
3824 .bdrv_close
= raw_close
,
3825 .bdrv_reopen_prepare
= raw_reopen_prepare
,
3826 .bdrv_reopen_commit
= raw_reopen_commit
,
3827 .bdrv_reopen_abort
= raw_reopen_abort
,
3828 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
3829 .create_opts
= &bdrv_create_opts_simple
,
3830 .mutable_opts
= mutable_opts
,
3831 .bdrv_co_invalidate_cache
= raw_co_invalidate_cache
,
3833 .bdrv_co_preadv
= raw_co_preadv
,
3834 .bdrv_co_pwritev
= raw_co_pwritev
,
3835 .bdrv_co_flush_to_disk
= raw_co_flush_to_disk
,
3836 .bdrv_refresh_limits
= cdrom_refresh_limits
,
3837 .bdrv_co_io_plug
= raw_co_io_plug
,
3838 .bdrv_co_io_unplug
= raw_co_io_unplug
,
3839 .bdrv_attach_aio_context
= raw_aio_attach_aio_context
,
3841 .bdrv_co_truncate
= raw_co_truncate
,
3842 .bdrv_co_getlength
= raw_co_getlength
,
3843 .bdrv_co_get_allocated_file_size
= raw_co_get_allocated_file_size
,
3845 /* removable device support */
3846 .bdrv_co_is_inserted
= cdrom_co_is_inserted
,
3847 .bdrv_co_eject
= cdrom_co_eject
,
3848 .bdrv_co_lock_medium
= cdrom_co_lock_medium
,
3850 /* generic scsi device */
3851 .bdrv_co_ioctl
= hdev_co_ioctl
,
3853 #endif /* __linux__ */
3855 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
3856 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
3859 BDRVRawState
*s
= bs
->opaque
;
3864 ret
= raw_open_common(bs
, options
, flags
, 0, true, errp
);
3869 /* make sure the door isn't locked at this time */
3870 ioctl(s
->fd
, CDIOCALLOW
);
3874 static int cdrom_probe_device(const char *filename
)
3876 if (strstart(filename
, "/dev/cd", NULL
) ||
3877 strstart(filename
, "/dev/acd", NULL
))
3882 static int cdrom_reopen(BlockDriverState
*bs
)
3884 BDRVRawState
*s
= bs
->opaque
;
3888 * Force reread of possibly changed/newly loaded disc,
3889 * FreeBSD seems to not notice sometimes...
3893 fd
= qemu_open(bs
->filename
, s
->open_flags
, NULL
);
3900 /* make sure the door isn't locked at this time */
3901 ioctl(s
->fd
, CDIOCALLOW
);
3905 static bool coroutine_fn
cdrom_co_is_inserted(BlockDriverState
*bs
)
3907 return raw_co_getlength(bs
) > 0;
3910 static void coroutine_fn
cdrom_co_eject(BlockDriverState
*bs
, bool eject_flag
)
3912 BDRVRawState
*s
= bs
->opaque
;
3917 (void) ioctl(s
->fd
, CDIOCALLOW
);
3920 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
3921 perror("CDIOCEJECT");
3923 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
3924 perror("CDIOCCLOSE");
3930 static void coroutine_fn
cdrom_co_lock_medium(BlockDriverState
*bs
, bool locked
)
3932 BDRVRawState
*s
= bs
->opaque
;
3936 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
3938 * Note: an error can happen if the distribution automatically
3941 /* perror("CDROM_LOCKDOOR"); */
3945 static BlockDriver bdrv_host_cdrom
= {
3946 .format_name
= "host_cdrom",
3947 .protocol_name
= "host_cdrom",
3948 .instance_size
= sizeof(BDRVRawState
),
3949 .bdrv_needs_filename
= true,
3950 .bdrv_probe_device
= cdrom_probe_device
,
3951 .bdrv_parse_filename
= cdrom_parse_filename
,
3952 .bdrv_file_open
= cdrom_open
,
3953 .bdrv_close
= raw_close
,
3954 .bdrv_reopen_prepare
= raw_reopen_prepare
,
3955 .bdrv_reopen_commit
= raw_reopen_commit
,
3956 .bdrv_reopen_abort
= raw_reopen_abort
,
3957 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
3958 .create_opts
= &bdrv_create_opts_simple
,
3959 .mutable_opts
= mutable_opts
,
3961 .bdrv_co_preadv
= raw_co_preadv
,
3962 .bdrv_co_pwritev
= raw_co_pwritev
,
3963 .bdrv_co_flush_to_disk
= raw_co_flush_to_disk
,
3964 .bdrv_refresh_limits
= cdrom_refresh_limits
,
3965 .bdrv_co_io_plug
= raw_co_io_plug
,
3966 .bdrv_co_io_unplug
= raw_co_io_unplug
,
3967 .bdrv_attach_aio_context
= raw_aio_attach_aio_context
,
3969 .bdrv_co_truncate
= raw_co_truncate
,
3970 .bdrv_co_getlength
= raw_co_getlength
,
3971 .bdrv_co_get_allocated_file_size
= raw_co_get_allocated_file_size
,
3973 /* removable device support */
3974 .bdrv_co_is_inserted
= cdrom_co_is_inserted
,
3975 .bdrv_co_eject
= cdrom_co_eject
,
3976 .bdrv_co_lock_medium
= cdrom_co_lock_medium
,
3978 #endif /* __FreeBSD__ */
3980 #endif /* HAVE_HOST_BLOCK_DEVICE */
3982 static void bdrv_file_init(void)
3985 * Register all the drivers. Note that order is important, the driver
3986 * registered last will get probed first.
3988 bdrv_register(&bdrv_file
);
3989 #if defined(HAVE_HOST_BLOCK_DEVICE)
3990 bdrv_register(&bdrv_host_device
);
3992 bdrv_register(&bdrv_host_cdrom
);
3994 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3995 bdrv_register(&bdrv_host_cdrom
);
3997 #endif /* HAVE_HOST_BLOCK_DEVICE */
4000 block_init(bdrv_file_init
);