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 #if defined(CONFIG_BLKZONED)
72 #include <linux/blkzoned.h>
74 #include <linux/cdrom.h>
77 #include <linux/hdreg.h>
78 #include <linux/magic.h>
84 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
87 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
88 #include <linux/falloc.h>
90 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
96 #include <sys/ioctl.h>
97 #include <sys/disklabel.h>
102 #include <sys/ioctl.h>
103 #include <sys/disklabel.h>
104 #include <sys/dkio.h>
105 #include <sys/disk.h>
109 #include <sys/ioctl.h>
110 #include <sys/diskslice.h>
113 /* OS X does not have O_DSYNC */
116 #define O_DSYNC O_SYNC
117 #elif defined(O_FSYNC)
118 #define O_DSYNC O_FSYNC
122 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
124 #define O_DIRECT O_DSYNC
130 #define MAX_BLOCKSIZE 4096
132 /* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
133 * leaving a few more bytes for its future use. */
134 #define RAW_LOCK_PERM_BASE 100
135 #define RAW_LOCK_SHARED_BASE 200
137 typedef struct BDRVRawState
{
144 /* The current permissions. */
146 uint64_t shared_perm
;
148 /* The perms bits whose corresponding bytes are already locked in
150 uint64_t locked_perm
;
151 uint64_t locked_shared_perm
;
153 uint64_t aio_max_batch
;
156 int perm_change_flags
;
157 BDRVReopenState
*reopen_state
;
160 bool has_write_zeroes
:1;
161 bool use_linux_aio
:1;
162 bool use_linux_io_uring
:1;
163 int64_t *offset
; /* offset of zone append operation */
164 int page_cache_inconsistent
; /* errno from fdatasync failure */
166 bool needs_alignment
;
167 bool force_alignment
;
169 bool check_cache_dropped
;
171 uint64_t discard_nb_ok
;
172 uint64_t discard_nb_failed
;
173 uint64_t discard_bytes_ok
;
179 typedef struct BDRVRawReopenState
{
182 bool check_cache_dropped
;
183 } BDRVRawReopenState
;
185 static int fd_open(BlockDriverState
*bs
)
187 BDRVRawState
*s
= bs
->opaque
;
189 /* this is just to ensure s->fd is sane (its called by io ops) */
196 static int64_t raw_getlength(BlockDriverState
*bs
);
198 typedef struct RawPosixAIOData
{
199 BlockDriverState
*bs
;
220 PreallocMode prealloc
;
224 unsigned int *nr_zones
;
225 BlockZoneDescriptor
*zones
;
233 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
234 static int cdrom_reopen(BlockDriverState
*bs
);
238 * Elide EAGAIN and EACCES details when failing to lock, as this
239 * indicates that the specified file region is already locked by
240 * another process, which is considered a common scenario.
242 #define raw_lock_error_setg_errno(errp, err, fmt, ...) \
244 if ((err) == EAGAIN || (err) == EACCES) { \
245 error_setg((errp), (fmt), ## __VA_ARGS__); \
247 error_setg_errno((errp), (err), (fmt), ## __VA_ARGS__); \
251 #if defined(__NetBSD__)
252 static int raw_normalize_devicepath(const char **filename
, Error
**errp
)
254 static char namebuf
[PATH_MAX
];
255 const char *dp
, *fname
;
259 dp
= strrchr(fname
, '/');
260 if (lstat(fname
, &sb
) < 0) {
261 error_setg_file_open(errp
, errno
, fname
);
265 if (!S_ISBLK(sb
.st_mode
)) {
270 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
272 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
273 (int)(dp
- fname
), fname
, dp
+ 1);
276 warn_report("%s is a block device, using %s", fname
, *filename
);
281 static int raw_normalize_devicepath(const char **filename
, Error
**errp
)
288 * Get logical block size via ioctl. On success store it in @sector_size_p.
290 static int probe_logical_blocksize(int fd
, unsigned int *sector_size_p
)
292 unsigned int sector_size
;
293 bool success
= false;
297 static const unsigned long ioctl_list
[] = {
301 #ifdef DKIOCGETBLOCKSIZE
304 #ifdef DIOCGSECTORSIZE
309 /* Try a few ioctls to get the right size */
310 for (i
= 0; i
< (int)ARRAY_SIZE(ioctl_list
); i
++) {
311 if (ioctl(fd
, ioctl_list
[i
], §or_size
) >= 0) {
312 *sector_size_p
= sector_size
;
317 return success
? 0 : -errno
;
321 * Get physical block size of @fd.
322 * On success, store it in @blk_size and return 0.
323 * On failure, return -errno.
325 static int probe_physical_blocksize(int fd
, unsigned int *blk_size
)
328 if (ioctl(fd
, BLKPBSZGET
, blk_size
) < 0) {
338 * Returns true if no alignment restrictions are necessary even for files
339 * opened with O_DIRECT.
341 * raw_probe_alignment() probes the required alignment and assume that 1 means
342 * the probing failed, so it falls back to a safe default of 4k. This can be
343 * avoided if we know that byte alignment is okay for the file.
345 static bool dio_byte_aligned(int fd
)
351 ret
= fstatfs(fd
, &buf
);
352 if (ret
== 0 && buf
.f_type
== NFS_SUPER_MAGIC
) {
359 static bool raw_needs_alignment(BlockDriverState
*bs
)
361 BDRVRawState
*s
= bs
->opaque
;
363 if ((bs
->open_flags
& BDRV_O_NOCACHE
) != 0 && !dio_byte_aligned(s
->fd
)) {
367 return s
->force_alignment
;
370 /* Check if read is allowed with given memory buffer and length.
372 * This function is used to check O_DIRECT memory buffer and request alignment.
374 static bool raw_is_io_aligned(int fd
, void *buf
, size_t len
)
376 ssize_t ret
= pread(fd
, buf
, len
, 0);
383 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
384 * other errors (e.g. real I/O error), which could happen on a failed
385 * drive, since we only care about probing alignment.
387 if (errno
!= EINVAL
) {
395 static void raw_probe_alignment(BlockDriverState
*bs
, int fd
, Error
**errp
)
397 BDRVRawState
*s
= bs
->opaque
;
399 size_t max_align
= MAX(MAX_BLOCKSIZE
, qemu_real_host_page_size());
400 size_t alignments
[] = {1, 512, 1024, 2048, 4096};
402 /* For SCSI generic devices the alignment is not really used.
403 With buffered I/O, we don't have any restrictions. */
404 if (bdrv_is_sg(bs
) || !s
->needs_alignment
) {
405 bs
->bl
.request_alignment
= 1;
410 bs
->bl
.request_alignment
= 0;
412 /* Let's try to use the logical blocksize for the alignment. */
413 if (probe_logical_blocksize(fd
, &bs
->bl
.request_alignment
) < 0) {
414 bs
->bl
.request_alignment
= 0;
419 * The XFS ioctl definitions are shipped in extra packages that might
420 * not always be available. Since we just need the XFS_IOC_DIOINFO ioctl
421 * here, we simply use our own definition instead:
428 if (ioctl(fd
, _IOR('X', 30, struct xfs_dioattr
), &da
) >= 0) {
429 bs
->bl
.request_alignment
= da
.d_miniosz
;
430 /* The kernel returns wrong information for d_mem */
431 /* s->buf_align = da.d_mem; */
436 * If we could not get the sizes so far, we can only guess them. First try
437 * to detect request alignment, since it is more likely to succeed. Then
438 * try to detect buf_align, which cannot be detected in some cases (e.g.
439 * Gluster). If buf_align cannot be detected, we fallback to the value of
443 if (!bs
->bl
.request_alignment
) {
446 buf
= qemu_memalign(max_align
, max_align
);
447 for (i
= 0; i
< ARRAY_SIZE(alignments
); i
++) {
448 align
= alignments
[i
];
449 if (raw_is_io_aligned(fd
, buf
, align
)) {
450 /* Fallback to safe value. */
451 bs
->bl
.request_alignment
= (align
!= 1) ? align
: max_align
;
461 buf
= qemu_memalign(max_align
, 2 * max_align
);
462 for (i
= 0; i
< ARRAY_SIZE(alignments
); i
++) {
463 align
= alignments
[i
];
464 if (raw_is_io_aligned(fd
, buf
+ align
, max_align
)) {
465 /* Fallback to request_alignment. */
466 s
->buf_align
= (align
!= 1) ? align
: bs
->bl
.request_alignment
;
473 if (!s
->buf_align
|| !bs
->bl
.request_alignment
) {
474 error_setg(errp
, "Could not find working O_DIRECT alignment");
475 error_append_hint(errp
, "Try cache.direct=off\n");
479 static int check_hdev_writable(int fd
)
481 #if defined(BLKROGET)
482 /* Linux block devices can be configured "read-only" using blockdev(8).
483 * This is independent of device node permissions and therefore open(2)
484 * with O_RDWR succeeds. Actual writes fail with EPERM.
486 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
487 * check for read-only block devices so that Linux block devices behave
493 if (fstat(fd
, &st
)) {
497 if (!S_ISBLK(st
.st_mode
)) {
501 if (ioctl(fd
, BLKROGET
, &readonly
) < 0) {
508 #endif /* defined(BLKROGET) */
512 static void raw_parse_flags(int bdrv_flags
, int *open_flags
, bool has_writers
)
514 bool read_write
= false;
515 assert(open_flags
!= NULL
);
517 *open_flags
|= O_BINARY
;
518 *open_flags
&= ~O_ACCMODE
;
520 if (bdrv_flags
& BDRV_O_AUTO_RDONLY
) {
521 read_write
= has_writers
;
522 } else if (bdrv_flags
& BDRV_O_RDWR
) {
527 *open_flags
|= O_RDWR
;
529 *open_flags
|= O_RDONLY
;
532 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
533 * and O_DIRECT for no caching. */
534 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
535 *open_flags
|= O_DIRECT
;
539 static void raw_parse_filename(const char *filename
, QDict
*options
,
542 bdrv_parse_filename_strip_prefix(filename
, "file:", options
);
545 static QemuOptsList raw_runtime_opts
= {
547 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
551 .type
= QEMU_OPT_STRING
,
552 .help
= "File name of the image",
556 .type
= QEMU_OPT_STRING
,
557 .help
= "host AIO implementation (threads, native, io_uring)",
560 .name
= "aio-max-batch",
561 .type
= QEMU_OPT_NUMBER
,
562 .help
= "AIO max batch size (0 = auto handled by AIO backend, default: 0)",
566 .type
= QEMU_OPT_STRING
,
567 .help
= "file locking mode (on/off/auto, default: auto)",
570 .name
= "pr-manager",
571 .type
= QEMU_OPT_STRING
,
572 .help
= "id of persistent reservation manager object (default: none)",
574 #if defined(__linux__)
576 .name
= "drop-cache",
577 .type
= QEMU_OPT_BOOL
,
578 .help
= "invalidate page cache during live migration (default: on)",
582 .name
= "x-check-cache-dropped",
583 .type
= QEMU_OPT_BOOL
,
584 .help
= "check that page cache was dropped on live migration (default: off)"
586 { /* end of list */ }
590 static const char *const mutable_opts
[] = { "x-check-cache-dropped", NULL
};
592 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
593 int bdrv_flags
, int open_flags
,
594 bool device
, Error
**errp
)
596 BDRVRawState
*s
= bs
->opaque
;
598 Error
*local_err
= NULL
;
599 const char *filename
= NULL
;
601 BlockdevAioOptions aio
, aio_default
;
606 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
607 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
612 filename
= qemu_opt_get(opts
, "filename");
614 ret
= raw_normalize_devicepath(&filename
, errp
);
619 if (bdrv_flags
& BDRV_O_NATIVE_AIO
) {
620 aio_default
= BLOCKDEV_AIO_OPTIONS_NATIVE
;
621 #ifdef CONFIG_LINUX_IO_URING
622 } else if (bdrv_flags
& BDRV_O_IO_URING
) {
623 aio_default
= BLOCKDEV_AIO_OPTIONS_IO_URING
;
626 aio_default
= BLOCKDEV_AIO_OPTIONS_THREADS
;
629 aio
= qapi_enum_parse(&BlockdevAioOptions_lookup
,
630 qemu_opt_get(opts
, "aio"),
631 aio_default
, &local_err
);
633 error_propagate(errp
, local_err
);
638 s
->use_linux_aio
= (aio
== BLOCKDEV_AIO_OPTIONS_NATIVE
);
639 #ifdef CONFIG_LINUX_IO_URING
640 s
->use_linux_io_uring
= (aio
== BLOCKDEV_AIO_OPTIONS_IO_URING
);
643 s
->aio_max_batch
= qemu_opt_get_number(opts
, "aio-max-batch", 0);
645 locking
= qapi_enum_parse(&OnOffAuto_lookup
,
646 qemu_opt_get(opts
, "locking"),
647 ON_OFF_AUTO_AUTO
, &local_err
);
649 error_propagate(errp
, local_err
);
656 if (!qemu_has_ofd_lock()) {
657 warn_report("File lock requested but OFD locking syscall is "
658 "unavailable, falling back to POSIX file locks");
659 error_printf("Due to the implementation, locks can be lost "
663 case ON_OFF_AUTO_OFF
:
666 case ON_OFF_AUTO_AUTO
:
667 s
->use_lock
= qemu_has_ofd_lock();
673 str
= qemu_opt_get(opts
, "pr-manager");
675 s
->pr_mgr
= pr_manager_lookup(str
, &local_err
);
677 error_propagate(errp
, local_err
);
683 s
->drop_cache
= qemu_opt_get_bool(opts
, "drop-cache", true);
684 s
->check_cache_dropped
= qemu_opt_get_bool(opts
, "x-check-cache-dropped",
687 s
->open_flags
= open_flags
;
688 raw_parse_flags(bdrv_flags
, &s
->open_flags
, false);
691 fd
= qemu_open(filename
, s
->open_flags
, errp
);
692 ret
= fd
< 0 ? -errno
: 0;
702 /* Check s->open_flags rather than bdrv_flags due to auto-read-only */
703 if (s
->open_flags
& O_RDWR
) {
704 ret
= check_hdev_writable(s
->fd
);
706 error_setg_errno(errp
, -ret
, "The device is not writable");
712 s
->shared_perm
= BLK_PERM_ALL
;
714 #ifdef CONFIG_LINUX_AIO
715 /* Currently Linux does AIO only for files opened with O_DIRECT */
716 if (s
->use_linux_aio
) {
717 if (!(s
->open_flags
& O_DIRECT
)) {
718 error_setg(errp
, "aio=native was specified, but it requires "
719 "cache.direct=on, which was not specified.");
723 if (!aio_setup_linux_aio(bdrv_get_aio_context(bs
), errp
)) {
724 error_prepend(errp
, "Unable to use native AIO: ");
729 if (s
->use_linux_aio
) {
730 error_setg(errp
, "aio=native was specified, but is not supported "
735 #endif /* !defined(CONFIG_LINUX_AIO) */
737 #ifdef CONFIG_LINUX_IO_URING
738 if (s
->use_linux_io_uring
) {
739 if (!aio_setup_linux_io_uring(bdrv_get_aio_context(bs
), errp
)) {
740 error_prepend(errp
, "Unable to use io_uring: ");
745 if (s
->use_linux_io_uring
) {
746 error_setg(errp
, "aio=io_uring was specified, but is not supported "
751 #endif /* !defined(CONFIG_LINUX_IO_URING) */
753 s
->has_discard
= true;
754 s
->has_write_zeroes
= true;
756 if (fstat(s
->fd
, &st
) < 0) {
758 error_setg_errno(errp
, errno
, "Could not stat file");
763 if (!S_ISREG(st
.st_mode
)) {
764 error_setg(errp
, "'%s' driver requires '%s' to be a regular file",
765 bs
->drv
->format_name
, bs
->filename
);
769 s
->has_fallocate
= true;
772 if (!(S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
773 error_setg(errp
, "'%s' driver requires '%s' to be either "
774 "a character or block device",
775 bs
->drv
->format_name
, bs
->filename
);
780 #ifdef CONFIG_BLKZONED
782 * The kernel page cache does not reliably work for writes to SWR zones
783 * of zoned block device because it can not guarantee the order of writes.
785 if ((bs
->bl
.zoned
!= BLK_Z_NONE
) &&
786 (!(s
->open_flags
& O_DIRECT
))) {
787 error_setg(errp
, "The driver supports zoned devices, and it requires "
788 "cache.direct=on, which was not specified.");
789 return -EINVAL
; /* No host kernel page cache */
793 if (S_ISBLK(st
.st_mode
)) {
795 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
796 * not rely on the contents of discarded blocks unless using O_DIRECT.
797 * Same for BLKZEROOUT.
799 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
800 s
->has_write_zeroes
= false;
805 if (S_ISCHR(st
.st_mode
)) {
807 * The file is a char device (disk), which on FreeBSD isn't behind
808 * a pager, so force all requests to be aligned. This is needed
809 * so QEMU makes sure all IO operations on the device are aligned
810 * to sector size, or else FreeBSD will reject them with EINVAL.
812 s
->force_alignment
= true;
815 s
->needs_alignment
= raw_needs_alignment(bs
);
817 bs
->supported_zero_flags
= BDRV_REQ_MAY_UNMAP
| BDRV_REQ_NO_FALLBACK
;
818 if (S_ISREG(st
.st_mode
)) {
819 /* When extending regular files, we get zeros from the OS */
820 bs
->supported_truncate_flags
= BDRV_REQ_ZERO_WRITE
;
824 if (ret
< 0 && s
->fd
!= -1) {
827 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
834 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
837 BDRVRawState
*s
= bs
->opaque
;
839 s
->type
= FTYPE_FILE
;
840 return raw_open_common(bs
, options
, flags
, 0, false, errp
);
849 #define PERM_FOREACH(i) \
850 for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
852 /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
853 * file; if @unlock == true, also unlock the unneeded bytes.
854 * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
856 static int raw_apply_lock_bytes(BDRVRawState
*s
, int fd
,
857 uint64_t perm_lock_bits
,
858 uint64_t shared_perm_lock_bits
,
859 bool unlock
, Error
**errp
)
863 uint64_t locked_perm
, locked_shared_perm
;
866 locked_perm
= s
->locked_perm
;
867 locked_shared_perm
= s
->locked_shared_perm
;
870 * We don't have the previous bits, just lock/unlock for each of the
874 locked_perm
= BLK_PERM_ALL
;
875 locked_shared_perm
= BLK_PERM_ALL
;
878 locked_shared_perm
= 0;
883 int off
= RAW_LOCK_PERM_BASE
+ i
;
884 uint64_t bit
= (1ULL << i
);
885 if ((perm_lock_bits
& bit
) && !(locked_perm
& bit
)) {
886 ret
= qemu_lock_fd(fd
, off
, 1, false);
888 raw_lock_error_setg_errno(errp
, -ret
, "Failed to lock byte %d",
892 s
->locked_perm
|= bit
;
894 } else if (unlock
&& (locked_perm
& bit
) && !(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_perm
&= ~bit
;
905 int off
= RAW_LOCK_SHARED_BASE
+ i
;
906 uint64_t bit
= (1ULL << i
);
907 if ((shared_perm_lock_bits
& bit
) && !(locked_shared_perm
& bit
)) {
908 ret
= qemu_lock_fd(fd
, off
, 1, false);
910 raw_lock_error_setg_errno(errp
, -ret
, "Failed to lock byte %d",
914 s
->locked_shared_perm
|= bit
;
916 } else if (unlock
&& (locked_shared_perm
& bit
) &&
917 !(shared_perm_lock_bits
& bit
)) {
918 ret
= qemu_unlock_fd(fd
, off
, 1);
920 error_setg_errno(errp
, -ret
, "Failed to unlock byte %d", off
);
923 s
->locked_shared_perm
&= ~bit
;
930 /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
931 static int raw_check_lock_bytes(int fd
, uint64_t perm
, uint64_t shared_perm
,
938 int off
= RAW_LOCK_SHARED_BASE
+ i
;
939 uint64_t p
= 1ULL << i
;
941 ret
= qemu_lock_fd_test(fd
, off
, 1, true);
943 char *perm_name
= bdrv_perm_names(p
);
945 raw_lock_error_setg_errno(errp
, -ret
,
946 "Failed to get \"%s\" lock",
954 int off
= RAW_LOCK_PERM_BASE
+ i
;
955 uint64_t p
= 1ULL << i
;
956 if (!(shared_perm
& p
)) {
957 ret
= qemu_lock_fd_test(fd
, off
, 1, true);
959 char *perm_name
= bdrv_perm_names(p
);
961 raw_lock_error_setg_errno(errp
, -ret
,
962 "Failed to get shared \"%s\" lock",
972 static int raw_handle_perm_lock(BlockDriverState
*bs
,
974 uint64_t new_perm
, uint64_t new_shared
,
977 BDRVRawState
*s
= bs
->opaque
;
979 Error
*local_err
= NULL
;
985 if (bdrv_get_flags(bs
) & BDRV_O_INACTIVE
) {
991 if ((s
->perm
| new_perm
) == s
->perm
&&
992 (s
->shared_perm
& new_shared
) == s
->shared_perm
)
995 * We are going to unlock bytes, it should not fail. If it fail due
996 * to some fs-dependent permission-unrelated reasons (which occurs
997 * sometimes on NFS and leads to abort in bdrv_replace_child) we
998 * can't prevent such errors by any check here. And we ignore them
999 * anyway in ABORT and COMMIT.
1003 ret
= raw_apply_lock_bytes(s
, s
->fd
, s
->perm
| new_perm
,
1004 ~s
->shared_perm
| ~new_shared
,
1007 ret
= raw_check_lock_bytes(s
->fd
, new_perm
, new_shared
, errp
);
1011 error_append_hint(errp
,
1012 "Is another process using the image [%s]?\n",
1015 /* fall through to unlock bytes. */
1017 raw_apply_lock_bytes(s
, s
->fd
, s
->perm
, ~s
->shared_perm
,
1020 /* Theoretically the above call only unlocks bytes and it cannot
1021 * fail. Something weird happened, report it.
1023 warn_report_err(local_err
);
1027 raw_apply_lock_bytes(s
, s
->fd
, new_perm
, ~new_shared
,
1030 /* Theoretically the above call only unlocks bytes and it cannot
1031 * fail. Something weird happened, report it.
1033 warn_report_err(local_err
);
1040 /* Sets a specific flag */
1041 static int fcntl_setfl(int fd
, int flag
)
1045 flags
= fcntl(fd
, F_GETFL
);
1049 if (fcntl(fd
, F_SETFL
, flags
| flag
) == -1) {
1055 static int raw_reconfigure_getfd(BlockDriverState
*bs
, int flags
,
1056 int *open_flags
, uint64_t perm
, bool force_dup
,
1059 BDRVRawState
*s
= bs
->opaque
;
1062 bool has_writers
= perm
&
1063 (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_RESIZE
);
1064 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
1066 fcntl_flags
|= O_NOATIME
;
1070 if (s
->type
== FTYPE_CD
) {
1071 *open_flags
|= O_NONBLOCK
;
1074 raw_parse_flags(flags
, open_flags
, has_writers
);
1077 /* Not all operating systems have O_ASYNC, and those that don't
1078 * will not let us track the state into rs->open_flags (typically
1079 * you achieve the same effect with an ioctl, for example I_SETSIG
1080 * on Solaris). But we do not use O_ASYNC, so that's fine.
1082 assert((s
->open_flags
& O_ASYNC
) == 0);
1085 if (!force_dup
&& *open_flags
== s
->open_flags
) {
1086 /* We're lucky, the existing fd is fine */
1090 if ((*open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
1091 /* dup the original fd */
1092 fd
= qemu_dup(s
->fd
);
1094 ret
= fcntl_setfl(fd
, *open_flags
);
1102 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
1104 const char *normalized_filename
= bs
->filename
;
1105 ret
= raw_normalize_devicepath(&normalized_filename
, errp
);
1107 fd
= qemu_open(normalized_filename
, *open_flags
, errp
);
1114 if (fd
!= -1 && (*open_flags
& O_RDWR
)) {
1115 ret
= check_hdev_writable(fd
);
1118 error_setg_errno(errp
, -ret
, "The device is not writable");
1126 static int raw_reopen_prepare(BDRVReopenState
*state
,
1127 BlockReopenQueue
*queue
, Error
**errp
)
1130 BDRVRawReopenState
*rs
;
1134 assert(state
!= NULL
);
1135 assert(state
->bs
!= NULL
);
1137 s
= state
->bs
->opaque
;
1139 state
->opaque
= g_new0(BDRVRawReopenState
, 1);
1142 /* Handle options changes */
1143 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
1144 if (!qemu_opts_absorb_qdict(opts
, state
->options
, errp
)) {
1149 rs
->drop_cache
= qemu_opt_get_bool_del(opts
, "drop-cache", true);
1150 rs
->check_cache_dropped
=
1151 qemu_opt_get_bool_del(opts
, "x-check-cache-dropped", false);
1153 /* This driver's reopen function doesn't currently allow changing
1154 * other options, so let's put them back in the original QDict and
1155 * bdrv_reopen_prepare() will detect changes and complain. */
1156 qemu_opts_to_qdict(opts
, state
->options
);
1159 * As part of reopen prepare we also want to create new fd by
1160 * raw_reconfigure_getfd(). But it wants updated "perm", when in
1161 * bdrv_reopen_multiple() .bdrv_reopen_prepare() callback called prior to
1162 * permission update. Happily, permission update is always a part (a seprate
1163 * stage) of bdrv_reopen_multiple() so we can rely on this fact and
1164 * reconfigure fd in raw_check_perm().
1167 s
->reopen_state
= state
;
1171 qemu_opts_del(opts
);
1175 static void raw_reopen_commit(BDRVReopenState
*state
)
1177 BDRVRawReopenState
*rs
= state
->opaque
;
1178 BDRVRawState
*s
= state
->bs
->opaque
;
1180 s
->drop_cache
= rs
->drop_cache
;
1181 s
->check_cache_dropped
= rs
->check_cache_dropped
;
1182 s
->open_flags
= rs
->open_flags
;
1183 g_free(state
->opaque
);
1184 state
->opaque
= NULL
;
1186 assert(s
->reopen_state
== state
);
1187 s
->reopen_state
= NULL
;
1191 static void raw_reopen_abort(BDRVReopenState
*state
)
1193 BDRVRawReopenState
*rs
= state
->opaque
;
1194 BDRVRawState
*s
= state
->bs
->opaque
;
1196 /* nothing to do if NULL, we didn't get far enough */
1201 g_free(state
->opaque
);
1202 state
->opaque
= NULL
;
1204 assert(s
->reopen_state
== state
);
1205 s
->reopen_state
= NULL
;
1208 static int hdev_get_max_hw_transfer(int fd
, struct stat
*st
)
1211 if (S_ISBLK(st
->st_mode
)) {
1212 unsigned short max_sectors
= 0;
1213 if (ioctl(fd
, BLKSECTGET
, &max_sectors
) == 0) {
1214 return max_sectors
* 512;
1218 if (ioctl(fd
, BLKSECTGET
, &max_bytes
) == 0) {
1229 * Get a sysfs attribute value as character string.
1232 static int get_sysfs_str_val(struct stat
*st
, const char *attribute
,
1234 g_autofree
char *sysfspath
= NULL
;
1237 if (!S_ISBLK(st
->st_mode
)) {
1241 sysfspath
= g_strdup_printf("/sys/dev/block/%u:%u/queue/%s",
1242 major(st
->st_rdev
), minor(st
->st_rdev
),
1244 if (!g_file_get_contents(sysfspath
, val
, &len
, NULL
)) {
1248 /* The file is ended with '\n' */
1251 if (*(p
+ len
- 1) == '\n') {
1252 *(p
+ len
- 1) = '\0';
1258 #if defined(CONFIG_BLKZONED)
1259 static int get_sysfs_zoned_model(struct stat
*st
, BlockZoneModel
*zoned
)
1261 g_autofree
char *val
= NULL
;
1264 ret
= get_sysfs_str_val(st
, "zoned", &val
);
1269 if (strcmp(val
, "host-managed") == 0) {
1271 } else if (strcmp(val
, "host-aware") == 0) {
1273 } else if (strcmp(val
, "none") == 0) {
1274 *zoned
= BLK_Z_NONE
;
1280 #endif /* defined(CONFIG_BLKZONED) */
1283 * Get a sysfs attribute value as a long integer.
1286 static long get_sysfs_long_val(struct stat
*st
, const char *attribute
)
1288 g_autofree
char *str
= NULL
;
1293 ret
= get_sysfs_str_val(st
, attribute
, &str
);
1298 /* The file is ended with '\n', pass 'end' to accept that. */
1299 ret
= qemu_strtol(str
, &end
, 10, &val
);
1300 if (ret
== 0 && end
&& *end
== '\0') {
1307 static int hdev_get_max_segments(int fd
, struct stat
*st
)
1312 if (S_ISCHR(st
->st_mode
)) {
1313 if (ioctl(fd
, SG_GET_SG_TABLESIZE
, &ret
) == 0) {
1318 return get_sysfs_long_val(st
, "max_segments");
1324 #if defined(CONFIG_BLKZONED)
1326 * If the reset_all flag is true, then the wps of zone whose state is
1327 * not readonly or offline should be all reset to the start sector.
1328 * Else, take the real wp of the device.
1330 static int get_zones_wp(BlockDriverState
*bs
, int fd
, int64_t offset
,
1331 unsigned int nrz
, bool reset_all
)
1333 struct blk_zone
*blkz
;
1335 uint64_t sector
= offset
>> BDRV_SECTOR_BITS
;
1336 BlockZoneWps
*wps
= bs
->wps
;
1337 unsigned int j
= offset
/ bs
->bl
.zone_size
;
1338 unsigned int n
= 0, i
= 0;
1340 rep_size
= sizeof(struct blk_zone_report
) + nrz
* sizeof(struct blk_zone
);
1341 g_autofree
struct blk_zone_report
*rep
= NULL
;
1343 rep
= g_malloc(rep_size
);
1344 blkz
= (struct blk_zone
*)(rep
+ 1);
1346 memset(rep
, 0, rep_size
);
1347 rep
->sector
= sector
;
1348 rep
->nr_zones
= nrz
- n
;
1351 ret
= ioctl(fd
, BLKREPORTZONE
, rep
);
1352 } while (ret
!= 0 && errno
== EINTR
);
1354 error_report("%d: ioctl BLKREPORTZONE at %" PRId64
" failed %d",
1359 if (!rep
->nr_zones
) {
1363 for (i
= 0; i
< rep
->nr_zones
; ++i
, ++n
, ++j
) {
1365 * The wp tracking cares only about sequential writes required and
1366 * sequential write preferred zones so that the wp can advance to
1367 * the right location.
1368 * Use the most significant bit of the wp location to indicate the
1369 * zone type: 0 for SWR/SWP zones and 1 for conventional zones.
1371 if (blkz
[i
].type
== BLK_ZONE_TYPE_CONVENTIONAL
) {
1372 wps
->wp
[j
] |= 1ULL << 63;
1374 switch(blkz
[i
].cond
) {
1375 case BLK_ZONE_COND_FULL
:
1376 case BLK_ZONE_COND_READONLY
:
1377 /* Zone not writable */
1378 wps
->wp
[j
] = (blkz
[i
].start
+ blkz
[i
].len
) << BDRV_SECTOR_BITS
;
1380 case BLK_ZONE_COND_OFFLINE
:
1381 /* Zone not writable nor readable */
1382 wps
->wp
[j
] = (blkz
[i
].start
) << BDRV_SECTOR_BITS
;
1386 wps
->wp
[j
] = blkz
[i
].start
<< BDRV_SECTOR_BITS
;
1388 wps
->wp
[j
] = blkz
[i
].wp
<< BDRV_SECTOR_BITS
;
1394 sector
= blkz
[i
- 1].start
+ blkz
[i
- 1].len
;
1400 static void update_zones_wp(BlockDriverState
*bs
, int fd
, int64_t offset
,
1403 if (get_zones_wp(bs
, fd
, offset
, nrz
, 0) < 0) {
1404 error_report("update zone wp failed");
1408 static void raw_refresh_zoned_limits(BlockDriverState
*bs
, struct stat
*st
,
1411 BDRVRawState
*s
= bs
->opaque
;
1412 BlockZoneModel zoned
;
1415 bs
->bl
.zoned
= BLK_Z_NONE
;
1417 ret
= get_sysfs_zoned_model(st
, &zoned
);
1418 if (ret
< 0 || zoned
== BLK_Z_NONE
) {
1421 bs
->bl
.zoned
= zoned
;
1423 ret
= get_sysfs_long_val(st
, "max_open_zones");
1425 bs
->bl
.max_open_zones
= ret
;
1428 ret
= get_sysfs_long_val(st
, "max_active_zones");
1430 bs
->bl
.max_active_zones
= ret
;
1434 * The zoned device must at least have zone size and nr_zones fields.
1436 ret
= get_sysfs_long_val(st
, "chunk_sectors");
1438 error_setg_errno(errp
, -ret
, "Unable to read chunk_sectors "
1442 error_setg(errp
, "Read 0 from chunk_sectors sysfs attribute");
1445 bs
->bl
.zone_size
= ret
<< BDRV_SECTOR_BITS
;
1447 ret
= get_sysfs_long_val(st
, "nr_zones");
1449 error_setg_errno(errp
, -ret
, "Unable to read nr_zones "
1453 error_setg(errp
, "Read 0 from nr_zones sysfs attribute");
1456 bs
->bl
.nr_zones
= ret
;
1458 ret
= get_sysfs_long_val(st
, "zone_append_max_bytes");
1460 bs
->bl
.max_append_sectors
= ret
>> BDRV_SECTOR_BITS
;
1463 ret
= get_sysfs_long_val(st
, "physical_block_size");
1465 bs
->bl
.write_granularity
= ret
;
1468 /* The refresh_limits() function can be called multiple times. */
1470 bs
->wps
= g_malloc(sizeof(BlockZoneWps
) +
1471 sizeof(int64_t) * bs
->bl
.nr_zones
);
1472 ret
= get_zones_wp(bs
, s
->fd
, 0, bs
->bl
.nr_zones
, 0);
1474 error_setg_errno(errp
, -ret
, "report wps failed");
1478 qemu_co_mutex_init(&bs
->wps
->colock
);
1480 #else /* !defined(CONFIG_BLKZONED) */
1481 static void raw_refresh_zoned_limits(BlockDriverState
*bs
, struct stat
*st
,
1484 bs
->bl
.zoned
= BLK_Z_NONE
;
1486 #endif /* !defined(CONFIG_BLKZONED) */
1488 static void raw_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1490 BDRVRawState
*s
= bs
->opaque
;
1493 s
->needs_alignment
= raw_needs_alignment(bs
);
1494 raw_probe_alignment(bs
, s
->fd
, errp
);
1496 bs
->bl
.min_mem_alignment
= s
->buf_align
;
1497 bs
->bl
.opt_mem_alignment
= MAX(s
->buf_align
, qemu_real_host_page_size());
1500 * Maximum transfers are best effort, so it is okay to ignore any
1501 * errors. That said, based on the man page errors in fstat would be
1502 * very much unexpected; the only possible case seems to be ENOMEM.
1504 if (fstat(s
->fd
, &st
)) {
1508 #if defined(__APPLE__) && (__MACH__)
1511 if (!fstatfs(s
->fd
, &buf
)) {
1512 bs
->bl
.opt_transfer
= buf
.f_iosize
;
1513 bs
->bl
.pdiscard_alignment
= buf
.f_bsize
;
1517 if (bdrv_is_sg(bs
) || S_ISBLK(st
.st_mode
)) {
1518 int ret
= hdev_get_max_hw_transfer(s
->fd
, &st
);
1520 if (ret
> 0 && ret
<= BDRV_REQUEST_MAX_BYTES
) {
1521 bs
->bl
.max_hw_transfer
= ret
;
1524 ret
= hdev_get_max_segments(s
->fd
, &st
);
1526 bs
->bl
.max_hw_iov
= ret
;
1530 raw_refresh_zoned_limits(bs
, &st
, errp
);
1533 static int check_for_dasd(int fd
)
1536 struct dasd_information2_t info
= {0};
1538 return ioctl(fd
, BIODASDINFO2
, &info
);
1545 * Try to get @bs's logical and physical block size.
1546 * On success, store them in @bsz and return zero.
1547 * On failure, return negative errno.
1549 static int hdev_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
1551 BDRVRawState
*s
= bs
->opaque
;
1554 /* If DASD or zoned devices, get blocksizes */
1555 if (check_for_dasd(s
->fd
) < 0) {
1556 /* zoned devices are not DASD */
1557 if (bs
->bl
.zoned
== BLK_Z_NONE
) {
1561 ret
= probe_logical_blocksize(s
->fd
, &bsz
->log
);
1565 return probe_physical_blocksize(s
->fd
, &bsz
->phys
);
1569 * Try to get @bs's geometry: cyls, heads, sectors.
1570 * On success, store them in @geo and return 0.
1571 * On failure return -errno.
1572 * (Allows block driver to assign default geometry values that guest sees)
1575 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
1577 BDRVRawState
*s
= bs
->opaque
;
1578 struct hd_geometry ioctl_geo
= {0};
1580 /* If DASD, get its geometry */
1581 if (check_for_dasd(s
->fd
) < 0) {
1584 if (ioctl(s
->fd
, HDIO_GETGEO
, &ioctl_geo
) < 0) {
1587 /* HDIO_GETGEO may return success even though geo contains zeros
1588 (e.g. certain multipath setups) */
1589 if (!ioctl_geo
.heads
|| !ioctl_geo
.sectors
|| !ioctl_geo
.cylinders
) {
1592 /* Do not return a geometry for partition */
1593 if (ioctl_geo
.start
!= 0) {
1596 geo
->heads
= ioctl_geo
.heads
;
1597 geo
->sectors
= ioctl_geo
.sectors
;
1598 geo
->cylinders
= ioctl_geo
.cylinders
;
1602 #else /* __linux__ */
1603 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
1609 #if defined(__linux__)
1610 static int handle_aiocb_ioctl(void *opaque
)
1612 RawPosixAIOData
*aiocb
= opaque
;
1615 ret
= RETRY_ON_EINTR(
1616 ioctl(aiocb
->aio_fildes
, aiocb
->ioctl
.cmd
, aiocb
->ioctl
.buf
)
1626 static int handle_aiocb_flush(void *opaque
)
1628 RawPosixAIOData
*aiocb
= opaque
;
1629 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1632 if (s
->page_cache_inconsistent
) {
1633 return -s
->page_cache_inconsistent
;
1636 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
1638 trace_file_flush_fdatasync_failed(errno
);
1640 /* There is no clear definition of the semantics of a failing fsync(),
1641 * so we may have to assume the worst. The sad truth is that this
1642 * assumption is correct for Linux. Some pages are now probably marked
1643 * clean in the page cache even though they are inconsistent with the
1644 * on-disk contents. The next fdatasync() call would succeed, but no
1645 * further writeback attempt will be made. We can't get back to a state
1646 * in which we know what is on disk (we would have to rewrite
1647 * everything that was touched since the last fdatasync() at least), so
1648 * make bdrv_flush() fail permanently. Given that the behaviour isn't
1649 * really defined, I have little hope that other OSes are doing better.
1651 * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1653 if ((s
->open_flags
& O_DIRECT
) == 0) {
1654 s
->page_cache_inconsistent
= errno
;
1661 #ifdef CONFIG_PREADV
1663 static bool preadv_present
= true;
1666 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1668 return preadv(fd
, iov
, nr_iov
, offset
);
1672 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1674 return pwritev(fd
, iov
, nr_iov
, offset
);
1679 static bool preadv_present
= false;
1682 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1688 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1695 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
1699 len
= RETRY_ON_EINTR(
1700 (aiocb
->aio_type
& (QEMU_AIO_WRITE
| QEMU_AIO_ZONE_APPEND
)) ?
1701 qemu_pwritev(aiocb
->aio_fildes
,
1704 aiocb
->aio_offset
) :
1705 qemu_preadv(aiocb
->aio_fildes
,
1718 * Read/writes the data to/from a given linear buffer.
1720 * Returns the number of bytes handles or -errno in case of an error. Short
1721 * reads are only returned if the end of the file is reached.
1723 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
1728 while (offset
< aiocb
->aio_nbytes
) {
1729 if (aiocb
->aio_type
& (QEMU_AIO_WRITE
| QEMU_AIO_ZONE_APPEND
)) {
1730 len
= pwrite(aiocb
->aio_fildes
,
1731 (const char *)buf
+ offset
,
1732 aiocb
->aio_nbytes
- offset
,
1733 aiocb
->aio_offset
+ offset
);
1735 len
= pread(aiocb
->aio_fildes
,
1737 aiocb
->aio_nbytes
- offset
,
1738 aiocb
->aio_offset
+ offset
);
1740 if (len
== -1 && errno
== EINTR
) {
1742 } else if (len
== -1 && errno
== EINVAL
&&
1743 (aiocb
->bs
->open_flags
& BDRV_O_NOCACHE
) &&
1744 !(aiocb
->aio_type
& QEMU_AIO_WRITE
) &&
1746 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1747 * after a short read. Assume that O_DIRECT short reads only occur
1748 * at EOF. Therefore this is a short read, not an I/O error.
1751 } else if (len
== -1) {
1754 } else if (len
== 0) {
1763 static int handle_aiocb_rw(void *opaque
)
1765 RawPosixAIOData
*aiocb
= opaque
;
1769 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
1771 * If there is just a single buffer, and it is properly aligned
1772 * we can just use plain pread/pwrite without any problems.
1774 if (aiocb
->io
.niov
== 1) {
1775 nbytes
= handle_aiocb_rw_linear(aiocb
, aiocb
->io
.iov
->iov_base
);
1779 * We have more than one iovec, and all are properly aligned.
1781 * Try preadv/pwritev first and fall back to linearizing the
1782 * buffer if it's not supported.
1784 if (preadv_present
) {
1785 nbytes
= handle_aiocb_rw_vector(aiocb
);
1786 if (nbytes
== aiocb
->aio_nbytes
||
1787 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
1790 preadv_present
= false;
1794 * XXX(hch): short read/write. no easy way to handle the reminder
1795 * using these interfaces. For now retry using plain
1801 * Ok, we have to do it the hard way, copy all segments into
1802 * a single aligned buffer.
1804 buf
= qemu_try_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
1810 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1814 for (i
= 0; i
< aiocb
->io
.niov
; ++i
) {
1815 memcpy(p
, aiocb
->io
.iov
[i
].iov_base
, aiocb
->io
.iov
[i
].iov_len
);
1816 p
+= aiocb
->io
.iov
[i
].iov_len
;
1818 assert(p
- buf
== aiocb
->aio_nbytes
);
1821 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
1822 if (!(aiocb
->aio_type
& (QEMU_AIO_WRITE
| QEMU_AIO_ZONE_APPEND
))) {
1824 size_t count
= aiocb
->aio_nbytes
, copy
;
1827 for (i
= 0; i
< aiocb
->io
.niov
&& count
; ++i
) {
1829 if (copy
> aiocb
->io
.iov
[i
].iov_len
) {
1830 copy
= aiocb
->io
.iov
[i
].iov_len
;
1832 memcpy(aiocb
->io
.iov
[i
].iov_base
, p
, copy
);
1833 assert(count
>= copy
);
1842 if (nbytes
== aiocb
->aio_nbytes
) {
1844 } else if (nbytes
>= 0 && nbytes
< aiocb
->aio_nbytes
) {
1845 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1848 iov_memset(aiocb
->io
.iov
, aiocb
->io
.niov
, nbytes
,
1849 0, aiocb
->aio_nbytes
- nbytes
);
1858 #if defined(CONFIG_FALLOCATE) || defined(BLKZEROOUT) || defined(BLKDISCARD)
1859 static int translate_err(int err
)
1861 if (err
== -ENODEV
|| err
== -ENOSYS
|| err
== -EOPNOTSUPP
||
1869 #ifdef CONFIG_FALLOCATE
1870 static int do_fallocate(int fd
, int mode
, off_t offset
, off_t len
)
1873 if (fallocate(fd
, mode
, offset
, len
) == 0) {
1876 } while (errno
== EINTR
);
1877 return translate_err(-errno
);
1881 static ssize_t
handle_aiocb_write_zeroes_block(RawPosixAIOData
*aiocb
)
1884 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1886 if (!s
->has_write_zeroes
) {
1891 /* The BLKZEROOUT implementation in the kernel doesn't set
1892 * BLKDEV_ZERO_NOFALLBACK, so we can't call this if we have to avoid slow
1894 if (!(aiocb
->aio_type
& QEMU_AIO_NO_FALLBACK
)) {
1896 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1897 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
1900 } while (errno
== EINTR
);
1902 ret
= translate_err(-errno
);
1903 if (ret
== -ENOTSUP
) {
1904 s
->has_write_zeroes
= false;
1912 static int handle_aiocb_write_zeroes(void *opaque
)
1914 RawPosixAIOData
*aiocb
= opaque
;
1915 #ifdef CONFIG_FALLOCATE
1916 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1920 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1921 return handle_aiocb_write_zeroes_block(aiocb
);
1924 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1925 if (s
->has_write_zeroes
) {
1926 int ret
= do_fallocate(s
->fd
, FALLOC_FL_ZERO_RANGE
,
1927 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1928 if (ret
== -ENOTSUP
) {
1929 s
->has_write_zeroes
= false;
1930 } else if (ret
== 0 || ret
!= -EINVAL
) {
1934 * Note: Some file systems do not like unaligned byte ranges, and
1935 * return EINVAL in such a case, though they should not do it according
1936 * to the man-page of fallocate(). Thus we simply ignore this return
1937 * value and try the other fallbacks instead.
1942 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1943 if (s
->has_discard
&& s
->has_fallocate
) {
1944 int ret
= do_fallocate(s
->fd
,
1945 FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1946 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1948 ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1949 if (ret
== 0 || ret
!= -ENOTSUP
) {
1952 s
->has_fallocate
= false;
1953 } else if (ret
== -EINVAL
) {
1955 * Some file systems like older versions of GPFS do not like un-
1956 * aligned byte ranges, and return EINVAL in such a case, though
1957 * they should not do it according to the man-page of fallocate().
1958 * Warn about the bad filesystem and try the final fallback instead.
1960 warn_report_once("Your file system is misbehaving: "
1961 "fallocate(FALLOC_FL_PUNCH_HOLE) returned EINVAL. "
1962 "Please report this bug to your file system "
1964 } else if (ret
!= -ENOTSUP
) {
1967 s
->has_discard
= false;
1972 #ifdef CONFIG_FALLOCATE
1973 /* Last resort: we are trying to extend the file with zeroed data. This
1974 * can be done via fallocate(fd, 0) */
1975 len
= raw_getlength(aiocb
->bs
);
1976 if (s
->has_fallocate
&& len
>= 0 && aiocb
->aio_offset
>= len
) {
1977 int ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1978 if (ret
== 0 || ret
!= -ENOTSUP
) {
1981 s
->has_fallocate
= false;
1988 static int handle_aiocb_write_zeroes_unmap(void *opaque
)
1990 RawPosixAIOData
*aiocb
= opaque
;
1991 BDRVRawState
*s G_GNUC_UNUSED
= aiocb
->bs
->opaque
;
1993 /* First try to write zeros and unmap at the same time */
1995 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1996 int ret
= do_fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1997 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
2008 /* If we couldn't manage to unmap while guaranteed that the area reads as
2009 * all-zero afterwards, just write zeroes without unmapping */
2010 return handle_aiocb_write_zeroes(aiocb
);
2013 #ifndef HAVE_COPY_FILE_RANGE
2014 static off_t
copy_file_range(int in_fd
, off_t
*in_off
, int out_fd
,
2015 off_t
*out_off
, size_t len
, unsigned int flags
)
2017 #ifdef __NR_copy_file_range
2018 return syscall(__NR_copy_file_range
, in_fd
, in_off
, out_fd
,
2019 out_off
, len
, flags
);
2028 * parse_zone - Fill a zone descriptor
2030 #if defined(CONFIG_BLKZONED)
2031 static inline int parse_zone(struct BlockZoneDescriptor
*zone
,
2032 const struct blk_zone
*blkz
) {
2033 zone
->start
= blkz
->start
<< BDRV_SECTOR_BITS
;
2034 zone
->length
= blkz
->len
<< BDRV_SECTOR_BITS
;
2035 zone
->wp
= blkz
->wp
<< BDRV_SECTOR_BITS
;
2037 #ifdef HAVE_BLK_ZONE_REP_CAPACITY
2038 zone
->cap
= blkz
->capacity
<< BDRV_SECTOR_BITS
;
2040 zone
->cap
= blkz
->len
<< BDRV_SECTOR_BITS
;
2043 switch (blkz
->type
) {
2044 case BLK_ZONE_TYPE_SEQWRITE_REQ
:
2045 zone
->type
= BLK_ZT_SWR
;
2047 case BLK_ZONE_TYPE_SEQWRITE_PREF
:
2048 zone
->type
= BLK_ZT_SWP
;
2050 case BLK_ZONE_TYPE_CONVENTIONAL
:
2051 zone
->type
= BLK_ZT_CONV
;
2054 error_report("Unsupported zone type: 0x%x", blkz
->type
);
2058 switch (blkz
->cond
) {
2059 case BLK_ZONE_COND_NOT_WP
:
2060 zone
->state
= BLK_ZS_NOT_WP
;
2062 case BLK_ZONE_COND_EMPTY
:
2063 zone
->state
= BLK_ZS_EMPTY
;
2065 case BLK_ZONE_COND_IMP_OPEN
:
2066 zone
->state
= BLK_ZS_IOPEN
;
2068 case BLK_ZONE_COND_EXP_OPEN
:
2069 zone
->state
= BLK_ZS_EOPEN
;
2071 case BLK_ZONE_COND_CLOSED
:
2072 zone
->state
= BLK_ZS_CLOSED
;
2074 case BLK_ZONE_COND_READONLY
:
2075 zone
->state
= BLK_ZS_RDONLY
;
2077 case BLK_ZONE_COND_FULL
:
2078 zone
->state
= BLK_ZS_FULL
;
2080 case BLK_ZONE_COND_OFFLINE
:
2081 zone
->state
= BLK_ZS_OFFLINE
;
2084 error_report("Unsupported zone state: 0x%x", blkz
->cond
);
2091 #if defined(CONFIG_BLKZONED)
2092 static int handle_aiocb_zone_report(void *opaque
)
2094 RawPosixAIOData
*aiocb
= opaque
;
2095 int fd
= aiocb
->aio_fildes
;
2096 unsigned int *nr_zones
= aiocb
->zone_report
.nr_zones
;
2097 BlockZoneDescriptor
*zones
= aiocb
->zone_report
.zones
;
2098 /* zoned block devices use 512-byte sectors */
2099 uint64_t sector
= aiocb
->aio_offset
/ 512;
2101 struct blk_zone
*blkz
;
2105 unsigned int n
= 0, i
= 0;
2108 rep_size
= sizeof(struct blk_zone_report
) + nrz
* sizeof(struct blk_zone
);
2109 g_autofree
struct blk_zone_report
*rep
= NULL
;
2110 rep
= g_malloc(rep_size
);
2112 blkz
= (struct blk_zone
*)(rep
+ 1);
2114 memset(rep
, 0, rep_size
);
2115 rep
->sector
= sector
;
2116 rep
->nr_zones
= nrz
- n
;
2119 ret
= ioctl(fd
, BLKREPORTZONE
, rep
);
2120 } while (ret
!= 0 && errno
== EINTR
);
2122 error_report("%d: ioctl BLKREPORTZONE at %" PRId64
" failed %d",
2127 if (!rep
->nr_zones
) {
2131 for (i
= 0; i
< rep
->nr_zones
; i
++, n
++) {
2132 ret
= parse_zone(&zones
[n
], &blkz
[i
]);
2137 /* The next report should start after the last zone reported */
2138 sector
= blkz
[i
].start
+ blkz
[i
].len
;
2147 #if defined(CONFIG_BLKZONED)
2148 static int handle_aiocb_zone_mgmt(void *opaque
)
2150 RawPosixAIOData
*aiocb
= opaque
;
2151 int fd
= aiocb
->aio_fildes
;
2152 uint64_t sector
= aiocb
->aio_offset
/ 512;
2153 int64_t nr_sectors
= aiocb
->aio_nbytes
/ 512;
2154 struct blk_zone_range range
;
2157 /* Execute the operation */
2158 range
.sector
= sector
;
2159 range
.nr_sectors
= nr_sectors
;
2161 ret
= ioctl(fd
, aiocb
->zone_mgmt
.op
, &range
);
2162 } while (ret
!= 0 && errno
== EINTR
);
2164 return ret
< 0 ? -errno
: ret
;
2168 static int handle_aiocb_copy_range(void *opaque
)
2170 RawPosixAIOData
*aiocb
= opaque
;
2171 uint64_t bytes
= aiocb
->aio_nbytes
;
2172 off_t in_off
= aiocb
->aio_offset
;
2173 off_t out_off
= aiocb
->copy_range
.aio_offset2
;
2176 ssize_t ret
= copy_file_range(aiocb
->aio_fildes
, &in_off
,
2177 aiocb
->copy_range
.aio_fd2
, &out_off
,
2179 trace_file_copy_file_range(aiocb
->bs
, aiocb
->aio_fildes
, in_off
,
2180 aiocb
->copy_range
.aio_fd2
, out_off
, bytes
,
2183 /* No progress (e.g. when beyond EOF), let the caller fall back to
2202 static int handle_aiocb_discard(void *opaque
)
2204 RawPosixAIOData
*aiocb
= opaque
;
2206 BDRVRawState
*s
= aiocb
->bs
->opaque
;
2208 if (!s
->has_discard
) {
2212 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
2215 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
2216 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
2219 } while (errno
== EINTR
);
2221 ret
= translate_err(-errno
);
2224 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
2225 ret
= do_fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
2226 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
2227 ret
= translate_err(ret
);
2228 #elif defined(__APPLE__) && (__MACH__)
2229 fpunchhole_t fpunchhole
;
2230 fpunchhole
.fp_flags
= 0;
2231 fpunchhole
.reserved
= 0;
2232 fpunchhole
.fp_offset
= aiocb
->aio_offset
;
2233 fpunchhole
.fp_length
= aiocb
->aio_nbytes
;
2234 if (fcntl(s
->fd
, F_PUNCHHOLE
, &fpunchhole
) == -1) {
2235 ret
= errno
== ENODEV
? -ENOTSUP
: -errno
;
2242 if (ret
== -ENOTSUP
) {
2243 s
->has_discard
= false;
2249 * Help alignment probing by allocating the first block.
2251 * When reading with direct I/O from unallocated area on Gluster backed by XFS,
2252 * reading succeeds regardless of request length. In this case we fallback to
2253 * safe alignment which is not optimal. Allocating the first block avoids this
2256 * fd may be opened with O_DIRECT, but we don't know the buffer alignment or
2257 * request alignment, so we use safe values.
2259 * Returns: 0 on success, -errno on failure. Since this is an optimization,
2260 * caller may ignore failures.
2262 static int allocate_first_block(int fd
, size_t max_size
)
2264 size_t write_size
= (max_size
< MAX_BLOCKSIZE
)
2267 size_t max_align
= MAX(MAX_BLOCKSIZE
, qemu_real_host_page_size());
2272 buf
= qemu_memalign(max_align
, write_size
);
2273 memset(buf
, 0, write_size
);
2275 n
= RETRY_ON_EINTR(pwrite(fd
, buf
, write_size
, 0));
2277 ret
= (n
== -1) ? -errno
: 0;
2283 static int handle_aiocb_truncate(void *opaque
)
2285 RawPosixAIOData
*aiocb
= opaque
;
2287 int64_t current_length
= 0;
2290 int fd
= aiocb
->aio_fildes
;
2291 int64_t offset
= aiocb
->aio_offset
;
2292 PreallocMode prealloc
= aiocb
->truncate
.prealloc
;
2293 Error
**errp
= aiocb
->truncate
.errp
;
2295 if (fstat(fd
, &st
) < 0) {
2297 error_setg_errno(errp
, -result
, "Could not stat file");
2301 current_length
= st
.st_size
;
2302 if (current_length
> offset
&& prealloc
!= PREALLOC_MODE_OFF
) {
2303 error_setg(errp
, "Cannot use preallocation for shrinking files");
2308 #ifdef CONFIG_POSIX_FALLOCATE
2309 case PREALLOC_MODE_FALLOC
:
2311 * Truncating before posix_fallocate() makes it about twice slower on
2312 * file systems that do not support fallocate(), trying to check if a
2313 * block is allocated before allocating it, so don't do that here.
2315 if (offset
!= current_length
) {
2316 result
= -posix_fallocate(fd
, current_length
,
2317 offset
- current_length
);
2319 /* posix_fallocate() doesn't set errno. */
2320 error_setg_errno(errp
, -result
,
2321 "Could not preallocate new data");
2322 } else if (current_length
== 0) {
2324 * posix_fallocate() uses fallocate() if the filesystem
2325 * supports it, or fallback to manually writing zeroes. If
2326 * fallocate() was used, unaligned reads from the fallocated
2327 * area in raw_probe_alignment() will succeed, hence we need to
2328 * allocate the first block.
2330 * Optimize future alignment probing; ignore failures.
2332 allocate_first_block(fd
, offset
);
2339 case PREALLOC_MODE_FULL
:
2341 int64_t num
= 0, left
= offset
- current_length
;
2345 * Knowing the final size from the beginning could allow the file
2346 * system driver to do less allocations and possibly avoid
2347 * fragmentation of the file.
2349 if (ftruncate(fd
, offset
) != 0) {
2351 error_setg_errno(errp
, -result
, "Could not resize file");
2355 buf
= g_malloc0(65536);
2357 seek_result
= lseek(fd
, current_length
, SEEK_SET
);
2358 if (seek_result
< 0) {
2360 error_setg_errno(errp
, -result
,
2361 "Failed to seek to the old end of file");
2366 num
= MIN(left
, 65536);
2367 result
= write(fd
, buf
, num
);
2369 if (errno
== EINTR
) {
2373 error_setg_errno(errp
, -result
,
2374 "Could not write zeros for preallocation");
2383 error_setg_errno(errp
, -result
,
2384 "Could not flush file to disk");
2390 case PREALLOC_MODE_OFF
:
2391 if (ftruncate(fd
, offset
) != 0) {
2393 error_setg_errno(errp
, -result
, "Could not resize file");
2394 } else if (current_length
== 0 && offset
> current_length
) {
2395 /* Optimize future alignment probing; ignore failures. */
2396 allocate_first_block(fd
, offset
);
2401 error_setg(errp
, "Unsupported preallocation mode: %s",
2402 PreallocMode_str(prealloc
));
2408 if (ftruncate(fd
, current_length
) < 0) {
2409 error_report("Failed to restore old file length: %s",
2418 static int coroutine_fn
raw_thread_pool_submit(ThreadPoolFunc func
, void *arg
)
2420 return thread_pool_submit_co(func
, arg
);
2424 * Check if all memory in this vector is sector aligned.
2426 static bool bdrv_qiov_is_aligned(BlockDriverState
*bs
, QEMUIOVector
*qiov
)
2429 size_t alignment
= bdrv_min_mem_align(bs
);
2430 size_t len
= bs
->bl
.request_alignment
;
2433 for (i
= 0; i
< qiov
->niov
; i
++) {
2434 if ((uintptr_t) qiov
->iov
[i
].iov_base
% alignment
) {
2437 if (qiov
->iov
[i
].iov_len
% len
) {
2445 static int coroutine_fn
raw_co_prw(BlockDriverState
*bs
, uint64_t offset
,
2446 uint64_t bytes
, QEMUIOVector
*qiov
, int type
)
2448 BDRVRawState
*s
= bs
->opaque
;
2449 RawPosixAIOData acb
;
2452 if (fd_open(bs
) < 0)
2454 #if defined(CONFIG_BLKZONED)
2455 if ((type
& (QEMU_AIO_WRITE
| QEMU_AIO_ZONE_APPEND
)) && bs
->wps
) {
2456 qemu_co_mutex_lock(&bs
->wps
->colock
);
2457 if (type
& QEMU_AIO_ZONE_APPEND
&& bs
->bl
.zone_size
) {
2458 int index
= offset
/ bs
->bl
.zone_size
;
2459 offset
= bs
->wps
->wp
[index
];
2465 * When using O_DIRECT, the request must be aligned to be able to use
2466 * either libaio or io_uring interface. If not fail back to regular thread
2467 * pool read/write code which emulates this for us if we
2468 * set QEMU_AIO_MISALIGNED.
2470 if (s
->needs_alignment
&& !bdrv_qiov_is_aligned(bs
, qiov
)) {
2471 type
|= QEMU_AIO_MISALIGNED
;
2472 #ifdef CONFIG_LINUX_IO_URING
2473 } else if (s
->use_linux_io_uring
) {
2474 assert(qiov
->size
== bytes
);
2475 ret
= luring_co_submit(bs
, s
->fd
, offset
, qiov
, type
);
2478 #ifdef CONFIG_LINUX_AIO
2479 } else if (s
->use_linux_aio
) {
2480 assert(qiov
->size
== bytes
);
2481 ret
= laio_co_submit(s
->fd
, offset
, qiov
, type
,
2487 acb
= (RawPosixAIOData
) {
2489 .aio_fildes
= s
->fd
,
2491 .aio_offset
= offset
,
2492 .aio_nbytes
= bytes
,
2499 assert(qiov
->size
== bytes
);
2500 ret
= raw_thread_pool_submit(handle_aiocb_rw
, &acb
);
2501 goto out
; /* Avoid the compiler err of unused label */
2504 #if defined(CONFIG_BLKZONED)
2506 BlockZoneWps
*wps
= bs
->wps
;
2508 if ((type
& (QEMU_AIO_WRITE
| QEMU_AIO_ZONE_APPEND
))
2509 && wps
&& bs
->bl
.zone_size
) {
2510 uint64_t *wp
= &wps
->wp
[offset
/ bs
->bl
.zone_size
];
2511 if (!BDRV_ZT_IS_CONV(*wp
)) {
2512 if (type
& QEMU_AIO_ZONE_APPEND
) {
2514 trace_zbd_zone_append_complete(bs
, *s
->offset
2515 >> BDRV_SECTOR_BITS
);
2517 /* Advance the wp if needed */
2518 if (offset
+ bytes
> *wp
) {
2519 *wp
= offset
+ bytes
;
2524 if (type
& (QEMU_AIO_WRITE
| QEMU_AIO_ZONE_APPEND
)) {
2525 update_zones_wp(bs
, s
->fd
, 0, 1);
2529 if ((type
& (QEMU_AIO_WRITE
| QEMU_AIO_ZONE_APPEND
)) && wps
) {
2530 qemu_co_mutex_unlock(&wps
->colock
);
2537 static int coroutine_fn
raw_co_preadv(BlockDriverState
*bs
, int64_t offset
,
2538 int64_t bytes
, QEMUIOVector
*qiov
,
2539 BdrvRequestFlags flags
)
2541 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_READ
);
2544 static int coroutine_fn
raw_co_pwritev(BlockDriverState
*bs
, int64_t offset
,
2545 int64_t bytes
, QEMUIOVector
*qiov
,
2546 BdrvRequestFlags flags
)
2548 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_WRITE
);
2551 static int coroutine_fn
raw_co_flush_to_disk(BlockDriverState
*bs
)
2553 BDRVRawState
*s
= bs
->opaque
;
2554 RawPosixAIOData acb
;
2562 acb
= (RawPosixAIOData
) {
2564 .aio_fildes
= s
->fd
,
2565 .aio_type
= QEMU_AIO_FLUSH
,
2568 #ifdef CONFIG_LINUX_IO_URING
2569 if (s
->use_linux_io_uring
) {
2570 return luring_co_submit(bs
, s
->fd
, 0, NULL
, QEMU_AIO_FLUSH
);
2573 return raw_thread_pool_submit(handle_aiocb_flush
, &acb
);
2576 static void raw_aio_attach_aio_context(BlockDriverState
*bs
,
2577 AioContext
*new_context
)
2579 BDRVRawState
__attribute__((unused
)) *s
= bs
->opaque
;
2580 #ifdef CONFIG_LINUX_AIO
2581 if (s
->use_linux_aio
) {
2582 Error
*local_err
= NULL
;
2583 if (!aio_setup_linux_aio(new_context
, &local_err
)) {
2584 error_reportf_err(local_err
, "Unable to use native AIO, "
2585 "falling back to thread pool: ");
2586 s
->use_linux_aio
= false;
2590 #ifdef CONFIG_LINUX_IO_URING
2591 if (s
->use_linux_io_uring
) {
2592 Error
*local_err
= NULL
;
2593 if (!aio_setup_linux_io_uring(new_context
, &local_err
)) {
2594 error_reportf_err(local_err
, "Unable to use linux io_uring, "
2595 "falling back to thread pool: ");
2596 s
->use_linux_io_uring
= false;
2602 static void raw_close(BlockDriverState
*bs
)
2604 BDRVRawState
*s
= bs
->opaque
;
2607 #if defined(CONFIG_BLKZONED)
2616 * Truncates the given regular file @fd to @offset and, when growing, fills the
2617 * new space according to @prealloc.
2619 * Returns: 0 on success, -errno on failure.
2621 static int coroutine_fn
2622 raw_regular_truncate(BlockDriverState
*bs
, int fd
, int64_t offset
,
2623 PreallocMode prealloc
, Error
**errp
)
2625 RawPosixAIOData acb
;
2627 acb
= (RawPosixAIOData
) {
2630 .aio_type
= QEMU_AIO_TRUNCATE
,
2631 .aio_offset
= offset
,
2633 .prealloc
= prealloc
,
2638 return raw_thread_pool_submit(handle_aiocb_truncate
, &acb
);
2641 static int coroutine_fn
raw_co_truncate(BlockDriverState
*bs
, int64_t offset
,
2642 bool exact
, PreallocMode prealloc
,
2643 BdrvRequestFlags flags
, Error
**errp
)
2645 BDRVRawState
*s
= bs
->opaque
;
2649 if (fstat(s
->fd
, &st
)) {
2651 error_setg_errno(errp
, -ret
, "Failed to fstat() the file");
2655 if (S_ISREG(st
.st_mode
)) {
2656 /* Always resizes to the exact @offset */
2657 return raw_regular_truncate(bs
, s
->fd
, offset
, prealloc
, errp
);
2660 if (prealloc
!= PREALLOC_MODE_OFF
) {
2661 error_setg(errp
, "Preallocation mode '%s' unsupported for this "
2662 "non-regular file", PreallocMode_str(prealloc
));
2666 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
2667 int64_t cur_length
= raw_getlength(bs
);
2669 if (offset
!= cur_length
&& exact
) {
2670 error_setg(errp
, "Cannot resize device files");
2672 } else if (offset
> cur_length
) {
2673 error_setg(errp
, "Cannot grow device files");
2677 error_setg(errp
, "Resizing this file is not supported");
2685 static int64_t raw_getlength(BlockDriverState
*bs
)
2687 BDRVRawState
*s
= bs
->opaque
;
2693 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
2694 struct disklabel dl
;
2696 if (ioctl(fd
, DIOCGDINFO
, &dl
))
2698 return (uint64_t)dl
.d_secsize
*
2699 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
2703 #elif defined(__NetBSD__)
2704 static int64_t raw_getlength(BlockDriverState
*bs
)
2706 BDRVRawState
*s
= bs
->opaque
;
2712 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
2713 struct dkwedge_info dkw
;
2715 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
2716 return dkw
.dkw_size
* 512;
2718 struct disklabel dl
;
2720 if (ioctl(fd
, DIOCGDINFO
, &dl
))
2722 return (uint64_t)dl
.d_secsize
*
2723 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
2728 #elif defined(__sun__)
2729 static int64_t raw_getlength(BlockDriverState
*bs
)
2731 BDRVRawState
*s
= bs
->opaque
;
2732 struct dk_minfo minfo
;
2742 * Use the DKIOCGMEDIAINFO ioctl to read the size.
2744 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
2746 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
2750 * There are reports that lseek on some devices fails, but
2751 * irc discussion said that contingency on contingency was overkill.
2753 size
= lseek(s
->fd
, 0, SEEK_END
);
2759 #elif defined(CONFIG_BSD)
2760 static int64_t raw_getlength(BlockDriverState
*bs
)
2762 BDRVRawState
*s
= bs
->opaque
;
2766 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2775 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2778 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
2780 #ifdef DIOCGMEDIASIZE
2781 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
)) {
2788 if (ioctl(fd
, DIOCGPART
, &pi
) == 0) {
2789 size
= pi
.media_size
;
2793 #if defined(DKIOCGETBLOCKCOUNT) && defined(DKIOCGETBLOCKSIZE)
2795 uint64_t sectors
= 0;
2796 uint32_t sector_size
= 0;
2798 if (ioctl(fd
, DKIOCGETBLOCKCOUNT
, §ors
) == 0
2799 && ioctl(fd
, DKIOCGETBLOCKSIZE
, §or_size
) == 0) {
2800 size
= sectors
* sector_size
;
2805 size
= lseek(fd
, 0LL, SEEK_END
);
2810 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2813 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
2814 if (size
== 2048LL * (unsigned)-1)
2816 /* XXX no disc? maybe we need to reopen... */
2817 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
2824 size
= lseek(fd
, 0, SEEK_END
);
2832 static int64_t raw_getlength(BlockDriverState
*bs
)
2834 BDRVRawState
*s
= bs
->opaque
;
2843 size
= lseek(s
->fd
, 0, SEEK_END
);
2851 static int64_t coroutine_fn
raw_co_getlength(BlockDriverState
*bs
)
2853 return raw_getlength(bs
);
2856 static int64_t coroutine_fn
raw_co_get_allocated_file_size(BlockDriverState
*bs
)
2859 BDRVRawState
*s
= bs
->opaque
;
2861 if (fstat(s
->fd
, &st
) < 0) {
2864 return (int64_t)st
.st_blocks
* 512;
2867 static int coroutine_fn
2868 raw_co_create(BlockdevCreateOptions
*options
, Error
**errp
)
2870 BlockdevCreateOptionsFile
*file_opts
;
2871 Error
*local_err
= NULL
;
2873 uint64_t perm
, shared
;
2876 /* Validate options and set default values */
2877 assert(options
->driver
== BLOCKDEV_DRIVER_FILE
);
2878 file_opts
= &options
->u
.file
;
2880 if (!file_opts
->has_nocow
) {
2881 file_opts
->nocow
= false;
2883 if (!file_opts
->has_preallocation
) {
2884 file_opts
->preallocation
= PREALLOC_MODE_OFF
;
2886 if (!file_opts
->has_extent_size_hint
) {
2887 file_opts
->extent_size_hint
= 1 * MiB
;
2889 if (file_opts
->extent_size_hint
> UINT32_MAX
) {
2891 error_setg(errp
, "Extent size hint is too large");
2896 fd
= qemu_create(file_opts
->filename
, O_RDWR
| O_BINARY
, 0644, errp
);
2902 /* Take permissions: We want to discard everything, so we need
2903 * BLK_PERM_WRITE; and truncation to the desired size requires
2905 * On the other hand, we cannot share the RESIZE permission
2906 * because we promise that after this function, the file has the
2907 * size given in the options. If someone else were to resize it
2908 * concurrently, we could not guarantee that.
2909 * Note that after this function, we can no longer guarantee that
2910 * the file is not touched by a third party, so it may be resized
2912 perm
= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2913 shared
= BLK_PERM_ALL
& ~BLK_PERM_RESIZE
;
2915 /* Step one: Take locks */
2916 result
= raw_apply_lock_bytes(NULL
, fd
, perm
, ~shared
, false, errp
);
2921 /* Step two: Check that nobody else has taken conflicting locks */
2922 result
= raw_check_lock_bytes(fd
, perm
, shared
, errp
);
2924 error_append_hint(errp
,
2925 "Is another process using the image [%s]?\n",
2926 file_opts
->filename
);
2930 /* Clear the file by truncating it to 0 */
2931 result
= raw_regular_truncate(NULL
, fd
, 0, PREALLOC_MODE_OFF
, errp
);
2936 if (file_opts
->nocow
) {
2938 /* Set NOCOW flag to solve performance issue on fs like btrfs.
2939 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2940 * will be ignored since any failure of this operation should not
2941 * block the left work.
2944 if (ioctl(fd
, FS_IOC_GETFLAGS
, &attr
) == 0) {
2945 attr
|= FS_NOCOW_FL
;
2946 ioctl(fd
, FS_IOC_SETFLAGS
, &attr
);
2950 #ifdef FS_IOC_FSSETXATTR
2952 * Try to set the extent size hint. Failure is not fatal, and a warning is
2953 * only printed if the option was explicitly specified.
2956 struct fsxattr attr
;
2957 result
= ioctl(fd
, FS_IOC_FSGETXATTR
, &attr
);
2959 attr
.fsx_xflags
|= FS_XFLAG_EXTSIZE
;
2960 attr
.fsx_extsize
= file_opts
->extent_size_hint
;
2961 result
= ioctl(fd
, FS_IOC_FSSETXATTR
, &attr
);
2963 if (result
< 0 && file_opts
->has_extent_size_hint
&&
2964 file_opts
->extent_size_hint
)
2966 warn_report("Failed to set extent size hint: %s",
2972 /* Resize and potentially preallocate the file to the desired
2974 result
= raw_regular_truncate(NULL
, fd
, file_opts
->size
,
2975 file_opts
->preallocation
, errp
);
2981 raw_apply_lock_bytes(NULL
, fd
, 0, 0, true, &local_err
);
2983 /* The above call should not fail, and if it does, that does
2984 * not mean the whole creation operation has failed. So
2985 * report it the user for their convenience, but do not report
2986 * it to the caller. */
2987 warn_report_err(local_err
);
2991 if (qemu_close(fd
) != 0 && result
== 0) {
2993 error_setg_errno(errp
, -result
, "Could not close the new file");
2999 static int coroutine_fn GRAPH_RDLOCK
3000 raw_co_create_opts(BlockDriver
*drv
, const char *filename
,
3001 QemuOpts
*opts
, Error
**errp
)
3003 BlockdevCreateOptions options
;
3004 int64_t total_size
= 0;
3005 int64_t extent_size_hint
= 0;
3006 bool has_extent_size_hint
= false;
3008 PreallocMode prealloc
;
3010 Error
*local_err
= NULL
;
3012 /* Skip file: protocol prefix */
3013 strstart(filename
, "file:", &filename
);
3015 /* Read out options */
3016 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
3018 if (qemu_opt_get(opts
, BLOCK_OPT_EXTENT_SIZE_HINT
)) {
3019 has_extent_size_hint
= true;
3021 qemu_opt_get_size_del(opts
, BLOCK_OPT_EXTENT_SIZE_HINT
, -1);
3023 nocow
= qemu_opt_get_bool(opts
, BLOCK_OPT_NOCOW
, false);
3024 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
3025 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
3026 PREALLOC_MODE_OFF
, &local_err
);
3029 error_propagate(errp
, local_err
);
3033 options
= (BlockdevCreateOptions
) {
3034 .driver
= BLOCKDEV_DRIVER_FILE
,
3036 .filename
= (char *) filename
,
3038 .has_preallocation
= true,
3039 .preallocation
= prealloc
,
3042 .has_extent_size_hint
= has_extent_size_hint
,
3043 .extent_size_hint
= extent_size_hint
,
3046 return raw_co_create(&options
, errp
);
3049 static int coroutine_fn
raw_co_delete_file(BlockDriverState
*bs
,
3055 if (!(stat(bs
->filename
, &st
) == 0) || !S_ISREG(st
.st_mode
)) {
3056 error_setg_errno(errp
, ENOENT
, "%s is not a regular file",
3061 ret
= unlink(bs
->filename
);
3064 error_setg_errno(errp
, -ret
, "Error when deleting file %s",
3072 * Find allocation range in @bs around offset @start.
3073 * May change underlying file descriptor's file offset.
3074 * If @start is not in a hole, store @start in @data, and the
3075 * beginning of the next hole in @hole, and return 0.
3076 * If @start is in a non-trailing hole, store @start in @hole and the
3077 * beginning of the next non-hole in @data, and return 0.
3078 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
3079 * If we can't find out, return a negative errno other than -ENXIO.
3081 static int find_allocation(BlockDriverState
*bs
, off_t start
,
3082 off_t
*data
, off_t
*hole
)
3084 #if defined SEEK_HOLE && defined SEEK_DATA
3085 BDRVRawState
*s
= bs
->opaque
;
3090 * D1. offs == start: start is in data
3091 * D2. offs > start: start is in a hole, next data at offs
3092 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
3093 * or start is beyond EOF
3094 * If the latter happens, the file has been truncated behind
3095 * our back since we opened it. All bets are off then.
3096 * Treating like a trailing hole is simplest.
3097 * D4. offs < 0, errno != ENXIO: we learned nothing
3099 offs
= lseek(s
->fd
, start
, SEEK_DATA
);
3101 return -errno
; /* D3 or D4 */
3105 /* This is not a valid return by lseek(). We are safe to just return
3106 * -EIO in this case, and we'll treat it like D4. */
3111 /* D2: in hole, next data at offs */
3117 /* D1: in data, end not yet known */
3121 * H1. offs == start: start is in a hole
3122 * If this happens here, a hole has been dug behind our back
3123 * since the previous lseek().
3124 * H2. offs > start: either start is in data, next hole at offs,
3125 * or start is in trailing hole, EOF at offs
3126 * Linux treats trailing holes like any other hole: offs ==
3127 * start. Solaris seeks to EOF instead: offs > start (blech).
3128 * If that happens here, a hole has been dug behind our back
3129 * since the previous lseek().
3130 * H3. offs < 0, errno = ENXIO: start is beyond EOF
3131 * If this happens, the file has been truncated behind our
3132 * back since we opened it. Treat it like a trailing hole.
3133 * H4. offs < 0, errno != ENXIO: we learned nothing
3134 * Pretend we know nothing at all, i.e. "forget" about D1.
3136 offs
= lseek(s
->fd
, start
, SEEK_HOLE
);
3138 return -errno
; /* D1 and (H3 or H4) */
3142 /* This is not a valid return by lseek(). We are safe to just return
3143 * -EIO in this case, and we'll treat it like H4. */
3149 * D1 and H2: either in data, next hole at offs, or it was in
3150 * data but is now in a trailing hole. In the latter case,
3151 * all bets are off. Treating it as if it there was data all
3152 * the way to EOF is safe, so simply do that.
3167 * Returns the allocation status of the specified offset.
3169 * The block layer guarantees 'offset' and 'bytes' are within bounds.
3171 * 'pnum' is set to the number of bytes (including and immediately following
3172 * the specified offset) that are known to be in the same
3173 * allocated/unallocated state.
3175 * 'bytes' is a soft cap for 'pnum'. If the information is free, 'pnum' may
3178 static int coroutine_fn
raw_co_block_status(BlockDriverState
*bs
,
3181 int64_t bytes
, int64_t *pnum
,
3183 BlockDriverState
**file
)
3185 off_t data
= 0, hole
= 0;
3188 assert(QEMU_IS_ALIGNED(offset
| bytes
, bs
->bl
.request_alignment
));
3199 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
3202 ret
= find_allocation(bs
, offset
, &data
, &hole
);
3203 if (ret
== -ENXIO
) {
3206 ret
= BDRV_BLOCK_ZERO
;
3207 } else if (ret
< 0) {
3208 /* No info available, so pretend there are no holes */
3210 ret
= BDRV_BLOCK_DATA
;
3211 } else if (data
== offset
) {
3212 /* On a data extent, compute bytes to the end of the extent,
3213 * possibly including a partial sector at EOF. */
3214 *pnum
= hole
- offset
;
3217 * We are not allowed to return partial sectors, though, so
3218 * round up if necessary.
3220 if (!QEMU_IS_ALIGNED(*pnum
, bs
->bl
.request_alignment
)) {
3221 int64_t file_length
= raw_getlength(bs
);
3222 if (file_length
> 0) {
3223 /* Ignore errors, this is just a safeguard */
3224 assert(hole
== file_length
);
3226 *pnum
= ROUND_UP(*pnum
, bs
->bl
.request_alignment
);
3229 ret
= BDRV_BLOCK_DATA
;
3231 /* On a hole, compute bytes to the beginning of the next extent. */
3232 assert(hole
== offset
);
3233 *pnum
= data
- offset
;
3234 ret
= BDRV_BLOCK_ZERO
;
3238 return ret
| BDRV_BLOCK_OFFSET_VALID
;
3241 #if defined(__linux__)
3242 /* Verify that the file is not in the page cache */
3243 static void check_cache_dropped(BlockDriverState
*bs
, Error
**errp
)
3245 const size_t window_size
= 128 * 1024 * 1024;
3246 BDRVRawState
*s
= bs
->opaque
;
3247 void *window
= NULL
;
3254 /* mincore(2) page status information requires 1 byte per page */
3255 page_size
= sysconf(_SC_PAGESIZE
);
3256 vec
= g_malloc(DIV_ROUND_UP(window_size
, page_size
));
3258 end
= raw_getlength(bs
);
3260 for (offset
= 0; offset
< end
; offset
+= window_size
) {
3267 /* Unmap previous window if size has changed */
3268 new_length
= MIN(end
- offset
, window_size
);
3269 if (new_length
!= length
) {
3270 munmap(window
, length
);
3275 new_window
= mmap(window
, new_length
, PROT_NONE
, MAP_PRIVATE
,
3277 if (new_window
== MAP_FAILED
) {
3278 error_setg_errno(errp
, errno
, "mmap failed");
3282 window
= new_window
;
3283 length
= new_length
;
3285 ret
= mincore(window
, length
, vec
);
3287 error_setg_errno(errp
, errno
, "mincore failed");
3291 vec_end
= DIV_ROUND_UP(length
, page_size
);
3292 for (i
= 0; i
< vec_end
; i
++) {
3298 error_setg(errp
, "page cache still in use!");
3304 munmap(window
, length
);
3309 #endif /* __linux__ */
3311 static void coroutine_fn GRAPH_RDLOCK
3312 raw_co_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
3314 BDRVRawState
*s
= bs
->opaque
;
3319 error_setg_errno(errp
, -ret
, "The file descriptor is not open");
3323 if (!s
->drop_cache
) {
3327 if (s
->open_flags
& O_DIRECT
) {
3328 return; /* No host kernel page cache */
3331 #if defined(__linux__)
3332 /* This sets the scene for the next syscall... */
3333 ret
= bdrv_co_flush(bs
);
3335 error_setg_errno(errp
, -ret
, "flush failed");
3339 /* Linux does not invalidate pages that are dirty, locked, or mmapped by a
3340 * process. These limitations are okay because we just fsynced the file,
3341 * we don't use mmap, and the file should not be in use by other processes.
3343 ret
= posix_fadvise(s
->fd
, 0, 0, POSIX_FADV_DONTNEED
);
3344 if (ret
!= 0) { /* the return value is a positive errno */
3345 error_setg_errno(errp
, ret
, "fadvise failed");
3349 if (s
->check_cache_dropped
) {
3350 check_cache_dropped(bs
, errp
);
3352 #else /* __linux__ */
3353 /* Do nothing. Live migration to a remote host with cache.direct=off is
3354 * unsupported on other host operating systems. Cache consistency issues
3355 * may occur but no error is reported here, partly because that's the
3356 * historical behavior and partly because it's hard to differentiate valid
3357 * configurations that should not cause errors.
3359 #endif /* !__linux__ */
3362 static void raw_account_discard(BDRVRawState
*s
, uint64_t nbytes
, int ret
)
3365 s
->stats
.discard_nb_failed
++;
3367 s
->stats
.discard_nb_ok
++;
3368 s
->stats
.discard_bytes_ok
+= nbytes
;
3373 * zone report - Get a zone block device's information in the form
3374 * of an array of zone descriptors.
3375 * zones is an array of zone descriptors to hold zone information on reply;
3376 * offset can be any byte within the entire size of the device;
3377 * nr_zones is the maxium number of sectors the command should operate on.
3379 #if defined(CONFIG_BLKZONED)
3380 static int coroutine_fn
raw_co_zone_report(BlockDriverState
*bs
, int64_t offset
,
3381 unsigned int *nr_zones
,
3382 BlockZoneDescriptor
*zones
) {
3383 BDRVRawState
*s
= bs
->opaque
;
3384 RawPosixAIOData acb
= (RawPosixAIOData
) {
3386 .aio_fildes
= s
->fd
,
3387 .aio_type
= QEMU_AIO_ZONE_REPORT
,
3388 .aio_offset
= offset
,
3390 .nr_zones
= nr_zones
,
3395 trace_zbd_zone_report(bs
, *nr_zones
, offset
>> BDRV_SECTOR_BITS
);
3396 return raw_thread_pool_submit(handle_aiocb_zone_report
, &acb
);
3401 * zone management operations - Execute an operation on a zone
3403 #if defined(CONFIG_BLKZONED)
3404 static int coroutine_fn
raw_co_zone_mgmt(BlockDriverState
*bs
, BlockZoneOp op
,
3405 int64_t offset
, int64_t len
) {
3406 BDRVRawState
*s
= bs
->opaque
;
3407 RawPosixAIOData acb
;
3408 int64_t zone_size
, zone_size_mask
;
3409 const char *op_name
;
3412 BlockZoneWps
*wps
= bs
->wps
;
3413 int64_t capacity
= bs
->total_sectors
<< BDRV_SECTOR_BITS
;
3415 zone_size
= bs
->bl
.zone_size
;
3416 zone_size_mask
= zone_size
- 1;
3417 if (offset
& zone_size_mask
) {
3418 error_report("sector offset %" PRId64
" is not aligned to zone size "
3419 "%" PRId64
"", offset
/ 512, zone_size
/ 512);
3423 if (((offset
+ len
) < capacity
&& len
& zone_size_mask
) ||
3424 offset
+ len
> capacity
) {
3425 error_report("number of sectors %" PRId64
" is not aligned to zone size"
3426 " %" PRId64
"", len
/ 512, zone_size
/ 512);
3430 uint32_t i
= offset
/ bs
->bl
.zone_size
;
3431 uint32_t nrz
= len
/ bs
->bl
.zone_size
;
3432 uint64_t *wp
= &wps
->wp
[i
];
3433 if (BDRV_ZT_IS_CONV(*wp
) && len
!= capacity
) {
3434 error_report("zone mgmt operations are not allowed for conventional zones");
3440 op_name
= "BLKOPENZONE";
3444 op_name
= "BLKCLOSEZONE";
3448 op_name
= "BLKFINISHZONE";
3452 op_name
= "BLKRESETZONE";
3456 error_report("Unsupported zone op: 0x%x", op
);
3460 acb
= (RawPosixAIOData
) {
3462 .aio_fildes
= s
->fd
,
3463 .aio_type
= QEMU_AIO_ZONE_MGMT
,
3464 .aio_offset
= offset
,
3471 trace_zbd_zone_mgmt(bs
, op_name
, offset
>> BDRV_SECTOR_BITS
,
3472 len
>> BDRV_SECTOR_BITS
);
3473 ret
= raw_thread_pool_submit(handle_aiocb_zone_mgmt
, &acb
);
3475 update_zones_wp(bs
, s
->fd
, offset
, i
);
3476 error_report("ioctl %s failed %d", op_name
, ret
);
3480 if (zo
== BLKRESETZONE
&& len
== capacity
) {
3481 ret
= get_zones_wp(bs
, s
->fd
, 0, bs
->bl
.nr_zones
, 1);
3483 error_report("reporting single wp failed");
3486 } else if (zo
== BLKRESETZONE
) {
3487 for (unsigned int j
= 0; j
< nrz
; ++j
) {
3488 wp
[j
] = offset
+ j
* zone_size
;
3490 } else if (zo
== BLKFINISHZONE
) {
3491 for (unsigned int j
= 0; j
< nrz
; ++j
) {
3492 /* The zoned device allows the last zone smaller that the
3494 wp
[j
] = MIN(offset
+ (j
+ 1) * zone_size
, offset
+ len
);
3502 #if defined(CONFIG_BLKZONED)
3503 static int coroutine_fn
raw_co_zone_append(BlockDriverState
*bs
,
3506 BdrvRequestFlags flags
) {
3508 int64_t zone_size_mask
= bs
->bl
.zone_size
- 1;
3509 int64_t iov_len
= 0;
3511 BDRVRawState
*s
= bs
->opaque
;
3514 if (*offset
& zone_size_mask
) {
3515 error_report("sector offset %" PRId64
" is not aligned to zone size "
3516 "%" PRId32
"", *offset
/ 512, bs
->bl
.zone_size
/ 512);
3520 int64_t wg
= bs
->bl
.write_granularity
;
3521 int64_t wg_mask
= wg
- 1;
3522 for (int i
= 0; i
< qiov
->niov
; i
++) {
3523 iov_len
= qiov
->iov
[i
].iov_len
;
3524 if (iov_len
& wg_mask
) {
3525 error_report("len of IOVector[%d] %" PRId64
" is not aligned to "
3526 "block size %" PRId64
"", i
, iov_len
, wg
);
3532 trace_zbd_zone_append(bs
, *offset
>> BDRV_SECTOR_BITS
);
3533 return raw_co_prw(bs
, *offset
, len
, qiov
, QEMU_AIO_ZONE_APPEND
);
3537 static coroutine_fn
int
3538 raw_do_pdiscard(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
3541 BDRVRawState
*s
= bs
->opaque
;
3542 RawPosixAIOData acb
;
3545 acb
= (RawPosixAIOData
) {
3547 .aio_fildes
= s
->fd
,
3548 .aio_type
= QEMU_AIO_DISCARD
,
3549 .aio_offset
= offset
,
3550 .aio_nbytes
= bytes
,
3554 acb
.aio_type
|= QEMU_AIO_BLKDEV
;
3557 ret
= raw_thread_pool_submit(handle_aiocb_discard
, &acb
);
3558 raw_account_discard(s
, bytes
, ret
);
3562 static coroutine_fn
int
3563 raw_co_pdiscard(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3565 return raw_do_pdiscard(bs
, offset
, bytes
, false);
3568 static int coroutine_fn
3569 raw_do_pwrite_zeroes(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
3570 BdrvRequestFlags flags
, bool blkdev
)
3572 BDRVRawState
*s
= bs
->opaque
;
3573 RawPosixAIOData acb
;
3574 ThreadPoolFunc
*handler
;
3576 #ifdef CONFIG_FALLOCATE
3577 if (offset
+ bytes
> bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3578 BdrvTrackedRequest
*req
;
3581 * This is a workaround for a bug in the Linux XFS driver,
3582 * where writes submitted through the AIO interface will be
3583 * discarded if they happen beyond a concurrently running
3584 * fallocate() that increases the file length (i.e., both the
3585 * write and the fallocate() happen beyond the EOF).
3587 * To work around it, we extend the tracked request for this
3588 * zero write until INT64_MAX (effectively infinity), and mark
3589 * it as serializing.
3591 * We have to enable this workaround for all filesystems and
3592 * AIO modes (not just XFS with aio=native), because for
3593 * remote filesystems we do not know the host configuration.
3596 req
= bdrv_co_get_self_request(bs
);
3598 assert(req
->type
== BDRV_TRACKED_WRITE
);
3599 assert(req
->offset
<= offset
);
3600 assert(req
->offset
+ req
->bytes
>= offset
+ bytes
);
3602 req
->bytes
= BDRV_MAX_LENGTH
- req
->offset
;
3604 bdrv_check_request(req
->offset
, req
->bytes
, &error_abort
);
3606 bdrv_make_request_serialising(req
, bs
->bl
.request_alignment
);
3610 acb
= (RawPosixAIOData
) {
3612 .aio_fildes
= s
->fd
,
3613 .aio_type
= QEMU_AIO_WRITE_ZEROES
,
3614 .aio_offset
= offset
,
3615 .aio_nbytes
= bytes
,
3619 acb
.aio_type
|= QEMU_AIO_BLKDEV
;
3621 if (flags
& BDRV_REQ_NO_FALLBACK
) {
3622 acb
.aio_type
|= QEMU_AIO_NO_FALLBACK
;
3625 if (flags
& BDRV_REQ_MAY_UNMAP
) {
3626 acb
.aio_type
|= QEMU_AIO_DISCARD
;
3627 handler
= handle_aiocb_write_zeroes_unmap
;
3629 handler
= handle_aiocb_write_zeroes
;
3632 return raw_thread_pool_submit(handler
, &acb
);
3635 static int coroutine_fn
raw_co_pwrite_zeroes(
3636 BlockDriverState
*bs
, int64_t offset
,
3637 int64_t bytes
, BdrvRequestFlags flags
)
3639 return raw_do_pwrite_zeroes(bs
, offset
, bytes
, flags
, false);
3642 static int coroutine_fn
3643 raw_co_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
3648 static ImageInfoSpecific
*raw_get_specific_info(BlockDriverState
*bs
,
3651 ImageInfoSpecificFile
*file_info
= g_new0(ImageInfoSpecificFile
, 1);
3652 ImageInfoSpecific
*spec_info
= g_new(ImageInfoSpecific
, 1);
3654 *spec_info
= (ImageInfoSpecific
){
3655 .type
= IMAGE_INFO_SPECIFIC_KIND_FILE
,
3656 .u
.file
.data
= file_info
,
3659 #ifdef FS_IOC_FSGETXATTR
3661 BDRVRawState
*s
= bs
->opaque
;
3662 struct fsxattr attr
;
3665 ret
= ioctl(s
->fd
, FS_IOC_FSGETXATTR
, &attr
);
3666 if (!ret
&& attr
.fsx_extsize
!= 0) {
3667 file_info
->has_extent_size_hint
= true;
3668 file_info
->extent_size_hint
= attr
.fsx_extsize
;
3676 static BlockStatsSpecificFile
get_blockstats_specific_file(BlockDriverState
*bs
)
3678 BDRVRawState
*s
= bs
->opaque
;
3679 return (BlockStatsSpecificFile
) {
3680 .discard_nb_ok
= s
->stats
.discard_nb_ok
,
3681 .discard_nb_failed
= s
->stats
.discard_nb_failed
,
3682 .discard_bytes_ok
= s
->stats
.discard_bytes_ok
,
3686 static BlockStatsSpecific
*raw_get_specific_stats(BlockDriverState
*bs
)
3688 BlockStatsSpecific
*stats
= g_new(BlockStatsSpecific
, 1);
3690 stats
->driver
= BLOCKDEV_DRIVER_FILE
;
3691 stats
->u
.file
= get_blockstats_specific_file(bs
);
3696 #if defined(HAVE_HOST_BLOCK_DEVICE)
3697 static BlockStatsSpecific
*hdev_get_specific_stats(BlockDriverState
*bs
)
3699 BlockStatsSpecific
*stats
= g_new(BlockStatsSpecific
, 1);
3701 stats
->driver
= BLOCKDEV_DRIVER_HOST_DEVICE
;
3702 stats
->u
.host_device
= get_blockstats_specific_file(bs
);
3706 #endif /* HAVE_HOST_BLOCK_DEVICE */
3708 static QemuOptsList raw_create_opts
= {
3709 .name
= "raw-create-opts",
3710 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
3713 .name
= BLOCK_OPT_SIZE
,
3714 .type
= QEMU_OPT_SIZE
,
3715 .help
= "Virtual disk size"
3718 .name
= BLOCK_OPT_NOCOW
,
3719 .type
= QEMU_OPT_BOOL
,
3720 .help
= "Turn off copy-on-write (valid only on btrfs)"
3723 .name
= BLOCK_OPT_PREALLOC
,
3724 .type
= QEMU_OPT_STRING
,
3725 .help
= "Preallocation mode (allowed values: off"
3726 #ifdef CONFIG_POSIX_FALLOCATE
3732 .name
= BLOCK_OPT_EXTENT_SIZE_HINT
,
3733 .type
= QEMU_OPT_SIZE
,
3734 .help
= "Extent size hint for the image file, 0 to disable"
3736 { /* end of list */ }
3740 static int raw_check_perm(BlockDriverState
*bs
, uint64_t perm
, uint64_t shared
,
3743 BDRVRawState
*s
= bs
->opaque
;
3744 int input_flags
= s
->reopen_state
? s
->reopen_state
->flags
: bs
->open_flags
;
3748 /* We may need a new fd if auto-read-only switches the mode */
3749 ret
= raw_reconfigure_getfd(bs
, input_flags
, &open_flags
, perm
,
3753 } else if (ret
!= s
->fd
) {
3754 Error
*local_err
= NULL
;
3757 * Fail already check_perm() if we can't get a working O_DIRECT
3758 * alignment with the new fd.
3760 raw_probe_alignment(bs
, ret
, &local_err
);
3762 error_propagate(errp
, local_err
);
3766 s
->perm_change_fd
= ret
;
3767 s
->perm_change_flags
= open_flags
;
3770 /* Prepare permissions on old fd to avoid conflicts between old and new,
3771 * but keep everything locked that new will need. */
3772 ret
= raw_handle_perm_lock(bs
, RAW_PL_PREPARE
, perm
, shared
, errp
);
3777 /* Copy locks to the new fd */
3778 if (s
->perm_change_fd
&& s
->use_lock
) {
3779 ret
= raw_apply_lock_bytes(NULL
, s
->perm_change_fd
, perm
, ~shared
,
3782 raw_handle_perm_lock(bs
, RAW_PL_ABORT
, 0, 0, NULL
);
3789 if (s
->perm_change_fd
) {
3790 qemu_close(s
->perm_change_fd
);
3792 s
->perm_change_fd
= 0;
3796 static void raw_set_perm(BlockDriverState
*bs
, uint64_t perm
, uint64_t shared
)
3798 BDRVRawState
*s
= bs
->opaque
;
3800 /* For reopen, we have already switched to the new fd (.bdrv_set_perm is
3801 * called after .bdrv_reopen_commit) */
3802 if (s
->perm_change_fd
&& s
->fd
!= s
->perm_change_fd
) {
3804 s
->fd
= s
->perm_change_fd
;
3805 s
->open_flags
= s
->perm_change_flags
;
3807 s
->perm_change_fd
= 0;
3809 raw_handle_perm_lock(bs
, RAW_PL_COMMIT
, perm
, shared
, NULL
);
3811 s
->shared_perm
= shared
;
3814 static void raw_abort_perm_update(BlockDriverState
*bs
)
3816 BDRVRawState
*s
= bs
->opaque
;
3818 /* For reopen, .bdrv_reopen_abort is called afterwards and will close
3819 * the file descriptor. */
3820 if (s
->perm_change_fd
) {
3821 qemu_close(s
->perm_change_fd
);
3823 s
->perm_change_fd
= 0;
3825 raw_handle_perm_lock(bs
, RAW_PL_ABORT
, 0, 0, NULL
);
3828 static int coroutine_fn GRAPH_RDLOCK
raw_co_copy_range_from(
3829 BlockDriverState
*bs
, BdrvChild
*src
, int64_t src_offset
,
3830 BdrvChild
*dst
, int64_t dst_offset
, int64_t bytes
,
3831 BdrvRequestFlags read_flags
, BdrvRequestFlags write_flags
)
3833 return bdrv_co_copy_range_to(src
, src_offset
, dst
, dst_offset
, bytes
,
3834 read_flags
, write_flags
);
3837 static int coroutine_fn GRAPH_RDLOCK
3838 raw_co_copy_range_to(BlockDriverState
*bs
,
3839 BdrvChild
*src
, int64_t src_offset
,
3840 BdrvChild
*dst
, int64_t dst_offset
,
3841 int64_t bytes
, BdrvRequestFlags read_flags
,
3842 BdrvRequestFlags write_flags
)
3844 RawPosixAIOData acb
;
3845 BDRVRawState
*s
= bs
->opaque
;
3846 BDRVRawState
*src_s
;
3848 assert(dst
->bs
== bs
);
3849 if (src
->bs
->drv
->bdrv_co_copy_range_to
!= raw_co_copy_range_to
) {
3853 src_s
= src
->bs
->opaque
;
3854 if (fd_open(src
->bs
) < 0 || fd_open(dst
->bs
) < 0) {
3858 acb
= (RawPosixAIOData
) {
3860 .aio_type
= QEMU_AIO_COPY_RANGE
,
3861 .aio_fildes
= src_s
->fd
,
3862 .aio_offset
= src_offset
,
3863 .aio_nbytes
= bytes
,
3866 .aio_offset2
= dst_offset
,
3870 return raw_thread_pool_submit(handle_aiocb_copy_range
, &acb
);
3873 BlockDriver bdrv_file
= {
3874 .format_name
= "file",
3875 .protocol_name
= "file",
3876 .instance_size
= sizeof(BDRVRawState
),
3877 .bdrv_needs_filename
= true,
3878 .bdrv_probe
= NULL
, /* no probe for protocols */
3879 .bdrv_parse_filename
= raw_parse_filename
,
3880 .bdrv_file_open
= raw_open
,
3881 .bdrv_reopen_prepare
= raw_reopen_prepare
,
3882 .bdrv_reopen_commit
= raw_reopen_commit
,
3883 .bdrv_reopen_abort
= raw_reopen_abort
,
3884 .bdrv_close
= raw_close
,
3885 .bdrv_co_create
= raw_co_create
,
3886 .bdrv_co_create_opts
= raw_co_create_opts
,
3887 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
3888 .bdrv_co_block_status
= raw_co_block_status
,
3889 .bdrv_co_invalidate_cache
= raw_co_invalidate_cache
,
3890 .bdrv_co_pwrite_zeroes
= raw_co_pwrite_zeroes
,
3891 .bdrv_co_delete_file
= raw_co_delete_file
,
3893 .bdrv_co_preadv
= raw_co_preadv
,
3894 .bdrv_co_pwritev
= raw_co_pwritev
,
3895 .bdrv_co_flush_to_disk
= raw_co_flush_to_disk
,
3896 .bdrv_co_pdiscard
= raw_co_pdiscard
,
3897 .bdrv_co_copy_range_from
= raw_co_copy_range_from
,
3898 .bdrv_co_copy_range_to
= raw_co_copy_range_to
,
3899 .bdrv_refresh_limits
= raw_refresh_limits
,
3900 .bdrv_attach_aio_context
= raw_aio_attach_aio_context
,
3902 .bdrv_co_truncate
= raw_co_truncate
,
3903 .bdrv_co_getlength
= raw_co_getlength
,
3904 .bdrv_co_get_info
= raw_co_get_info
,
3905 .bdrv_get_specific_info
= raw_get_specific_info
,
3906 .bdrv_co_get_allocated_file_size
= raw_co_get_allocated_file_size
,
3907 .bdrv_get_specific_stats
= raw_get_specific_stats
,
3908 .bdrv_check_perm
= raw_check_perm
,
3909 .bdrv_set_perm
= raw_set_perm
,
3910 .bdrv_abort_perm_update
= raw_abort_perm_update
,
3911 .create_opts
= &raw_create_opts
,
3912 .mutable_opts
= mutable_opts
,
3915 /***********************************************/
3918 #if defined(HAVE_HOST_BLOCK_DEVICE)
3920 #if defined(__APPLE__) && defined(__MACH__)
3921 static kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
3922 CFIndex maxPathSize
, int flags
);
3924 #if !defined(MAC_OS_VERSION_12_0) \
3925 || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_12_0)
3926 #define IOMainPort IOMasterPort
3929 static char *FindEjectableOpticalMedia(io_iterator_t
*mediaIterator
)
3931 kern_return_t kernResult
= KERN_FAILURE
;
3932 mach_port_t mainPort
;
3933 CFMutableDictionaryRef classesToMatch
;
3934 const char *matching_array
[] = {kIODVDMediaClass
, kIOCDMediaClass
};
3935 char *mediaType
= NULL
;
3937 kernResult
= IOMainPort(MACH_PORT_NULL
, &mainPort
);
3938 if ( KERN_SUCCESS
!= kernResult
) {
3939 printf("IOMainPort returned %d\n", kernResult
);
3943 for (index
= 0; index
< ARRAY_SIZE(matching_array
); index
++) {
3944 classesToMatch
= IOServiceMatching(matching_array
[index
]);
3945 if (classesToMatch
== NULL
) {
3946 error_report("IOServiceMatching returned NULL for %s",
3947 matching_array
[index
]);
3950 CFDictionarySetValue(classesToMatch
, CFSTR(kIOMediaEjectableKey
),
3952 kernResult
= IOServiceGetMatchingServices(mainPort
, classesToMatch
,
3954 if (kernResult
!= KERN_SUCCESS
) {
3955 error_report("Note: IOServiceGetMatchingServices returned %d",
3960 /* If a match was found, leave the loop */
3961 if (*mediaIterator
!= 0) {
3962 trace_file_FindEjectableOpticalMedia(matching_array
[index
]);
3963 mediaType
= g_strdup(matching_array
[index
]);
3970 kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
3971 CFIndex maxPathSize
, int flags
)
3973 io_object_t nextMedia
;
3974 kern_return_t kernResult
= KERN_FAILURE
;
3976 nextMedia
= IOIteratorNext( mediaIterator
);
3979 CFTypeRef bsdPathAsCFString
;
3980 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
3981 if ( bsdPathAsCFString
) {
3982 size_t devPathLength
;
3983 strcpy( bsdPath
, _PATH_DEV
);
3984 if (flags
& BDRV_O_NOCACHE
) {
3985 strcat(bsdPath
, "r");
3987 devPathLength
= strlen( bsdPath
);
3988 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
3989 kernResult
= KERN_SUCCESS
;
3991 CFRelease( bsdPathAsCFString
);
3993 IOObjectRelease( nextMedia
);
3999 /* Sets up a real cdrom for use in QEMU */
4000 static bool setup_cdrom(char *bsd_path
, Error
**errp
)
4002 int index
, num_of_test_partitions
= 2, fd
;
4003 char test_partition
[MAXPATHLEN
];
4004 bool partition_found
= false;
4006 /* look for a working partition */
4007 for (index
= 0; index
< num_of_test_partitions
; index
++) {
4008 snprintf(test_partition
, sizeof(test_partition
), "%ss%d", bsd_path
,
4010 fd
= qemu_open(test_partition
, O_RDONLY
| O_BINARY
| O_LARGEFILE
, NULL
);
4012 partition_found
= true;
4018 /* if a working partition on the device was not found */
4019 if (partition_found
== false) {
4020 error_setg(errp
, "Failed to find a working partition on disc");
4022 trace_file_setup_cdrom(test_partition
);
4023 pstrcpy(bsd_path
, MAXPATHLEN
, test_partition
);
4025 return partition_found
;
4028 /* Prints directions on mounting and unmounting a device */
4029 static void print_unmounting_directions(const char *file_name
)
4031 error_report("If device %s is mounted on the desktop, unmount"
4032 " it first before using it in QEMU", file_name
);
4033 error_report("Command to unmount device: diskutil unmountDisk %s",
4035 error_report("Command to mount device: diskutil mountDisk %s", file_name
);
4038 #endif /* defined(__APPLE__) && defined(__MACH__) */
4040 static int hdev_probe_device(const char *filename
)
4044 /* allow a dedicated CD-ROM driver to match with a higher priority */
4045 if (strstart(filename
, "/dev/cdrom", NULL
))
4048 if (stat(filename
, &st
) >= 0 &&
4049 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
4056 static void hdev_parse_filename(const char *filename
, QDict
*options
,
4059 bdrv_parse_filename_strip_prefix(filename
, "host_device:", options
);
4062 static bool hdev_is_sg(BlockDriverState
*bs
)
4065 #if defined(__linux__)
4067 BDRVRawState
*s
= bs
->opaque
;
4069 struct sg_scsi_id scsiid
;
4073 if (stat(bs
->filename
, &st
) < 0 || !S_ISCHR(st
.st_mode
)) {
4077 ret
= ioctl(s
->fd
, SG_GET_VERSION_NUM
, &sg_version
);
4082 ret
= ioctl(s
->fd
, SG_GET_SCSI_ID
, &scsiid
);
4084 trace_file_hdev_is_sg(scsiid
.scsi_type
, sg_version
);
4093 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
4096 BDRVRawState
*s
= bs
->opaque
;
4099 #if defined(__APPLE__) && defined(__MACH__)
4101 * Caution: while qdict_get_str() is fine, getting non-string types
4102 * would require more care. When @options come from -blockdev or
4103 * blockdev_add, its members are typed according to the QAPI
4104 * schema, but when they come from -drive, they're all QString.
4106 const char *filename
= qdict_get_str(options
, "filename");
4107 char bsd_path
[MAXPATHLEN
] = "";
4108 bool error_occurred
= false;
4110 /* If using a real cdrom */
4111 if (strcmp(filename
, "/dev/cdrom") == 0) {
4112 char *mediaType
= NULL
;
4113 kern_return_t ret_val
;
4114 io_iterator_t mediaIterator
= 0;
4116 mediaType
= FindEjectableOpticalMedia(&mediaIterator
);
4117 if (mediaType
== NULL
) {
4118 error_setg(errp
, "Please make sure your CD/DVD is in the optical"
4120 error_occurred
= true;
4121 goto hdev_open_Mac_error
;
4124 ret_val
= GetBSDPath(mediaIterator
, bsd_path
, sizeof(bsd_path
), flags
);
4125 if (ret_val
!= KERN_SUCCESS
) {
4126 error_setg(errp
, "Could not get BSD path for optical drive");
4127 error_occurred
= true;
4128 goto hdev_open_Mac_error
;
4131 /* If a real optical drive was not found */
4132 if (bsd_path
[0] == '\0') {
4133 error_setg(errp
, "Failed to obtain bsd path for optical drive");
4134 error_occurred
= true;
4135 goto hdev_open_Mac_error
;
4138 /* If using a cdrom disc and finding a partition on the disc failed */
4139 if (strncmp(mediaType
, kIOCDMediaClass
, 9) == 0 &&
4140 setup_cdrom(bsd_path
, errp
) == false) {
4141 print_unmounting_directions(bsd_path
);
4142 error_occurred
= true;
4143 goto hdev_open_Mac_error
;
4146 qdict_put_str(options
, "filename", bsd_path
);
4148 hdev_open_Mac_error
:
4150 if (mediaIterator
) {
4151 IOObjectRelease(mediaIterator
);
4153 if (error_occurred
) {
4157 #endif /* defined(__APPLE__) && defined(__MACH__) */
4159 s
->type
= FTYPE_FILE
;
4161 ret
= raw_open_common(bs
, options
, flags
, 0, true, errp
);
4163 #if defined(__APPLE__) && defined(__MACH__)
4165 filename
= bsd_path
;
4167 /* if a physical device experienced an error while being opened */
4168 if (strncmp(filename
, "/dev/", 5) == 0) {
4169 print_unmounting_directions(filename
);
4171 #endif /* defined(__APPLE__) && defined(__MACH__) */
4175 /* Since this does ioctl the device must be already opened */
4176 bs
->sg
= hdev_is_sg(bs
);
4181 #if defined(__linux__)
4182 static int coroutine_fn
4183 hdev_co_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
4185 BDRVRawState
*s
= bs
->opaque
;
4186 RawPosixAIOData acb
;
4194 if (req
== SG_IO
&& s
->pr_mgr
) {
4195 struct sg_io_hdr
*io_hdr
= buf
;
4196 if (io_hdr
->cmdp
[0] == PERSISTENT_RESERVE_OUT
||
4197 io_hdr
->cmdp
[0] == PERSISTENT_RESERVE_IN
) {
4198 return pr_manager_execute(s
->pr_mgr
, qemu_get_current_aio_context(),
4203 acb
= (RawPosixAIOData
) {
4205 .aio_type
= QEMU_AIO_IOCTL
,
4206 .aio_fildes
= s
->fd
,
4214 return raw_thread_pool_submit(handle_aiocb_ioctl
, &acb
);
4218 static coroutine_fn
int
4219 hdev_co_pdiscard(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
4221 BDRVRawState
*s
= bs
->opaque
;
4226 raw_account_discard(s
, bytes
, ret
);
4229 return raw_do_pdiscard(bs
, offset
, bytes
, true);
4232 static coroutine_fn
int hdev_co_pwrite_zeroes(BlockDriverState
*bs
,
4233 int64_t offset
, int64_t bytes
, BdrvRequestFlags flags
)
4242 return raw_do_pwrite_zeroes(bs
, offset
, bytes
, flags
, true);
4245 static BlockDriver bdrv_host_device
= {
4246 .format_name
= "host_device",
4247 .protocol_name
= "host_device",
4248 .instance_size
= sizeof(BDRVRawState
),
4249 .bdrv_needs_filename
= true,
4250 .bdrv_probe_device
= hdev_probe_device
,
4251 .bdrv_parse_filename
= hdev_parse_filename
,
4252 .bdrv_file_open
= hdev_open
,
4253 .bdrv_close
= raw_close
,
4254 .bdrv_reopen_prepare
= raw_reopen_prepare
,
4255 .bdrv_reopen_commit
= raw_reopen_commit
,
4256 .bdrv_reopen_abort
= raw_reopen_abort
,
4257 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
4258 .create_opts
= &bdrv_create_opts_simple
,
4259 .mutable_opts
= mutable_opts
,
4260 .bdrv_co_invalidate_cache
= raw_co_invalidate_cache
,
4261 .bdrv_co_pwrite_zeroes
= hdev_co_pwrite_zeroes
,
4263 .bdrv_co_preadv
= raw_co_preadv
,
4264 .bdrv_co_pwritev
= raw_co_pwritev
,
4265 .bdrv_co_flush_to_disk
= raw_co_flush_to_disk
,
4266 .bdrv_co_pdiscard
= hdev_co_pdiscard
,
4267 .bdrv_co_copy_range_from
= raw_co_copy_range_from
,
4268 .bdrv_co_copy_range_to
= raw_co_copy_range_to
,
4269 .bdrv_refresh_limits
= raw_refresh_limits
,
4270 .bdrv_attach_aio_context
= raw_aio_attach_aio_context
,
4272 .bdrv_co_truncate
= raw_co_truncate
,
4273 .bdrv_co_getlength
= raw_co_getlength
,
4274 .bdrv_co_get_info
= raw_co_get_info
,
4275 .bdrv_get_specific_info
= raw_get_specific_info
,
4276 .bdrv_co_get_allocated_file_size
= raw_co_get_allocated_file_size
,
4277 .bdrv_get_specific_stats
= hdev_get_specific_stats
,
4278 .bdrv_check_perm
= raw_check_perm
,
4279 .bdrv_set_perm
= raw_set_perm
,
4280 .bdrv_abort_perm_update
= raw_abort_perm_update
,
4281 .bdrv_probe_blocksizes
= hdev_probe_blocksizes
,
4282 .bdrv_probe_geometry
= hdev_probe_geometry
,
4284 /* generic scsi device */
4286 .bdrv_co_ioctl
= hdev_co_ioctl
,
4290 #if defined(CONFIG_BLKZONED)
4291 /* zone management operations */
4292 .bdrv_co_zone_report
= raw_co_zone_report
,
4293 .bdrv_co_zone_mgmt
= raw_co_zone_mgmt
,
4294 .bdrv_co_zone_append
= raw_co_zone_append
,
4298 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
4299 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
4302 bdrv_parse_filename_strip_prefix(filename
, "host_cdrom:", options
);
4305 static void cdrom_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
4307 bs
->bl
.has_variable_length
= true;
4308 raw_refresh_limits(bs
, errp
);
4313 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
4316 BDRVRawState
*s
= bs
->opaque
;
4320 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
4321 return raw_open_common(bs
, options
, flags
, O_NONBLOCK
, true, errp
);
4324 static int cdrom_probe_device(const char *filename
)
4330 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
, NULL
);
4334 ret
= fstat(fd
, &st
);
4335 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
4339 /* Attempt to detect via a CDROM specific ioctl */
4340 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
4350 static bool coroutine_fn
cdrom_co_is_inserted(BlockDriverState
*bs
)
4352 BDRVRawState
*s
= bs
->opaque
;
4355 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
4356 return ret
== CDS_DISC_OK
;
4359 static void coroutine_fn
cdrom_co_eject(BlockDriverState
*bs
, bool eject_flag
)
4361 BDRVRawState
*s
= bs
->opaque
;
4364 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
4365 perror("CDROMEJECT");
4367 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
4368 perror("CDROMEJECT");
4372 static void coroutine_fn
cdrom_co_lock_medium(BlockDriverState
*bs
, bool locked
)
4374 BDRVRawState
*s
= bs
->opaque
;
4376 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
4378 * Note: an error can happen if the distribution automatically
4381 /* perror("CDROM_LOCKDOOR"); */
4385 static BlockDriver bdrv_host_cdrom
= {
4386 .format_name
= "host_cdrom",
4387 .protocol_name
= "host_cdrom",
4388 .instance_size
= sizeof(BDRVRawState
),
4389 .bdrv_needs_filename
= true,
4390 .bdrv_probe_device
= cdrom_probe_device
,
4391 .bdrv_parse_filename
= cdrom_parse_filename
,
4392 .bdrv_file_open
= cdrom_open
,
4393 .bdrv_close
= raw_close
,
4394 .bdrv_reopen_prepare
= raw_reopen_prepare
,
4395 .bdrv_reopen_commit
= raw_reopen_commit
,
4396 .bdrv_reopen_abort
= raw_reopen_abort
,
4397 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
4398 .create_opts
= &bdrv_create_opts_simple
,
4399 .mutable_opts
= mutable_opts
,
4400 .bdrv_co_invalidate_cache
= raw_co_invalidate_cache
,
4402 .bdrv_co_preadv
= raw_co_preadv
,
4403 .bdrv_co_pwritev
= raw_co_pwritev
,
4404 .bdrv_co_flush_to_disk
= raw_co_flush_to_disk
,
4405 .bdrv_refresh_limits
= cdrom_refresh_limits
,
4406 .bdrv_attach_aio_context
= raw_aio_attach_aio_context
,
4408 .bdrv_co_truncate
= raw_co_truncate
,
4409 .bdrv_co_getlength
= raw_co_getlength
,
4410 .bdrv_co_get_allocated_file_size
= raw_co_get_allocated_file_size
,
4412 /* removable device support */
4413 .bdrv_co_is_inserted
= cdrom_co_is_inserted
,
4414 .bdrv_co_eject
= cdrom_co_eject
,
4415 .bdrv_co_lock_medium
= cdrom_co_lock_medium
,
4417 /* generic scsi device */
4418 .bdrv_co_ioctl
= hdev_co_ioctl
,
4420 #endif /* __linux__ */
4422 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
4423 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
4426 BDRVRawState
*s
= bs
->opaque
;
4431 ret
= raw_open_common(bs
, options
, flags
, 0, true, errp
);
4436 /* make sure the door isn't locked at this time */
4437 ioctl(s
->fd
, CDIOCALLOW
);
4441 static int cdrom_probe_device(const char *filename
)
4443 if (strstart(filename
, "/dev/cd", NULL
) ||
4444 strstart(filename
, "/dev/acd", NULL
))
4449 static int cdrom_reopen(BlockDriverState
*bs
)
4451 BDRVRawState
*s
= bs
->opaque
;
4455 * Force reread of possibly changed/newly loaded disc,
4456 * FreeBSD seems to not notice sometimes...
4460 fd
= qemu_open(bs
->filename
, s
->open_flags
, NULL
);
4467 /* make sure the door isn't locked at this time */
4468 ioctl(s
->fd
, CDIOCALLOW
);
4472 static bool coroutine_fn
cdrom_co_is_inserted(BlockDriverState
*bs
)
4474 return raw_getlength(bs
) > 0;
4477 static void coroutine_fn
cdrom_co_eject(BlockDriverState
*bs
, bool eject_flag
)
4479 BDRVRawState
*s
= bs
->opaque
;
4484 (void) ioctl(s
->fd
, CDIOCALLOW
);
4487 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
4488 perror("CDIOCEJECT");
4490 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
4491 perror("CDIOCCLOSE");
4497 static void coroutine_fn
cdrom_co_lock_medium(BlockDriverState
*bs
, bool locked
)
4499 BDRVRawState
*s
= bs
->opaque
;
4503 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
4505 * Note: an error can happen if the distribution automatically
4508 /* perror("CDROM_LOCKDOOR"); */
4512 static BlockDriver bdrv_host_cdrom
= {
4513 .format_name
= "host_cdrom",
4514 .protocol_name
= "host_cdrom",
4515 .instance_size
= sizeof(BDRVRawState
),
4516 .bdrv_needs_filename
= true,
4517 .bdrv_probe_device
= cdrom_probe_device
,
4518 .bdrv_parse_filename
= cdrom_parse_filename
,
4519 .bdrv_file_open
= cdrom_open
,
4520 .bdrv_close
= raw_close
,
4521 .bdrv_reopen_prepare
= raw_reopen_prepare
,
4522 .bdrv_reopen_commit
= raw_reopen_commit
,
4523 .bdrv_reopen_abort
= raw_reopen_abort
,
4524 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
4525 .create_opts
= &bdrv_create_opts_simple
,
4526 .mutable_opts
= mutable_opts
,
4528 .bdrv_co_preadv
= raw_co_preadv
,
4529 .bdrv_co_pwritev
= raw_co_pwritev
,
4530 .bdrv_co_flush_to_disk
= raw_co_flush_to_disk
,
4531 .bdrv_refresh_limits
= cdrom_refresh_limits
,
4532 .bdrv_attach_aio_context
= raw_aio_attach_aio_context
,
4534 .bdrv_co_truncate
= raw_co_truncate
,
4535 .bdrv_co_getlength
= raw_co_getlength
,
4536 .bdrv_co_get_allocated_file_size
= raw_co_get_allocated_file_size
,
4538 /* removable device support */
4539 .bdrv_co_is_inserted
= cdrom_co_is_inserted
,
4540 .bdrv_co_eject
= cdrom_co_eject
,
4541 .bdrv_co_lock_medium
= cdrom_co_lock_medium
,
4543 #endif /* __FreeBSD__ */
4545 #endif /* HAVE_HOST_BLOCK_DEVICE */
4547 static void bdrv_file_init(void)
4550 * Register all the drivers. Note that order is important, the driver
4551 * registered last will get probed first.
4553 bdrv_register(&bdrv_file
);
4554 #if defined(HAVE_HOST_BLOCK_DEVICE)
4555 bdrv_register(&bdrv_host_device
);
4557 bdrv_register(&bdrv_host_cdrom
);
4559 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
4560 bdrv_register(&bdrv_host_cdrom
);
4562 #endif /* HAVE_HOST_BLOCK_DEVICE */
4565 block_init(bdrv_file_init
);