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 "qemu-common.h"
27 #include "qapi/error.h"
28 #include "qemu/cutils.h"
29 #include "qemu/error-report.h"
30 #include "block/block_int.h"
31 #include "qemu/module.h"
32 #include "qemu/option.h"
33 #include "qemu/units.h"
35 #include "block/thread-pool.h"
37 #include "block/raw-aio.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qstring.h"
41 #include "scsi/pr-manager.h"
42 #include "scsi/constants.h"
44 #if defined(__APPLE__) && (__MACH__)
45 #include <sys/ioctl.h>
46 #if defined(HAVE_HOST_BLOCK_DEVICE)
48 #include <sys/param.h>
49 #include <IOKit/IOKitLib.h>
50 #include <IOKit/IOBSD.h>
51 #include <IOKit/storage/IOMediaBSDClient.h>
52 #include <IOKit/storage/IOMedia.h>
53 #include <IOKit/storage/IOCDMedia.h>
54 //#include <IOKit/storage/IOCDTypes.h>
55 #include <IOKit/storage/IODVDMedia.h>
56 #include <CoreFoundation/CoreFoundation.h>
57 #endif /* defined(HAVE_HOST_BLOCK_DEVICE) */
61 #define _POSIX_PTHREAD_SEMANTICS 1
65 #include <sys/ioctl.h>
66 #include <sys/param.h>
67 #include <sys/syscall.h>
69 #include <linux/cdrom.h>
72 #include <linux/hdreg.h>
73 #include <linux/magic.h>
79 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
82 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
83 #include <linux/falloc.h>
85 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
91 #include <sys/ioctl.h>
92 #include <sys/disklabel.h>
97 #include <sys/ioctl.h>
98 #include <sys/disklabel.h>
100 #include <sys/disk.h>
104 #include <sys/ioctl.h>
105 #include <sys/diskslice.h>
112 /* OS X does not have O_DSYNC */
115 #define O_DSYNC O_SYNC
116 #elif defined(O_FSYNC)
117 #define O_DSYNC O_FSYNC
121 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
123 #define O_DIRECT O_DSYNC
129 #define MAX_BLOCKSIZE 4096
131 /* Posix file locking bytes. Libvirt takes byte 0, we start from higher bytes,
132 * leaving a few more bytes for its future use. */
133 #define RAW_LOCK_PERM_BASE 100
134 #define RAW_LOCK_SHARED_BASE 200
136 typedef struct BDRVRawState
{
143 /* The current permissions. */
145 uint64_t shared_perm
;
147 /* The perms bits whose corresponding bytes are already locked in
149 uint64_t locked_perm
;
150 uint64_t locked_shared_perm
;
153 int perm_change_flags
;
154 BDRVReopenState
*reopen_state
;
160 bool has_write_zeroes
:1;
161 bool discard_zeroes
:1;
162 bool use_linux_aio
:1;
163 bool use_linux_io_uring
:1;
164 int page_cache_inconsistent
; /* errno from fdatasync failure */
166 bool needs_alignment
;
168 bool check_cache_dropped
;
170 uint64_t discard_nb_ok
;
171 uint64_t discard_nb_failed
;
172 uint64_t discard_bytes_ok
;
178 typedef struct BDRVRawReopenState
{
181 bool check_cache_dropped
;
182 } BDRVRawReopenState
;
184 static int fd_open(BlockDriverState
*bs
)
186 BDRVRawState
*s
= bs
->opaque
;
188 /* this is just to ensure s->fd is sane (its called by io ops) */
195 static int64_t raw_getlength(BlockDriverState
*bs
);
197 typedef struct RawPosixAIOData
{
198 BlockDriverState
*bs
;
219 PreallocMode prealloc
;
225 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
226 static int cdrom_reopen(BlockDriverState
*bs
);
230 * Elide EAGAIN and EACCES details when failing to lock, as this
231 * indicates that the specified file region is already locked by
232 * another process, which is considered a common scenario.
234 #define raw_lock_error_setg_errno(errp, err, fmt, ...) \
236 if ((err) == EAGAIN || (err) == EACCES) { \
237 error_setg((errp), (fmt), ## __VA_ARGS__); \
239 error_setg_errno((errp), (err), (fmt), ## __VA_ARGS__); \
243 #if defined(__NetBSD__)
244 static int raw_normalize_devicepath(const char **filename
, Error
**errp
)
246 static char namebuf
[PATH_MAX
];
247 const char *dp
, *fname
;
251 dp
= strrchr(fname
, '/');
252 if (lstat(fname
, &sb
) < 0) {
253 error_setg_file_open(errp
, errno
, fname
);
257 if (!S_ISBLK(sb
.st_mode
)) {
262 snprintf(namebuf
, PATH_MAX
, "r%s", fname
);
264 snprintf(namebuf
, PATH_MAX
, "%.*s/r%s",
265 (int)(dp
- fname
), fname
, dp
+ 1);
268 warn_report("%s is a block device, using %s", fname
, *filename
);
273 static int raw_normalize_devicepath(const char **filename
, Error
**errp
)
280 * Get logical block size via ioctl. On success store it in @sector_size_p.
282 static int probe_logical_blocksize(int fd
, unsigned int *sector_size_p
)
284 unsigned int sector_size
;
285 bool success
= false;
289 static const unsigned long ioctl_list
[] = {
293 #ifdef DKIOCGETBLOCKSIZE
296 #ifdef DIOCGSECTORSIZE
301 /* Try a few ioctls to get the right size */
302 for (i
= 0; i
< (int)ARRAY_SIZE(ioctl_list
); i
++) {
303 if (ioctl(fd
, ioctl_list
[i
], §or_size
) >= 0) {
304 *sector_size_p
= sector_size
;
309 return success
? 0 : -errno
;
313 * Get physical block size of @fd.
314 * On success, store it in @blk_size and return 0.
315 * On failure, return -errno.
317 static int probe_physical_blocksize(int fd
, unsigned int *blk_size
)
320 if (ioctl(fd
, BLKPBSZGET
, blk_size
) < 0) {
330 * Returns true if no alignment restrictions are necessary even for files
331 * opened with O_DIRECT.
333 * raw_probe_alignment() probes the required alignment and assume that 1 means
334 * the probing failed, so it falls back to a safe default of 4k. This can be
335 * avoided if we know that byte alignment is okay for the file.
337 static bool dio_byte_aligned(int fd
)
343 ret
= fstatfs(fd
, &buf
);
344 if (ret
== 0 && buf
.f_type
== NFS_SUPER_MAGIC
) {
351 /* Check if read is allowed with given memory buffer and length.
353 * This function is used to check O_DIRECT memory buffer and request alignment.
355 static bool raw_is_io_aligned(int fd
, void *buf
, size_t len
)
357 ssize_t ret
= pread(fd
, buf
, len
, 0);
364 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
365 * other errors (e.g. real I/O error), which could happen on a failed
366 * drive, since we only care about probing alignment.
368 if (errno
!= EINVAL
) {
376 static void raw_probe_alignment(BlockDriverState
*bs
, int fd
, Error
**errp
)
378 BDRVRawState
*s
= bs
->opaque
;
380 size_t max_align
= MAX(MAX_BLOCKSIZE
, qemu_real_host_page_size
);
381 size_t alignments
[] = {1, 512, 1024, 2048, 4096};
383 /* For SCSI generic devices the alignment is not really used.
384 With buffered I/O, we don't have any restrictions. */
385 if (bdrv_is_sg(bs
) || !s
->needs_alignment
) {
386 bs
->bl
.request_alignment
= 1;
391 bs
->bl
.request_alignment
= 0;
393 /* Let's try to use the logical blocksize for the alignment. */
394 if (probe_logical_blocksize(fd
, &bs
->bl
.request_alignment
) < 0) {
395 bs
->bl
.request_alignment
= 0;
400 if (xfsctl(NULL
, fd
, XFS_IOC_DIOINFO
, &da
) >= 0) {
401 bs
->bl
.request_alignment
= da
.d_miniosz
;
402 /* The kernel returns wrong information for d_mem */
403 /* s->buf_align = da.d_mem; */
409 * If we could not get the sizes so far, we can only guess them. First try
410 * to detect request alignment, since it is more likely to succeed. Then
411 * try to detect buf_align, which cannot be detected in some cases (e.g.
412 * Gluster). If buf_align cannot be detected, we fallback to the value of
416 if (!bs
->bl
.request_alignment
) {
419 buf
= qemu_memalign(max_align
, max_align
);
420 for (i
= 0; i
< ARRAY_SIZE(alignments
); i
++) {
421 align
= alignments
[i
];
422 if (raw_is_io_aligned(fd
, buf
, align
)) {
423 /* Fallback to safe value. */
424 bs
->bl
.request_alignment
= (align
!= 1) ? align
: max_align
;
434 buf
= qemu_memalign(max_align
, 2 * max_align
);
435 for (i
= 0; i
< ARRAY_SIZE(alignments
); i
++) {
436 align
= alignments
[i
];
437 if (raw_is_io_aligned(fd
, buf
+ align
, max_align
)) {
438 /* Fallback to request_alignment. */
439 s
->buf_align
= (align
!= 1) ? align
: bs
->bl
.request_alignment
;
446 if (!s
->buf_align
|| !bs
->bl
.request_alignment
) {
447 error_setg(errp
, "Could not find working O_DIRECT alignment");
448 error_append_hint(errp
, "Try cache.direct=off\n");
452 static int check_hdev_writable(int fd
)
454 #if defined(BLKROGET)
455 /* Linux block devices can be configured "read-only" using blockdev(8).
456 * This is independent of device node permissions and therefore open(2)
457 * with O_RDWR succeeds. Actual writes fail with EPERM.
459 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
460 * check for read-only block devices so that Linux block devices behave
466 if (fstat(fd
, &st
)) {
470 if (!S_ISBLK(st
.st_mode
)) {
474 if (ioctl(fd
, BLKROGET
, &readonly
) < 0) {
481 #endif /* defined(BLKROGET) */
485 static void raw_parse_flags(int bdrv_flags
, int *open_flags
, bool has_writers
)
487 bool read_write
= false;
488 assert(open_flags
!= NULL
);
490 *open_flags
|= O_BINARY
;
491 *open_flags
&= ~O_ACCMODE
;
493 if (bdrv_flags
& BDRV_O_AUTO_RDONLY
) {
494 read_write
= has_writers
;
495 } else if (bdrv_flags
& BDRV_O_RDWR
) {
500 *open_flags
|= O_RDWR
;
502 *open_flags
|= O_RDONLY
;
505 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
506 * and O_DIRECT for no caching. */
507 if ((bdrv_flags
& BDRV_O_NOCACHE
)) {
508 *open_flags
|= O_DIRECT
;
512 static void raw_parse_filename(const char *filename
, QDict
*options
,
515 bdrv_parse_filename_strip_prefix(filename
, "file:", options
);
518 static QemuOptsList raw_runtime_opts
= {
520 .head
= QTAILQ_HEAD_INITIALIZER(raw_runtime_opts
.head
),
524 .type
= QEMU_OPT_STRING
,
525 .help
= "File name of the image",
529 .type
= QEMU_OPT_STRING
,
530 .help
= "host AIO implementation (threads, native, io_uring)",
534 .type
= QEMU_OPT_STRING
,
535 .help
= "file locking mode (on/off/auto, default: auto)",
538 .name
= "pr-manager",
539 .type
= QEMU_OPT_STRING
,
540 .help
= "id of persistent reservation manager object (default: none)",
542 #if defined(__linux__)
544 .name
= "drop-cache",
545 .type
= QEMU_OPT_BOOL
,
546 .help
= "invalidate page cache during live migration (default: on)",
550 .name
= "x-check-cache-dropped",
551 .type
= QEMU_OPT_BOOL
,
552 .help
= "check that page cache was dropped on live migration (default: off)"
554 { /* end of list */ }
558 static const char *const mutable_opts
[] = { "x-check-cache-dropped", NULL
};
560 static int raw_open_common(BlockDriverState
*bs
, QDict
*options
,
561 int bdrv_flags
, int open_flags
,
562 bool device
, Error
**errp
)
564 BDRVRawState
*s
= bs
->opaque
;
566 Error
*local_err
= NULL
;
567 const char *filename
= NULL
;
569 BlockdevAioOptions aio
, aio_default
;
574 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
575 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
580 filename
= qemu_opt_get(opts
, "filename");
582 ret
= raw_normalize_devicepath(&filename
, errp
);
587 if (bdrv_flags
& BDRV_O_NATIVE_AIO
) {
588 aio_default
= BLOCKDEV_AIO_OPTIONS_NATIVE
;
589 #ifdef CONFIG_LINUX_IO_URING
590 } else if (bdrv_flags
& BDRV_O_IO_URING
) {
591 aio_default
= BLOCKDEV_AIO_OPTIONS_IO_URING
;
594 aio_default
= BLOCKDEV_AIO_OPTIONS_THREADS
;
597 aio
= qapi_enum_parse(&BlockdevAioOptions_lookup
,
598 qemu_opt_get(opts
, "aio"),
599 aio_default
, &local_err
);
601 error_propagate(errp
, local_err
);
606 s
->use_linux_aio
= (aio
== BLOCKDEV_AIO_OPTIONS_NATIVE
);
607 #ifdef CONFIG_LINUX_IO_URING
608 s
->use_linux_io_uring
= (aio
== BLOCKDEV_AIO_OPTIONS_IO_URING
);
611 locking
= qapi_enum_parse(&OnOffAuto_lookup
,
612 qemu_opt_get(opts
, "locking"),
613 ON_OFF_AUTO_AUTO
, &local_err
);
615 error_propagate(errp
, local_err
);
622 if (!qemu_has_ofd_lock()) {
623 warn_report("File lock requested but OFD locking syscall is "
624 "unavailable, falling back to POSIX file locks");
625 error_printf("Due to the implementation, locks can be lost "
629 case ON_OFF_AUTO_OFF
:
632 case ON_OFF_AUTO_AUTO
:
633 s
->use_lock
= qemu_has_ofd_lock();
639 str
= qemu_opt_get(opts
, "pr-manager");
641 s
->pr_mgr
= pr_manager_lookup(str
, &local_err
);
643 error_propagate(errp
, local_err
);
649 s
->drop_cache
= qemu_opt_get_bool(opts
, "drop-cache", true);
650 s
->check_cache_dropped
= qemu_opt_get_bool(opts
, "x-check-cache-dropped",
653 s
->open_flags
= open_flags
;
654 raw_parse_flags(bdrv_flags
, &s
->open_flags
, false);
657 fd
= qemu_open(filename
, s
->open_flags
, errp
);
658 ret
= fd
< 0 ? -errno
: 0;
668 /* Check s->open_flags rather than bdrv_flags due to auto-read-only */
669 if (s
->open_flags
& O_RDWR
) {
670 ret
= check_hdev_writable(s
->fd
);
672 error_setg_errno(errp
, -ret
, "The device is not writable");
678 s
->shared_perm
= BLK_PERM_ALL
;
680 #ifdef CONFIG_LINUX_AIO
681 /* Currently Linux does AIO only for files opened with O_DIRECT */
682 if (s
->use_linux_aio
) {
683 if (!(s
->open_flags
& O_DIRECT
)) {
684 error_setg(errp
, "aio=native was specified, but it requires "
685 "cache.direct=on, which was not specified.");
689 if (!aio_setup_linux_aio(bdrv_get_aio_context(bs
), errp
)) {
690 error_prepend(errp
, "Unable to use native AIO: ");
695 if (s
->use_linux_aio
) {
696 error_setg(errp
, "aio=native was specified, but is not supported "
701 #endif /* !defined(CONFIG_LINUX_AIO) */
703 #ifdef CONFIG_LINUX_IO_URING
704 if (s
->use_linux_io_uring
) {
705 if (!aio_setup_linux_io_uring(bdrv_get_aio_context(bs
), errp
)) {
706 error_prepend(errp
, "Unable to use io_uring: ");
711 if (s
->use_linux_io_uring
) {
712 error_setg(errp
, "aio=io_uring was specified, but is not supported "
717 #endif /* !defined(CONFIG_LINUX_IO_URING) */
719 s
->has_discard
= true;
720 s
->has_write_zeroes
= true;
721 if ((bs
->open_flags
& BDRV_O_NOCACHE
) != 0 && !dio_byte_aligned(s
->fd
)) {
722 s
->needs_alignment
= true;
725 if (fstat(s
->fd
, &st
) < 0) {
727 error_setg_errno(errp
, errno
, "Could not stat file");
732 if (!S_ISREG(st
.st_mode
)) {
733 error_setg(errp
, "'%s' driver requires '%s' to be a regular file",
734 bs
->drv
->format_name
, bs
->filename
);
738 s
->discard_zeroes
= true;
739 s
->has_fallocate
= true;
742 if (!(S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
743 error_setg(errp
, "'%s' driver requires '%s' to be either "
744 "a character or block device",
745 bs
->drv
->format_name
, bs
->filename
);
751 if (S_ISBLK(st
.st_mode
)) {
752 #ifdef BLKDISCARDZEROES
754 if (ioctl(s
->fd
, BLKDISCARDZEROES
, &arg
) == 0 && arg
) {
755 s
->discard_zeroes
= true;
759 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
760 * not rely on the contents of discarded blocks unless using O_DIRECT.
761 * Same for BLKZEROOUT.
763 if (!(bs
->open_flags
& BDRV_O_NOCACHE
)) {
764 s
->discard_zeroes
= false;
765 s
->has_write_zeroes
= false;
770 if (S_ISCHR(st
.st_mode
)) {
772 * The file is a char device (disk), which on FreeBSD isn't behind
773 * a pager, so force all requests to be aligned. This is needed
774 * so QEMU makes sure all IO operations on the device are aligned
775 * to sector size, or else FreeBSD will reject them with EINVAL.
777 s
->needs_alignment
= true;
782 if (platform_test_xfs_fd(s
->fd
)) {
787 bs
->supported_zero_flags
= BDRV_REQ_MAY_UNMAP
| BDRV_REQ_NO_FALLBACK
;
788 if (S_ISREG(st
.st_mode
)) {
789 /* When extending regular files, we get zeros from the OS */
790 bs
->supported_truncate_flags
= BDRV_REQ_ZERO_WRITE
;
794 if (ret
< 0 && s
->fd
!= -1) {
797 if (filename
&& (bdrv_flags
& BDRV_O_TEMPORARY
)) {
804 static int raw_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
807 BDRVRawState
*s
= bs
->opaque
;
809 s
->type
= FTYPE_FILE
;
810 return raw_open_common(bs
, options
, flags
, 0, false, errp
);
819 #define PERM_FOREACH(i) \
820 for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
822 /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
823 * file; if @unlock == true, also unlock the unneeded bytes.
824 * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
826 static int raw_apply_lock_bytes(BDRVRawState
*s
, int fd
,
827 uint64_t perm_lock_bits
,
828 uint64_t shared_perm_lock_bits
,
829 bool unlock
, Error
**errp
)
833 uint64_t locked_perm
, locked_shared_perm
;
836 locked_perm
= s
->locked_perm
;
837 locked_shared_perm
= s
->locked_shared_perm
;
840 * We don't have the previous bits, just lock/unlock for each of the
844 locked_perm
= BLK_PERM_ALL
;
845 locked_shared_perm
= BLK_PERM_ALL
;
848 locked_shared_perm
= 0;
853 int off
= RAW_LOCK_PERM_BASE
+ i
;
854 uint64_t bit
= (1ULL << i
);
855 if ((perm_lock_bits
& bit
) && !(locked_perm
& bit
)) {
856 ret
= qemu_lock_fd(fd
, off
, 1, false);
858 raw_lock_error_setg_errno(errp
, -ret
, "Failed to lock byte %d",
862 s
->locked_perm
|= bit
;
864 } else if (unlock
&& (locked_perm
& bit
) && !(perm_lock_bits
& bit
)) {
865 ret
= qemu_unlock_fd(fd
, off
, 1);
867 error_setg_errno(errp
, -ret
, "Failed to unlock byte %d", off
);
870 s
->locked_perm
&= ~bit
;
875 int off
= RAW_LOCK_SHARED_BASE
+ i
;
876 uint64_t bit
= (1ULL << i
);
877 if ((shared_perm_lock_bits
& bit
) && !(locked_shared_perm
& bit
)) {
878 ret
= qemu_lock_fd(fd
, off
, 1, false);
880 raw_lock_error_setg_errno(errp
, -ret
, "Failed to lock byte %d",
884 s
->locked_shared_perm
|= bit
;
886 } else if (unlock
&& (locked_shared_perm
& bit
) &&
887 !(shared_perm_lock_bits
& bit
)) {
888 ret
= qemu_unlock_fd(fd
, off
, 1);
890 error_setg_errno(errp
, -ret
, "Failed to unlock byte %d", off
);
893 s
->locked_shared_perm
&= ~bit
;
900 /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
901 static int raw_check_lock_bytes(int fd
, uint64_t perm
, uint64_t shared_perm
,
908 int off
= RAW_LOCK_SHARED_BASE
+ i
;
909 uint64_t p
= 1ULL << i
;
911 ret
= qemu_lock_fd_test(fd
, off
, 1, true);
913 char *perm_name
= bdrv_perm_names(p
);
915 raw_lock_error_setg_errno(errp
, -ret
,
916 "Failed to get \"%s\" lock",
924 int off
= RAW_LOCK_PERM_BASE
+ i
;
925 uint64_t p
= 1ULL << i
;
926 if (!(shared_perm
& p
)) {
927 ret
= qemu_lock_fd_test(fd
, off
, 1, true);
929 char *perm_name
= bdrv_perm_names(p
);
931 raw_lock_error_setg_errno(errp
, -ret
,
932 "Failed to get shared \"%s\" lock",
942 static int raw_handle_perm_lock(BlockDriverState
*bs
,
944 uint64_t new_perm
, uint64_t new_shared
,
947 BDRVRawState
*s
= bs
->opaque
;
949 Error
*local_err
= NULL
;
955 if (bdrv_get_flags(bs
) & BDRV_O_INACTIVE
) {
961 if ((s
->perm
| new_perm
) == s
->perm
&&
962 (s
->shared_perm
& new_shared
) == s
->shared_perm
)
965 * We are going to unlock bytes, it should not fail. If it fail due
966 * to some fs-dependent permission-unrelated reasons (which occurs
967 * sometimes on NFS and leads to abort in bdrv_replace_child) we
968 * can't prevent such errors by any check here. And we ignore them
969 * anyway in ABORT and COMMIT.
973 ret
= raw_apply_lock_bytes(s
, s
->fd
, s
->perm
| new_perm
,
974 ~s
->shared_perm
| ~new_shared
,
977 ret
= raw_check_lock_bytes(s
->fd
, new_perm
, new_shared
, errp
);
981 error_append_hint(errp
,
982 "Is another process using the image [%s]?\n",
985 /* fall through to unlock bytes. */
987 raw_apply_lock_bytes(s
, s
->fd
, s
->perm
, ~s
->shared_perm
,
990 /* Theoretically the above call only unlocks bytes and it cannot
991 * fail. Something weird happened, report it.
993 warn_report_err(local_err
);
997 raw_apply_lock_bytes(s
, s
->fd
, new_perm
, ~new_shared
,
1000 /* Theoretically the above call only unlocks bytes and it cannot
1001 * fail. Something weird happened, report it.
1003 warn_report_err(local_err
);
1010 static int raw_reconfigure_getfd(BlockDriverState
*bs
, int flags
,
1011 int *open_flags
, uint64_t perm
, bool force_dup
,
1014 BDRVRawState
*s
= bs
->opaque
;
1017 bool has_writers
= perm
&
1018 (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_RESIZE
);
1019 int fcntl_flags
= O_APPEND
| O_NONBLOCK
;
1021 fcntl_flags
|= O_NOATIME
;
1025 if (s
->type
== FTYPE_CD
) {
1026 *open_flags
|= O_NONBLOCK
;
1029 raw_parse_flags(flags
, open_flags
, has_writers
);
1032 /* Not all operating systems have O_ASYNC, and those that don't
1033 * will not let us track the state into rs->open_flags (typically
1034 * you achieve the same effect with an ioctl, for example I_SETSIG
1035 * on Solaris). But we do not use O_ASYNC, so that's fine.
1037 assert((s
->open_flags
& O_ASYNC
) == 0);
1040 if (!force_dup
&& *open_flags
== s
->open_flags
) {
1041 /* We're lucky, the existing fd is fine */
1045 if ((*open_flags
& ~fcntl_flags
) == (s
->open_flags
& ~fcntl_flags
)) {
1046 /* dup the original fd */
1047 fd
= qemu_dup(s
->fd
);
1049 ret
= fcntl_setfl(fd
, *open_flags
);
1057 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
1059 const char *normalized_filename
= bs
->filename
;
1060 ret
= raw_normalize_devicepath(&normalized_filename
, errp
);
1062 fd
= qemu_open(normalized_filename
, *open_flags
, errp
);
1069 if (fd
!= -1 && (*open_flags
& O_RDWR
)) {
1070 ret
= check_hdev_writable(fd
);
1073 error_setg_errno(errp
, -ret
, "The device is not writable");
1081 static int raw_reopen_prepare(BDRVReopenState
*state
,
1082 BlockReopenQueue
*queue
, Error
**errp
)
1085 BDRVRawReopenState
*rs
;
1089 assert(state
!= NULL
);
1090 assert(state
->bs
!= NULL
);
1092 s
= state
->bs
->opaque
;
1094 state
->opaque
= g_new0(BDRVRawReopenState
, 1);
1097 /* Handle options changes */
1098 opts
= qemu_opts_create(&raw_runtime_opts
, NULL
, 0, &error_abort
);
1099 if (!qemu_opts_absorb_qdict(opts
, state
->options
, errp
)) {
1104 rs
->drop_cache
= qemu_opt_get_bool_del(opts
, "drop-cache", true);
1105 rs
->check_cache_dropped
=
1106 qemu_opt_get_bool_del(opts
, "x-check-cache-dropped", false);
1108 /* This driver's reopen function doesn't currently allow changing
1109 * other options, so let's put them back in the original QDict and
1110 * bdrv_reopen_prepare() will detect changes and complain. */
1111 qemu_opts_to_qdict(opts
, state
->options
);
1114 * As part of reopen prepare we also want to create new fd by
1115 * raw_reconfigure_getfd(). But it wants updated "perm", when in
1116 * bdrv_reopen_multiple() .bdrv_reopen_prepare() callback called prior to
1117 * permission update. Happily, permission update is always a part (a seprate
1118 * stage) of bdrv_reopen_multiple() so we can rely on this fact and
1119 * reconfigure fd in raw_check_perm().
1122 s
->reopen_state
= state
;
1126 qemu_opts_del(opts
);
1130 static void raw_reopen_commit(BDRVReopenState
*state
)
1132 BDRVRawReopenState
*rs
= state
->opaque
;
1133 BDRVRawState
*s
= state
->bs
->opaque
;
1135 s
->drop_cache
= rs
->drop_cache
;
1136 s
->check_cache_dropped
= rs
->check_cache_dropped
;
1137 s
->open_flags
= rs
->open_flags
;
1138 g_free(state
->opaque
);
1139 state
->opaque
= NULL
;
1141 assert(s
->reopen_state
== state
);
1142 s
->reopen_state
= NULL
;
1146 static void raw_reopen_abort(BDRVReopenState
*state
)
1148 BDRVRawReopenState
*rs
= state
->opaque
;
1149 BDRVRawState
*s
= state
->bs
->opaque
;
1151 /* nothing to do if NULL, we didn't get far enough */
1156 g_free(state
->opaque
);
1157 state
->opaque
= NULL
;
1159 assert(s
->reopen_state
== state
);
1160 s
->reopen_state
= NULL
;
1163 static int hdev_get_max_hw_transfer(int fd
, struct stat
*st
)
1166 if (S_ISBLK(st
->st_mode
)) {
1167 unsigned short max_sectors
= 0;
1168 if (ioctl(fd
, BLKSECTGET
, &max_sectors
) == 0) {
1169 return max_sectors
* 512;
1173 if (ioctl(fd
, BLKSECTGET
, &max_bytes
) == 0) {
1183 static int hdev_get_max_segments(int fd
, struct stat
*st
)
1188 char *sysfspath
= NULL
;
1193 if (S_ISCHR(st
->st_mode
)) {
1194 if (ioctl(fd
, SG_GET_SG_TABLESIZE
, &ret
) == 0) {
1200 if (!S_ISBLK(st
->st_mode
)) {
1204 sysfspath
= g_strdup_printf("/sys/dev/block/%u:%u/queue/max_segments",
1205 major(st
->st_rdev
), minor(st
->st_rdev
));
1206 sysfd
= open(sysfspath
, O_RDONLY
);
1212 ret
= read(sysfd
, buf
, sizeof(buf
) - 1);
1213 } while (ret
== -1 && errno
== EINTR
);
1217 } else if (ret
== 0) {
1222 /* The file is ended with '\n', pass 'end' to accept that. */
1223 ret
= qemu_strtol(buf
, &end
, 10, &max_segments
);
1224 if (ret
== 0 && end
&& *end
== '\n') {
1239 static void raw_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1241 BDRVRawState
*s
= bs
->opaque
;
1244 raw_probe_alignment(bs
, s
->fd
, errp
);
1245 bs
->bl
.min_mem_alignment
= s
->buf_align
;
1246 bs
->bl
.opt_mem_alignment
= MAX(s
->buf_align
, qemu_real_host_page_size
);
1249 * Maximum transfers are best effort, so it is okay to ignore any
1250 * errors. That said, based on the man page errors in fstat would be
1251 * very much unexpected; the only possible case seems to be ENOMEM.
1253 if (fstat(s
->fd
, &st
)) {
1257 if (bs
->sg
|| S_ISBLK(st
.st_mode
)) {
1258 int ret
= hdev_get_max_hw_transfer(s
->fd
, &st
);
1260 if (ret
> 0 && ret
<= BDRV_REQUEST_MAX_BYTES
) {
1261 bs
->bl
.max_hw_transfer
= ret
;
1264 ret
= hdev_get_max_segments(s
->fd
, &st
);
1266 bs
->bl
.max_iov
= ret
;
1271 static int check_for_dasd(int fd
)
1274 struct dasd_information2_t info
= {0};
1276 return ioctl(fd
, BIODASDINFO2
, &info
);
1283 * Try to get @bs's logical and physical block size.
1284 * On success, store them in @bsz and return zero.
1285 * On failure, return negative errno.
1287 static int hdev_probe_blocksizes(BlockDriverState
*bs
, BlockSizes
*bsz
)
1289 BDRVRawState
*s
= bs
->opaque
;
1292 /* If DASD, get blocksizes */
1293 if (check_for_dasd(s
->fd
) < 0) {
1296 ret
= probe_logical_blocksize(s
->fd
, &bsz
->log
);
1300 return probe_physical_blocksize(s
->fd
, &bsz
->phys
);
1304 * Try to get @bs's geometry: cyls, heads, sectors.
1305 * On success, store them in @geo and return 0.
1306 * On failure return -errno.
1307 * (Allows block driver to assign default geometry values that guest sees)
1310 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
1312 BDRVRawState
*s
= bs
->opaque
;
1313 struct hd_geometry ioctl_geo
= {0};
1315 /* If DASD, get its geometry */
1316 if (check_for_dasd(s
->fd
) < 0) {
1319 if (ioctl(s
->fd
, HDIO_GETGEO
, &ioctl_geo
) < 0) {
1322 /* HDIO_GETGEO may return success even though geo contains zeros
1323 (e.g. certain multipath setups) */
1324 if (!ioctl_geo
.heads
|| !ioctl_geo
.sectors
|| !ioctl_geo
.cylinders
) {
1327 /* Do not return a geometry for partition */
1328 if (ioctl_geo
.start
!= 0) {
1331 geo
->heads
= ioctl_geo
.heads
;
1332 geo
->sectors
= ioctl_geo
.sectors
;
1333 geo
->cylinders
= ioctl_geo
.cylinders
;
1337 #else /* __linux__ */
1338 static int hdev_probe_geometry(BlockDriverState
*bs
, HDGeometry
*geo
)
1344 #if defined(__linux__)
1345 static int handle_aiocb_ioctl(void *opaque
)
1347 RawPosixAIOData
*aiocb
= opaque
;
1351 ret
= ioctl(aiocb
->aio_fildes
, aiocb
->ioctl
.cmd
, aiocb
->ioctl
.buf
);
1352 } while (ret
== -1 && errno
== EINTR
);
1361 static int handle_aiocb_flush(void *opaque
)
1363 RawPosixAIOData
*aiocb
= opaque
;
1364 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1367 if (s
->page_cache_inconsistent
) {
1368 return -s
->page_cache_inconsistent
;
1371 ret
= qemu_fdatasync(aiocb
->aio_fildes
);
1373 trace_file_flush_fdatasync_failed(errno
);
1375 /* There is no clear definition of the semantics of a failing fsync(),
1376 * so we may have to assume the worst. The sad truth is that this
1377 * assumption is correct for Linux. Some pages are now probably marked
1378 * clean in the page cache even though they are inconsistent with the
1379 * on-disk contents. The next fdatasync() call would succeed, but no
1380 * further writeback attempt will be made. We can't get back to a state
1381 * in which we know what is on disk (we would have to rewrite
1382 * everything that was touched since the last fdatasync() at least), so
1383 * make bdrv_flush() fail permanently. Given that the behaviour isn't
1384 * really defined, I have little hope that other OSes are doing better.
1386 * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1388 if ((s
->open_flags
& O_DIRECT
) == 0) {
1389 s
->page_cache_inconsistent
= errno
;
1396 #ifdef CONFIG_PREADV
1398 static bool preadv_present
= true;
1401 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1403 return preadv(fd
, iov
, nr_iov
, offset
);
1407 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1409 return pwritev(fd
, iov
, nr_iov
, offset
);
1414 static bool preadv_present
= false;
1417 qemu_preadv(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1423 qemu_pwritev(int fd
, const struct iovec
*iov
, int nr_iov
, off_t offset
)
1430 static ssize_t
handle_aiocb_rw_vector(RawPosixAIOData
*aiocb
)
1435 if (aiocb
->aio_type
& QEMU_AIO_WRITE
)
1436 len
= qemu_pwritev(aiocb
->aio_fildes
,
1441 len
= qemu_preadv(aiocb
->aio_fildes
,
1445 } while (len
== -1 && errno
== EINTR
);
1454 * Read/writes the data to/from a given linear buffer.
1456 * Returns the number of bytes handles or -errno in case of an error. Short
1457 * reads are only returned if the end of the file is reached.
1459 static ssize_t
handle_aiocb_rw_linear(RawPosixAIOData
*aiocb
, char *buf
)
1464 while (offset
< aiocb
->aio_nbytes
) {
1465 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1466 len
= pwrite(aiocb
->aio_fildes
,
1467 (const char *)buf
+ offset
,
1468 aiocb
->aio_nbytes
- offset
,
1469 aiocb
->aio_offset
+ offset
);
1471 len
= pread(aiocb
->aio_fildes
,
1473 aiocb
->aio_nbytes
- offset
,
1474 aiocb
->aio_offset
+ offset
);
1476 if (len
== -1 && errno
== EINTR
) {
1478 } else if (len
== -1 && errno
== EINVAL
&&
1479 (aiocb
->bs
->open_flags
& BDRV_O_NOCACHE
) &&
1480 !(aiocb
->aio_type
& QEMU_AIO_WRITE
) &&
1482 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1483 * after a short read. Assume that O_DIRECT short reads only occur
1484 * at EOF. Therefore this is a short read, not an I/O error.
1487 } else if (len
== -1) {
1490 } else if (len
== 0) {
1499 static int handle_aiocb_rw(void *opaque
)
1501 RawPosixAIOData
*aiocb
= opaque
;
1505 if (!(aiocb
->aio_type
& QEMU_AIO_MISALIGNED
)) {
1507 * If there is just a single buffer, and it is properly aligned
1508 * we can just use plain pread/pwrite without any problems.
1510 if (aiocb
->io
.niov
== 1) {
1511 nbytes
= handle_aiocb_rw_linear(aiocb
, aiocb
->io
.iov
->iov_base
);
1515 * We have more than one iovec, and all are properly aligned.
1517 * Try preadv/pwritev first and fall back to linearizing the
1518 * buffer if it's not supported.
1520 if (preadv_present
) {
1521 nbytes
= handle_aiocb_rw_vector(aiocb
);
1522 if (nbytes
== aiocb
->aio_nbytes
||
1523 (nbytes
< 0 && nbytes
!= -ENOSYS
)) {
1526 preadv_present
= false;
1530 * XXX(hch): short read/write. no easy way to handle the reminder
1531 * using these interfaces. For now retry using plain
1537 * Ok, we have to do it the hard way, copy all segments into
1538 * a single aligned buffer.
1540 buf
= qemu_try_blockalign(aiocb
->bs
, aiocb
->aio_nbytes
);
1546 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1550 for (i
= 0; i
< aiocb
->io
.niov
; ++i
) {
1551 memcpy(p
, aiocb
->io
.iov
[i
].iov_base
, aiocb
->io
.iov
[i
].iov_len
);
1552 p
+= aiocb
->io
.iov
[i
].iov_len
;
1554 assert(p
- buf
== aiocb
->aio_nbytes
);
1557 nbytes
= handle_aiocb_rw_linear(aiocb
, buf
);
1558 if (!(aiocb
->aio_type
& QEMU_AIO_WRITE
)) {
1560 size_t count
= aiocb
->aio_nbytes
, copy
;
1563 for (i
= 0; i
< aiocb
->io
.niov
&& count
; ++i
) {
1565 if (copy
> aiocb
->io
.iov
[i
].iov_len
) {
1566 copy
= aiocb
->io
.iov
[i
].iov_len
;
1568 memcpy(aiocb
->io
.iov
[i
].iov_base
, p
, copy
);
1569 assert(count
>= copy
);
1578 if (nbytes
== aiocb
->aio_nbytes
) {
1580 } else if (nbytes
>= 0 && nbytes
< aiocb
->aio_nbytes
) {
1581 if (aiocb
->aio_type
& QEMU_AIO_WRITE
) {
1584 iov_memset(aiocb
->io
.iov
, aiocb
->io
.niov
, nbytes
,
1585 0, aiocb
->aio_nbytes
- nbytes
);
1594 static int translate_err(int err
)
1596 if (err
== -ENODEV
|| err
== -ENOSYS
|| err
== -EOPNOTSUPP
||
1603 #ifdef CONFIG_FALLOCATE
1604 static int do_fallocate(int fd
, int mode
, off_t offset
, off_t len
)
1607 if (fallocate(fd
, mode
, offset
, len
) == 0) {
1610 } while (errno
== EINTR
);
1611 return translate_err(-errno
);
1615 static ssize_t
handle_aiocb_write_zeroes_block(RawPosixAIOData
*aiocb
)
1618 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1620 if (!s
->has_write_zeroes
) {
1625 /* The BLKZEROOUT implementation in the kernel doesn't set
1626 * BLKDEV_ZERO_NOFALLBACK, so we can't call this if we have to avoid slow
1628 if (!(aiocb
->aio_type
& QEMU_AIO_NO_FALLBACK
)) {
1630 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1631 if (ioctl(aiocb
->aio_fildes
, BLKZEROOUT
, range
) == 0) {
1634 } while (errno
== EINTR
);
1636 ret
= translate_err(-errno
);
1637 if (ret
== -ENOTSUP
) {
1638 s
->has_write_zeroes
= false;
1646 static int handle_aiocb_write_zeroes(void *opaque
)
1648 RawPosixAIOData
*aiocb
= opaque
;
1649 #ifdef CONFIG_FALLOCATE
1650 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1654 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1655 return handle_aiocb_write_zeroes_block(aiocb
);
1658 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1659 if (s
->has_write_zeroes
) {
1660 int ret
= do_fallocate(s
->fd
, FALLOC_FL_ZERO_RANGE
,
1661 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1662 if (ret
== -ENOTSUP
) {
1663 s
->has_write_zeroes
= false;
1664 } else if (ret
== 0 || ret
!= -EINVAL
) {
1668 * Note: Some file systems do not like unaligned byte ranges, and
1669 * return EINVAL in such a case, though they should not do it according
1670 * to the man-page of fallocate(). Thus we simply ignore this return
1671 * value and try the other fallbacks instead.
1676 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1677 if (s
->has_discard
&& s
->has_fallocate
) {
1678 int ret
= do_fallocate(s
->fd
,
1679 FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1680 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1682 ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1683 if (ret
== 0 || ret
!= -ENOTSUP
) {
1686 s
->has_fallocate
= false;
1687 } else if (ret
== -EINVAL
) {
1689 * Some file systems like older versions of GPFS do not like un-
1690 * aligned byte ranges, and return EINVAL in such a case, though
1691 * they should not do it according to the man-page of fallocate().
1692 * Warn about the bad filesystem and try the final fallback instead.
1694 warn_report_once("Your file system is misbehaving: "
1695 "fallocate(FALLOC_FL_PUNCH_HOLE) returned EINVAL. "
1696 "Please report this bug to your file sytem "
1698 } else if (ret
!= -ENOTSUP
) {
1701 s
->has_discard
= false;
1706 #ifdef CONFIG_FALLOCATE
1707 /* Last resort: we are trying to extend the file with zeroed data. This
1708 * can be done via fallocate(fd, 0) */
1709 len
= bdrv_getlength(aiocb
->bs
);
1710 if (s
->has_fallocate
&& len
>= 0 && aiocb
->aio_offset
>= len
) {
1711 int ret
= do_fallocate(s
->fd
, 0, aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1712 if (ret
== 0 || ret
!= -ENOTSUP
) {
1715 s
->has_fallocate
= false;
1722 static int handle_aiocb_write_zeroes_unmap(void *opaque
)
1724 RawPosixAIOData
*aiocb
= opaque
;
1725 BDRVRawState
*s G_GNUC_UNUSED
= aiocb
->bs
->opaque
;
1727 /* First try to write zeros and unmap at the same time */
1729 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1730 int ret
= do_fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1731 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1742 /* If we couldn't manage to unmap while guaranteed that the area reads as
1743 * all-zero afterwards, just write zeroes without unmapping */
1744 return handle_aiocb_write_zeroes(aiocb
);
1747 #ifndef HAVE_COPY_FILE_RANGE
1748 static off_t
copy_file_range(int in_fd
, off_t
*in_off
, int out_fd
,
1749 off_t
*out_off
, size_t len
, unsigned int flags
)
1751 #ifdef __NR_copy_file_range
1752 return syscall(__NR_copy_file_range
, in_fd
, in_off
, out_fd
,
1753 out_off
, len
, flags
);
1761 static int handle_aiocb_copy_range(void *opaque
)
1763 RawPosixAIOData
*aiocb
= opaque
;
1764 uint64_t bytes
= aiocb
->aio_nbytes
;
1765 off_t in_off
= aiocb
->aio_offset
;
1766 off_t out_off
= aiocb
->copy_range
.aio_offset2
;
1769 ssize_t ret
= copy_file_range(aiocb
->aio_fildes
, &in_off
,
1770 aiocb
->copy_range
.aio_fd2
, &out_off
,
1772 trace_file_copy_file_range(aiocb
->bs
, aiocb
->aio_fildes
, in_off
,
1773 aiocb
->copy_range
.aio_fd2
, out_off
, bytes
,
1776 /* No progress (e.g. when beyond EOF), let the caller fall back to
1795 static int handle_aiocb_discard(void *opaque
)
1797 RawPosixAIOData
*aiocb
= opaque
;
1798 int ret
= -EOPNOTSUPP
;
1799 BDRVRawState
*s
= aiocb
->bs
->opaque
;
1801 if (!s
->has_discard
) {
1805 if (aiocb
->aio_type
& QEMU_AIO_BLKDEV
) {
1808 uint64_t range
[2] = { aiocb
->aio_offset
, aiocb
->aio_nbytes
};
1809 if (ioctl(aiocb
->aio_fildes
, BLKDISCARD
, range
) == 0) {
1812 } while (errno
== EINTR
);
1817 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1818 ret
= do_fallocate(s
->fd
, FALLOC_FL_PUNCH_HOLE
| FALLOC_FL_KEEP_SIZE
,
1819 aiocb
->aio_offset
, aiocb
->aio_nbytes
);
1823 ret
= translate_err(ret
);
1824 if (ret
== -ENOTSUP
) {
1825 s
->has_discard
= false;
1831 * Help alignment probing by allocating the first block.
1833 * When reading with direct I/O from unallocated area on Gluster backed by XFS,
1834 * reading succeeds regardless of request length. In this case we fallback to
1835 * safe alignment which is not optimal. Allocating the first block avoids this
1838 * fd may be opened with O_DIRECT, but we don't know the buffer alignment or
1839 * request alignment, so we use safe values.
1841 * Returns: 0 on success, -errno on failure. Since this is an optimization,
1842 * caller may ignore failures.
1844 static int allocate_first_block(int fd
, size_t max_size
)
1846 size_t write_size
= (max_size
< MAX_BLOCKSIZE
)
1849 size_t max_align
= MAX(MAX_BLOCKSIZE
, qemu_real_host_page_size
);
1854 buf
= qemu_memalign(max_align
, write_size
);
1855 memset(buf
, 0, write_size
);
1858 n
= pwrite(fd
, buf
, write_size
, 0);
1859 } while (n
== -1 && errno
== EINTR
);
1861 ret
= (n
== -1) ? -errno
: 0;
1867 static int handle_aiocb_truncate(void *opaque
)
1869 RawPosixAIOData
*aiocb
= opaque
;
1871 int64_t current_length
= 0;
1874 int fd
= aiocb
->aio_fildes
;
1875 int64_t offset
= aiocb
->aio_offset
;
1876 PreallocMode prealloc
= aiocb
->truncate
.prealloc
;
1877 Error
**errp
= aiocb
->truncate
.errp
;
1879 if (fstat(fd
, &st
) < 0) {
1881 error_setg_errno(errp
, -result
, "Could not stat file");
1885 current_length
= st
.st_size
;
1886 if (current_length
> offset
&& prealloc
!= PREALLOC_MODE_OFF
) {
1887 error_setg(errp
, "Cannot use preallocation for shrinking files");
1892 #ifdef CONFIG_POSIX_FALLOCATE
1893 case PREALLOC_MODE_FALLOC
:
1895 * Truncating before posix_fallocate() makes it about twice slower on
1896 * file systems that do not support fallocate(), trying to check if a
1897 * block is allocated before allocating it, so don't do that here.
1899 if (offset
!= current_length
) {
1900 result
= -posix_fallocate(fd
, current_length
,
1901 offset
- current_length
);
1903 /* posix_fallocate() doesn't set errno. */
1904 error_setg_errno(errp
, -result
,
1905 "Could not preallocate new data");
1906 } else if (current_length
== 0) {
1908 * posix_fallocate() uses fallocate() if the filesystem
1909 * supports it, or fallback to manually writing zeroes. If
1910 * fallocate() was used, unaligned reads from the fallocated
1911 * area in raw_probe_alignment() will succeed, hence we need to
1912 * allocate the first block.
1914 * Optimize future alignment probing; ignore failures.
1916 allocate_first_block(fd
, offset
);
1923 case PREALLOC_MODE_FULL
:
1925 int64_t num
= 0, left
= offset
- current_length
;
1929 * Knowing the final size from the beginning could allow the file
1930 * system driver to do less allocations and possibly avoid
1931 * fragmentation of the file.
1933 if (ftruncate(fd
, offset
) != 0) {
1935 error_setg_errno(errp
, -result
, "Could not resize file");
1939 buf
= g_malloc0(65536);
1941 seek_result
= lseek(fd
, current_length
, SEEK_SET
);
1942 if (seek_result
< 0) {
1944 error_setg_errno(errp
, -result
,
1945 "Failed to seek to the old end of file");
1950 num
= MIN(left
, 65536);
1951 result
= write(fd
, buf
, num
);
1953 if (errno
== EINTR
) {
1957 error_setg_errno(errp
, -result
,
1958 "Could not write zeros for preallocation");
1967 error_setg_errno(errp
, -result
,
1968 "Could not flush file to disk");
1974 case PREALLOC_MODE_OFF
:
1975 if (ftruncate(fd
, offset
) != 0) {
1977 error_setg_errno(errp
, -result
, "Could not resize file");
1978 } else if (current_length
== 0 && offset
> current_length
) {
1979 /* Optimize future alignment probing; ignore failures. */
1980 allocate_first_block(fd
, offset
);
1985 error_setg(errp
, "Unsupported preallocation mode: %s",
1986 PreallocMode_str(prealloc
));
1992 if (ftruncate(fd
, current_length
) < 0) {
1993 error_report("Failed to restore old file length: %s",
2002 static int coroutine_fn
raw_thread_pool_submit(BlockDriverState
*bs
,
2003 ThreadPoolFunc func
, void *arg
)
2005 /* @bs can be NULL, bdrv_get_aio_context() returns the main context then */
2006 ThreadPool
*pool
= aio_get_thread_pool(bdrv_get_aio_context(bs
));
2007 return thread_pool_submit_co(pool
, func
, arg
);
2010 static int coroutine_fn
raw_co_prw(BlockDriverState
*bs
, uint64_t offset
,
2011 uint64_t bytes
, QEMUIOVector
*qiov
, int type
)
2013 BDRVRawState
*s
= bs
->opaque
;
2014 RawPosixAIOData acb
;
2016 if (fd_open(bs
) < 0)
2020 * When using O_DIRECT, the request must be aligned to be able to use
2021 * either libaio or io_uring interface. If not fail back to regular thread
2022 * pool read/write code which emulates this for us if we
2023 * set QEMU_AIO_MISALIGNED.
2025 if (s
->needs_alignment
&& !bdrv_qiov_is_aligned(bs
, qiov
)) {
2026 type
|= QEMU_AIO_MISALIGNED
;
2027 #ifdef CONFIG_LINUX_IO_URING
2028 } else if (s
->use_linux_io_uring
) {
2029 LuringState
*aio
= aio_get_linux_io_uring(bdrv_get_aio_context(bs
));
2030 assert(qiov
->size
== bytes
);
2031 return luring_co_submit(bs
, aio
, s
->fd
, offset
, qiov
, type
);
2033 #ifdef CONFIG_LINUX_AIO
2034 } else if (s
->use_linux_aio
) {
2035 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
2036 assert(qiov
->size
== bytes
);
2037 return laio_co_submit(bs
, aio
, s
->fd
, offset
, qiov
, type
);
2041 acb
= (RawPosixAIOData
) {
2043 .aio_fildes
= s
->fd
,
2045 .aio_offset
= offset
,
2046 .aio_nbytes
= bytes
,
2053 assert(qiov
->size
== bytes
);
2054 return raw_thread_pool_submit(bs
, handle_aiocb_rw
, &acb
);
2057 static int coroutine_fn
raw_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
2058 uint64_t bytes
, QEMUIOVector
*qiov
,
2061 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_READ
);
2064 static int coroutine_fn
raw_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
2065 uint64_t bytes
, QEMUIOVector
*qiov
,
2069 return raw_co_prw(bs
, offset
, bytes
, qiov
, QEMU_AIO_WRITE
);
2072 static void raw_aio_plug(BlockDriverState
*bs
)
2074 BDRVRawState
__attribute__((unused
)) *s
= bs
->opaque
;
2075 #ifdef CONFIG_LINUX_AIO
2076 if (s
->use_linux_aio
) {
2077 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
2078 laio_io_plug(bs
, aio
);
2081 #ifdef CONFIG_LINUX_IO_URING
2082 if (s
->use_linux_io_uring
) {
2083 LuringState
*aio
= aio_get_linux_io_uring(bdrv_get_aio_context(bs
));
2084 luring_io_plug(bs
, aio
);
2089 static void raw_aio_unplug(BlockDriverState
*bs
)
2091 BDRVRawState
__attribute__((unused
)) *s
= bs
->opaque
;
2092 #ifdef CONFIG_LINUX_AIO
2093 if (s
->use_linux_aio
) {
2094 LinuxAioState
*aio
= aio_get_linux_aio(bdrv_get_aio_context(bs
));
2095 laio_io_unplug(bs
, aio
);
2098 #ifdef CONFIG_LINUX_IO_URING
2099 if (s
->use_linux_io_uring
) {
2100 LuringState
*aio
= aio_get_linux_io_uring(bdrv_get_aio_context(bs
));
2101 luring_io_unplug(bs
, aio
);
2106 static int raw_co_flush_to_disk(BlockDriverState
*bs
)
2108 BDRVRawState
*s
= bs
->opaque
;
2109 RawPosixAIOData acb
;
2117 acb
= (RawPosixAIOData
) {
2119 .aio_fildes
= s
->fd
,
2120 .aio_type
= QEMU_AIO_FLUSH
,
2123 #ifdef CONFIG_LINUX_IO_URING
2124 if (s
->use_linux_io_uring
) {
2125 LuringState
*aio
= aio_get_linux_io_uring(bdrv_get_aio_context(bs
));
2126 return luring_co_submit(bs
, aio
, s
->fd
, 0, NULL
, QEMU_AIO_FLUSH
);
2129 return raw_thread_pool_submit(bs
, handle_aiocb_flush
, &acb
);
2132 static void raw_aio_attach_aio_context(BlockDriverState
*bs
,
2133 AioContext
*new_context
)
2135 BDRVRawState
__attribute__((unused
)) *s
= bs
->opaque
;
2136 #ifdef CONFIG_LINUX_AIO
2137 if (s
->use_linux_aio
) {
2138 Error
*local_err
= NULL
;
2139 if (!aio_setup_linux_aio(new_context
, &local_err
)) {
2140 error_reportf_err(local_err
, "Unable to use native AIO, "
2141 "falling back to thread pool: ");
2142 s
->use_linux_aio
= false;
2146 #ifdef CONFIG_LINUX_IO_URING
2147 if (s
->use_linux_io_uring
) {
2148 Error
*local_err
= NULL
;
2149 if (!aio_setup_linux_io_uring(new_context
, &local_err
)) {
2150 error_reportf_err(local_err
, "Unable to use linux io_uring, "
2151 "falling back to thread pool: ");
2152 s
->use_linux_io_uring
= false;
2158 static void raw_close(BlockDriverState
*bs
)
2160 BDRVRawState
*s
= bs
->opaque
;
2169 * Truncates the given regular file @fd to @offset and, when growing, fills the
2170 * new space according to @prealloc.
2172 * Returns: 0 on success, -errno on failure.
2174 static int coroutine_fn
2175 raw_regular_truncate(BlockDriverState
*bs
, int fd
, int64_t offset
,
2176 PreallocMode prealloc
, Error
**errp
)
2178 RawPosixAIOData acb
;
2180 acb
= (RawPosixAIOData
) {
2183 .aio_type
= QEMU_AIO_TRUNCATE
,
2184 .aio_offset
= offset
,
2186 .prealloc
= prealloc
,
2191 return raw_thread_pool_submit(bs
, handle_aiocb_truncate
, &acb
);
2194 static int coroutine_fn
raw_co_truncate(BlockDriverState
*bs
, int64_t offset
,
2195 bool exact
, PreallocMode prealloc
,
2196 BdrvRequestFlags flags
, Error
**errp
)
2198 BDRVRawState
*s
= bs
->opaque
;
2202 if (fstat(s
->fd
, &st
)) {
2204 error_setg_errno(errp
, -ret
, "Failed to fstat() the file");
2208 if (S_ISREG(st
.st_mode
)) {
2209 /* Always resizes to the exact @offset */
2210 return raw_regular_truncate(bs
, s
->fd
, offset
, prealloc
, errp
);
2213 if (prealloc
!= PREALLOC_MODE_OFF
) {
2214 error_setg(errp
, "Preallocation mode '%s' unsupported for this "
2215 "non-regular file", PreallocMode_str(prealloc
));
2219 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
2220 int64_t cur_length
= raw_getlength(bs
);
2222 if (offset
!= cur_length
&& exact
) {
2223 error_setg(errp
, "Cannot resize device files");
2225 } else if (offset
> cur_length
) {
2226 error_setg(errp
, "Cannot grow device files");
2230 error_setg(errp
, "Resizing this file is not supported");
2238 static int64_t raw_getlength(BlockDriverState
*bs
)
2240 BDRVRawState
*s
= bs
->opaque
;
2246 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
2247 struct disklabel dl
;
2249 if (ioctl(fd
, DIOCGDINFO
, &dl
))
2251 return (uint64_t)dl
.d_secsize
*
2252 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
2256 #elif defined(__NetBSD__)
2257 static int64_t raw_getlength(BlockDriverState
*bs
)
2259 BDRVRawState
*s
= bs
->opaque
;
2265 if (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
)) {
2266 struct dkwedge_info dkw
;
2268 if (ioctl(fd
, DIOCGWEDGEINFO
, &dkw
) != -1) {
2269 return dkw
.dkw_size
* 512;
2271 struct disklabel dl
;
2273 if (ioctl(fd
, DIOCGDINFO
, &dl
))
2275 return (uint64_t)dl
.d_secsize
*
2276 dl
.d_partitions
[DISKPART(st
.st_rdev
)].p_size
;
2281 #elif defined(__sun__)
2282 static int64_t raw_getlength(BlockDriverState
*bs
)
2284 BDRVRawState
*s
= bs
->opaque
;
2285 struct dk_minfo minfo
;
2295 * Use the DKIOCGMEDIAINFO ioctl to read the size.
2297 ret
= ioctl(s
->fd
, DKIOCGMEDIAINFO
, &minfo
);
2299 return minfo
.dki_lbsize
* minfo
.dki_capacity
;
2303 * There are reports that lseek on some devices fails, but
2304 * irc discussion said that contingency on contingency was overkill.
2306 size
= lseek(s
->fd
, 0, SEEK_END
);
2312 #elif defined(CONFIG_BSD)
2313 static int64_t raw_getlength(BlockDriverState
*bs
)
2315 BDRVRawState
*s
= bs
->opaque
;
2319 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2328 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2331 if (!fstat(fd
, &sb
) && (S_IFCHR
& sb
.st_mode
)) {
2333 #ifdef DIOCGMEDIASIZE
2334 if (ioctl(fd
, DIOCGMEDIASIZE
, (off_t
*)&size
)) {
2341 if (ioctl(fd
, DIOCGPART
, &pi
) == 0) {
2342 size
= pi
.media_size
;
2346 #if defined(DKIOCGETBLOCKCOUNT) && defined(DKIOCGETBLOCKSIZE)
2348 uint64_t sectors
= 0;
2349 uint32_t sector_size
= 0;
2351 if (ioctl(fd
, DKIOCGETBLOCKCOUNT
, §ors
) == 0
2352 && ioctl(fd
, DKIOCGETBLOCKSIZE
, §or_size
) == 0) {
2353 size
= sectors
* sector_size
;
2358 size
= lseek(fd
, 0LL, SEEK_END
);
2363 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2366 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
2367 if (size
== 2048LL * (unsigned)-1)
2369 /* XXX no disc? maybe we need to reopen... */
2370 if (size
<= 0 && !reopened
&& cdrom_reopen(bs
) >= 0) {
2377 size
= lseek(fd
, 0, SEEK_END
);
2385 static int64_t raw_getlength(BlockDriverState
*bs
)
2387 BDRVRawState
*s
= bs
->opaque
;
2396 size
= lseek(s
->fd
, 0, SEEK_END
);
2404 static int64_t raw_get_allocated_file_size(BlockDriverState
*bs
)
2407 BDRVRawState
*s
= bs
->opaque
;
2409 if (fstat(s
->fd
, &st
) < 0) {
2412 return (int64_t)st
.st_blocks
* 512;
2415 static int coroutine_fn
2416 raw_co_create(BlockdevCreateOptions
*options
, Error
**errp
)
2418 BlockdevCreateOptionsFile
*file_opts
;
2419 Error
*local_err
= NULL
;
2421 uint64_t perm
, shared
;
2424 /* Validate options and set default values */
2425 assert(options
->driver
== BLOCKDEV_DRIVER_FILE
);
2426 file_opts
= &options
->u
.file
;
2428 if (!file_opts
->has_nocow
) {
2429 file_opts
->nocow
= false;
2431 if (!file_opts
->has_preallocation
) {
2432 file_opts
->preallocation
= PREALLOC_MODE_OFF
;
2434 if (!file_opts
->has_extent_size_hint
) {
2435 file_opts
->extent_size_hint
= 1 * MiB
;
2437 if (file_opts
->extent_size_hint
> UINT32_MAX
) {
2439 error_setg(errp
, "Extent size hint is too large");
2444 fd
= qemu_create(file_opts
->filename
, O_RDWR
| O_BINARY
, 0644, errp
);
2450 /* Take permissions: We want to discard everything, so we need
2451 * BLK_PERM_WRITE; and truncation to the desired size requires
2453 * On the other hand, we cannot share the RESIZE permission
2454 * because we promise that after this function, the file has the
2455 * size given in the options. If someone else were to resize it
2456 * concurrently, we could not guarantee that.
2457 * Note that after this function, we can no longer guarantee that
2458 * the file is not touched by a third party, so it may be resized
2460 perm
= BLK_PERM_WRITE
| BLK_PERM_RESIZE
;
2461 shared
= BLK_PERM_ALL
& ~BLK_PERM_RESIZE
;
2463 /* Step one: Take locks */
2464 result
= raw_apply_lock_bytes(NULL
, fd
, perm
, ~shared
, false, errp
);
2469 /* Step two: Check that nobody else has taken conflicting locks */
2470 result
= raw_check_lock_bytes(fd
, perm
, shared
, errp
);
2472 error_append_hint(errp
,
2473 "Is another process using the image [%s]?\n",
2474 file_opts
->filename
);
2478 /* Clear the file by truncating it to 0 */
2479 result
= raw_regular_truncate(NULL
, fd
, 0, PREALLOC_MODE_OFF
, errp
);
2484 if (file_opts
->nocow
) {
2486 /* Set NOCOW flag to solve performance issue on fs like btrfs.
2487 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2488 * will be ignored since any failure of this operation should not
2489 * block the left work.
2492 if (ioctl(fd
, FS_IOC_GETFLAGS
, &attr
) == 0) {
2493 attr
|= FS_NOCOW_FL
;
2494 ioctl(fd
, FS_IOC_SETFLAGS
, &attr
);
2498 #ifdef FS_IOC_FSSETXATTR
2500 * Try to set the extent size hint. Failure is not fatal, and a warning is
2501 * only printed if the option was explicitly specified.
2504 struct fsxattr attr
;
2505 result
= ioctl(fd
, FS_IOC_FSGETXATTR
, &attr
);
2507 attr
.fsx_xflags
|= FS_XFLAG_EXTSIZE
;
2508 attr
.fsx_extsize
= file_opts
->extent_size_hint
;
2509 result
= ioctl(fd
, FS_IOC_FSSETXATTR
, &attr
);
2511 if (result
< 0 && file_opts
->has_extent_size_hint
&&
2512 file_opts
->extent_size_hint
)
2514 warn_report("Failed to set extent size hint: %s",
2520 /* Resize and potentially preallocate the file to the desired
2522 result
= raw_regular_truncate(NULL
, fd
, file_opts
->size
,
2523 file_opts
->preallocation
, errp
);
2529 raw_apply_lock_bytes(NULL
, fd
, 0, 0, true, &local_err
);
2531 /* The above call should not fail, and if it does, that does
2532 * not mean the whole creation operation has failed. So
2533 * report it the user for their convenience, but do not report
2534 * it to the caller. */
2535 warn_report_err(local_err
);
2539 if (qemu_close(fd
) != 0 && result
== 0) {
2541 error_setg_errno(errp
, -result
, "Could not close the new file");
2547 static int coroutine_fn
raw_co_create_opts(BlockDriver
*drv
,
2548 const char *filename
,
2552 BlockdevCreateOptions options
;
2553 int64_t total_size
= 0;
2554 int64_t extent_size_hint
= 0;
2555 bool has_extent_size_hint
= false;
2557 PreallocMode prealloc
;
2559 Error
*local_err
= NULL
;
2561 /* Skip file: protocol prefix */
2562 strstart(filename
, "file:", &filename
);
2564 /* Read out options */
2565 total_size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2567 if (qemu_opt_get(opts
, BLOCK_OPT_EXTENT_SIZE_HINT
)) {
2568 has_extent_size_hint
= true;
2570 qemu_opt_get_size_del(opts
, BLOCK_OPT_EXTENT_SIZE_HINT
, -1);
2572 nocow
= qemu_opt_get_bool(opts
, BLOCK_OPT_NOCOW
, false);
2573 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
2574 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
2575 PREALLOC_MODE_OFF
, &local_err
);
2578 error_propagate(errp
, local_err
);
2582 options
= (BlockdevCreateOptions
) {
2583 .driver
= BLOCKDEV_DRIVER_FILE
,
2585 .filename
= (char *) filename
,
2587 .has_preallocation
= true,
2588 .preallocation
= prealloc
,
2591 .has_extent_size_hint
= has_extent_size_hint
,
2592 .extent_size_hint
= extent_size_hint
,
2595 return raw_co_create(&options
, errp
);
2598 static int coroutine_fn
raw_co_delete_file(BlockDriverState
*bs
,
2604 if (!(stat(bs
->filename
, &st
) == 0) || !S_ISREG(st
.st_mode
)) {
2605 error_setg_errno(errp
, ENOENT
, "%s is not a regular file",
2610 ret
= unlink(bs
->filename
);
2613 error_setg_errno(errp
, -ret
, "Error when deleting file %s",
2621 * Find allocation range in @bs around offset @start.
2622 * May change underlying file descriptor's file offset.
2623 * If @start is not in a hole, store @start in @data, and the
2624 * beginning of the next hole in @hole, and return 0.
2625 * If @start is in a non-trailing hole, store @start in @hole and the
2626 * beginning of the next non-hole in @data, and return 0.
2627 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
2628 * If we can't find out, return a negative errno other than -ENXIO.
2630 static int find_allocation(BlockDriverState
*bs
, off_t start
,
2631 off_t
*data
, off_t
*hole
)
2633 #if defined SEEK_HOLE && defined SEEK_DATA
2634 BDRVRawState
*s
= bs
->opaque
;
2639 * D1. offs == start: start is in data
2640 * D2. offs > start: start is in a hole, next data at offs
2641 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
2642 * or start is beyond EOF
2643 * If the latter happens, the file has been truncated behind
2644 * our back since we opened it. All bets are off then.
2645 * Treating like a trailing hole is simplest.
2646 * D4. offs < 0, errno != ENXIO: we learned nothing
2648 offs
= lseek(s
->fd
, start
, SEEK_DATA
);
2650 return -errno
; /* D3 or D4 */
2654 /* This is not a valid return by lseek(). We are safe to just return
2655 * -EIO in this case, and we'll treat it like D4. */
2660 /* D2: in hole, next data at offs */
2666 /* D1: in data, end not yet known */
2670 * H1. offs == start: start is in a hole
2671 * If this happens here, a hole has been dug behind our back
2672 * since the previous lseek().
2673 * H2. offs > start: either start is in data, next hole at offs,
2674 * or start is in trailing hole, EOF at offs
2675 * Linux treats trailing holes like any other hole: offs ==
2676 * start. Solaris seeks to EOF instead: offs > start (blech).
2677 * If that happens here, a hole has been dug behind our back
2678 * since the previous lseek().
2679 * H3. offs < 0, errno = ENXIO: start is beyond EOF
2680 * If this happens, the file has been truncated behind our
2681 * back since we opened it. Treat it like a trailing hole.
2682 * H4. offs < 0, errno != ENXIO: we learned nothing
2683 * Pretend we know nothing at all, i.e. "forget" about D1.
2685 offs
= lseek(s
->fd
, start
, SEEK_HOLE
);
2687 return -errno
; /* D1 and (H3 or H4) */
2691 /* This is not a valid return by lseek(). We are safe to just return
2692 * -EIO in this case, and we'll treat it like H4. */
2698 * D1 and H2: either in data, next hole at offs, or it was in
2699 * data but is now in a trailing hole. In the latter case,
2700 * all bets are off. Treating it as if it there was data all
2701 * the way to EOF is safe, so simply do that.
2716 * Returns the allocation status of the specified offset.
2718 * The block layer guarantees 'offset' and 'bytes' are within bounds.
2720 * 'pnum' is set to the number of bytes (including and immediately following
2721 * the specified offset) that are known to be in the same
2722 * allocated/unallocated state.
2724 * 'bytes' is the max value 'pnum' should be set to.
2726 static int coroutine_fn
raw_co_block_status(BlockDriverState
*bs
,
2729 int64_t bytes
, int64_t *pnum
,
2731 BlockDriverState
**file
)
2733 off_t data
= 0, hole
= 0;
2736 assert(QEMU_IS_ALIGNED(offset
| bytes
, bs
->bl
.request_alignment
));
2747 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
2750 ret
= find_allocation(bs
, offset
, &data
, &hole
);
2751 if (ret
== -ENXIO
) {
2754 ret
= BDRV_BLOCK_ZERO
;
2755 } else if (ret
< 0) {
2756 /* No info available, so pretend there are no holes */
2758 ret
= BDRV_BLOCK_DATA
;
2759 } else if (data
== offset
) {
2760 /* On a data extent, compute bytes to the end of the extent,
2761 * possibly including a partial sector at EOF. */
2762 *pnum
= MIN(bytes
, hole
- offset
);
2765 * We are not allowed to return partial sectors, though, so
2766 * round up if necessary.
2768 if (!QEMU_IS_ALIGNED(*pnum
, bs
->bl
.request_alignment
)) {
2769 int64_t file_length
= raw_getlength(bs
);
2770 if (file_length
> 0) {
2771 /* Ignore errors, this is just a safeguard */
2772 assert(hole
== file_length
);
2774 *pnum
= ROUND_UP(*pnum
, bs
->bl
.request_alignment
);
2777 ret
= BDRV_BLOCK_DATA
;
2779 /* On a hole, compute bytes to the beginning of the next extent. */
2780 assert(hole
== offset
);
2781 *pnum
= MIN(bytes
, data
- offset
);
2782 ret
= BDRV_BLOCK_ZERO
;
2786 return ret
| BDRV_BLOCK_OFFSET_VALID
;
2789 #if defined(__linux__)
2790 /* Verify that the file is not in the page cache */
2791 static void check_cache_dropped(BlockDriverState
*bs
, Error
**errp
)
2793 const size_t window_size
= 128 * 1024 * 1024;
2794 BDRVRawState
*s
= bs
->opaque
;
2795 void *window
= NULL
;
2802 /* mincore(2) page status information requires 1 byte per page */
2803 page_size
= sysconf(_SC_PAGESIZE
);
2804 vec
= g_malloc(DIV_ROUND_UP(window_size
, page_size
));
2806 end
= raw_getlength(bs
);
2808 for (offset
= 0; offset
< end
; offset
+= window_size
) {
2815 /* Unmap previous window if size has changed */
2816 new_length
= MIN(end
- offset
, window_size
);
2817 if (new_length
!= length
) {
2818 munmap(window
, length
);
2823 new_window
= mmap(window
, new_length
, PROT_NONE
, MAP_PRIVATE
,
2825 if (new_window
== MAP_FAILED
) {
2826 error_setg_errno(errp
, errno
, "mmap failed");
2830 window
= new_window
;
2831 length
= new_length
;
2833 ret
= mincore(window
, length
, vec
);
2835 error_setg_errno(errp
, errno
, "mincore failed");
2839 vec_end
= DIV_ROUND_UP(length
, page_size
);
2840 for (i
= 0; i
< vec_end
; i
++) {
2846 error_setg(errp
, "page cache still in use!");
2852 munmap(window
, length
);
2857 #endif /* __linux__ */
2859 static void coroutine_fn
raw_co_invalidate_cache(BlockDriverState
*bs
,
2862 BDRVRawState
*s
= bs
->opaque
;
2867 error_setg_errno(errp
, -ret
, "The file descriptor is not open");
2871 if (!s
->drop_cache
) {
2875 if (s
->open_flags
& O_DIRECT
) {
2876 return; /* No host kernel page cache */
2879 #if defined(__linux__)
2880 /* This sets the scene for the next syscall... */
2881 ret
= bdrv_co_flush(bs
);
2883 error_setg_errno(errp
, -ret
, "flush failed");
2887 /* Linux does not invalidate pages that are dirty, locked, or mmapped by a
2888 * process. These limitations are okay because we just fsynced the file,
2889 * we don't use mmap, and the file should not be in use by other processes.
2891 ret
= posix_fadvise(s
->fd
, 0, 0, POSIX_FADV_DONTNEED
);
2892 if (ret
!= 0) { /* the return value is a positive errno */
2893 error_setg_errno(errp
, ret
, "fadvise failed");
2897 if (s
->check_cache_dropped
) {
2898 check_cache_dropped(bs
, errp
);
2900 #else /* __linux__ */
2901 /* Do nothing. Live migration to a remote host with cache.direct=off is
2902 * unsupported on other host operating systems. Cache consistency issues
2903 * may occur but no error is reported here, partly because that's the
2904 * historical behavior and partly because it's hard to differentiate valid
2905 * configurations that should not cause errors.
2907 #endif /* !__linux__ */
2910 static void raw_account_discard(BDRVRawState
*s
, uint64_t nbytes
, int ret
)
2913 s
->stats
.discard_nb_failed
++;
2915 s
->stats
.discard_nb_ok
++;
2916 s
->stats
.discard_bytes_ok
+= nbytes
;
2920 static coroutine_fn
int
2921 raw_do_pdiscard(BlockDriverState
*bs
, int64_t offset
, int bytes
, bool blkdev
)
2923 BDRVRawState
*s
= bs
->opaque
;
2924 RawPosixAIOData acb
;
2927 acb
= (RawPosixAIOData
) {
2929 .aio_fildes
= s
->fd
,
2930 .aio_type
= QEMU_AIO_DISCARD
,
2931 .aio_offset
= offset
,
2932 .aio_nbytes
= bytes
,
2936 acb
.aio_type
|= QEMU_AIO_BLKDEV
;
2939 ret
= raw_thread_pool_submit(bs
, handle_aiocb_discard
, &acb
);
2940 raw_account_discard(s
, bytes
, ret
);
2944 static coroutine_fn
int
2945 raw_co_pdiscard(BlockDriverState
*bs
, int64_t offset
, int bytes
)
2947 return raw_do_pdiscard(bs
, offset
, bytes
, false);
2950 static int coroutine_fn
2951 raw_do_pwrite_zeroes(BlockDriverState
*bs
, int64_t offset
, int bytes
,
2952 BdrvRequestFlags flags
, bool blkdev
)
2954 BDRVRawState
*s
= bs
->opaque
;
2955 RawPosixAIOData acb
;
2956 ThreadPoolFunc
*handler
;
2958 #ifdef CONFIG_FALLOCATE
2959 if (offset
+ bytes
> bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
2960 BdrvTrackedRequest
*req
;
2963 * This is a workaround for a bug in the Linux XFS driver,
2964 * where writes submitted through the AIO interface will be
2965 * discarded if they happen beyond a concurrently running
2966 * fallocate() that increases the file length (i.e., both the
2967 * write and the fallocate() happen beyond the EOF).
2969 * To work around it, we extend the tracked request for this
2970 * zero write until INT64_MAX (effectively infinity), and mark
2971 * it as serializing.
2973 * We have to enable this workaround for all filesystems and
2974 * AIO modes (not just XFS with aio=native), because for
2975 * remote filesystems we do not know the host configuration.
2978 req
= bdrv_co_get_self_request(bs
);
2980 assert(req
->type
== BDRV_TRACKED_WRITE
);
2981 assert(req
->offset
<= offset
);
2982 assert(req
->offset
+ req
->bytes
>= offset
+ bytes
);
2984 req
->bytes
= BDRV_MAX_LENGTH
- req
->offset
;
2986 bdrv_check_request(req
->offset
, req
->bytes
, &error_abort
);
2988 bdrv_make_request_serialising(req
, bs
->bl
.request_alignment
);
2992 acb
= (RawPosixAIOData
) {
2994 .aio_fildes
= s
->fd
,
2995 .aio_type
= QEMU_AIO_WRITE_ZEROES
,
2996 .aio_offset
= offset
,
2997 .aio_nbytes
= bytes
,
3001 acb
.aio_type
|= QEMU_AIO_BLKDEV
;
3003 if (flags
& BDRV_REQ_NO_FALLBACK
) {
3004 acb
.aio_type
|= QEMU_AIO_NO_FALLBACK
;
3007 if (flags
& BDRV_REQ_MAY_UNMAP
) {
3008 acb
.aio_type
|= QEMU_AIO_DISCARD
;
3009 handler
= handle_aiocb_write_zeroes_unmap
;
3011 handler
= handle_aiocb_write_zeroes
;
3014 return raw_thread_pool_submit(bs
, handler
, &acb
);
3017 static int coroutine_fn
raw_co_pwrite_zeroes(
3018 BlockDriverState
*bs
, int64_t offset
,
3019 int bytes
, BdrvRequestFlags flags
)
3021 return raw_do_pwrite_zeroes(bs
, offset
, bytes
, flags
, false);
3024 static int raw_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
3029 static BlockStatsSpecificFile
get_blockstats_specific_file(BlockDriverState
*bs
)
3031 BDRVRawState
*s
= bs
->opaque
;
3032 return (BlockStatsSpecificFile
) {
3033 .discard_nb_ok
= s
->stats
.discard_nb_ok
,
3034 .discard_nb_failed
= s
->stats
.discard_nb_failed
,
3035 .discard_bytes_ok
= s
->stats
.discard_bytes_ok
,
3039 static BlockStatsSpecific
*raw_get_specific_stats(BlockDriverState
*bs
)
3041 BlockStatsSpecific
*stats
= g_new(BlockStatsSpecific
, 1);
3043 stats
->driver
= BLOCKDEV_DRIVER_FILE
;
3044 stats
->u
.file
= get_blockstats_specific_file(bs
);
3049 #if defined(HAVE_HOST_BLOCK_DEVICE)
3050 static BlockStatsSpecific
*hdev_get_specific_stats(BlockDriverState
*bs
)
3052 BlockStatsSpecific
*stats
= g_new(BlockStatsSpecific
, 1);
3054 stats
->driver
= BLOCKDEV_DRIVER_HOST_DEVICE
;
3055 stats
->u
.host_device
= get_blockstats_specific_file(bs
);
3059 #endif /* HAVE_HOST_BLOCK_DEVICE */
3061 static QemuOptsList raw_create_opts
= {
3062 .name
= "raw-create-opts",
3063 .head
= QTAILQ_HEAD_INITIALIZER(raw_create_opts
.head
),
3066 .name
= BLOCK_OPT_SIZE
,
3067 .type
= QEMU_OPT_SIZE
,
3068 .help
= "Virtual disk size"
3071 .name
= BLOCK_OPT_NOCOW
,
3072 .type
= QEMU_OPT_BOOL
,
3073 .help
= "Turn off copy-on-write (valid only on btrfs)"
3076 .name
= BLOCK_OPT_PREALLOC
,
3077 .type
= QEMU_OPT_STRING
,
3078 .help
= "Preallocation mode (allowed values: off"
3079 #ifdef CONFIG_POSIX_FALLOCATE
3085 .name
= BLOCK_OPT_EXTENT_SIZE_HINT
,
3086 .type
= QEMU_OPT_SIZE
,
3087 .help
= "Extent size hint for the image file, 0 to disable"
3089 { /* end of list */ }
3093 static int raw_check_perm(BlockDriverState
*bs
, uint64_t perm
, uint64_t shared
,
3096 BDRVRawState
*s
= bs
->opaque
;
3097 int input_flags
= s
->reopen_state
? s
->reopen_state
->flags
: bs
->open_flags
;
3101 /* We may need a new fd if auto-read-only switches the mode */
3102 ret
= raw_reconfigure_getfd(bs
, input_flags
, &open_flags
, perm
,
3106 } else if (ret
!= s
->fd
) {
3107 Error
*local_err
= NULL
;
3110 * Fail already check_perm() if we can't get a working O_DIRECT
3111 * alignment with the new fd.
3113 raw_probe_alignment(bs
, ret
, &local_err
);
3115 error_propagate(errp
, local_err
);
3119 s
->perm_change_fd
= ret
;
3120 s
->perm_change_flags
= open_flags
;
3123 /* Prepare permissions on old fd to avoid conflicts between old and new,
3124 * but keep everything locked that new will need. */
3125 ret
= raw_handle_perm_lock(bs
, RAW_PL_PREPARE
, perm
, shared
, errp
);
3130 /* Copy locks to the new fd */
3131 if (s
->perm_change_fd
&& s
->use_lock
) {
3132 ret
= raw_apply_lock_bytes(NULL
, s
->perm_change_fd
, perm
, ~shared
,
3135 raw_handle_perm_lock(bs
, RAW_PL_ABORT
, 0, 0, NULL
);
3142 if (s
->perm_change_fd
) {
3143 qemu_close(s
->perm_change_fd
);
3145 s
->perm_change_fd
= 0;
3149 static void raw_set_perm(BlockDriverState
*bs
, uint64_t perm
, uint64_t shared
)
3151 BDRVRawState
*s
= bs
->opaque
;
3153 /* For reopen, we have already switched to the new fd (.bdrv_set_perm is
3154 * called after .bdrv_reopen_commit) */
3155 if (s
->perm_change_fd
&& s
->fd
!= s
->perm_change_fd
) {
3157 s
->fd
= s
->perm_change_fd
;
3158 s
->open_flags
= s
->perm_change_flags
;
3160 s
->perm_change_fd
= 0;
3162 raw_handle_perm_lock(bs
, RAW_PL_COMMIT
, perm
, shared
, NULL
);
3164 s
->shared_perm
= shared
;
3167 static void raw_abort_perm_update(BlockDriverState
*bs
)
3169 BDRVRawState
*s
= bs
->opaque
;
3171 /* For reopen, .bdrv_reopen_abort is called afterwards and will close
3172 * the file descriptor. */
3173 if (s
->perm_change_fd
) {
3174 qemu_close(s
->perm_change_fd
);
3176 s
->perm_change_fd
= 0;
3178 raw_handle_perm_lock(bs
, RAW_PL_ABORT
, 0, 0, NULL
);
3181 static int coroutine_fn
raw_co_copy_range_from(
3182 BlockDriverState
*bs
, BdrvChild
*src
, uint64_t src_offset
,
3183 BdrvChild
*dst
, uint64_t dst_offset
, uint64_t bytes
,
3184 BdrvRequestFlags read_flags
, BdrvRequestFlags write_flags
)
3186 return bdrv_co_copy_range_to(src
, src_offset
, dst
, dst_offset
, bytes
,
3187 read_flags
, write_flags
);
3190 static int coroutine_fn
raw_co_copy_range_to(BlockDriverState
*bs
,
3192 uint64_t src_offset
,
3194 uint64_t dst_offset
,
3196 BdrvRequestFlags read_flags
,
3197 BdrvRequestFlags write_flags
)
3199 RawPosixAIOData acb
;
3200 BDRVRawState
*s
= bs
->opaque
;
3201 BDRVRawState
*src_s
;
3203 assert(dst
->bs
== bs
);
3204 if (src
->bs
->drv
->bdrv_co_copy_range_to
!= raw_co_copy_range_to
) {
3208 src_s
= src
->bs
->opaque
;
3209 if (fd_open(src
->bs
) < 0 || fd_open(dst
->bs
) < 0) {
3213 acb
= (RawPosixAIOData
) {
3215 .aio_type
= QEMU_AIO_COPY_RANGE
,
3216 .aio_fildes
= src_s
->fd
,
3217 .aio_offset
= src_offset
,
3218 .aio_nbytes
= bytes
,
3221 .aio_offset2
= dst_offset
,
3225 return raw_thread_pool_submit(bs
, handle_aiocb_copy_range
, &acb
);
3228 BlockDriver bdrv_file
= {
3229 .format_name
= "file",
3230 .protocol_name
= "file",
3231 .instance_size
= sizeof(BDRVRawState
),
3232 .bdrv_needs_filename
= true,
3233 .bdrv_probe
= NULL
, /* no probe for protocols */
3234 .bdrv_parse_filename
= raw_parse_filename
,
3235 .bdrv_file_open
= raw_open
,
3236 .bdrv_reopen_prepare
= raw_reopen_prepare
,
3237 .bdrv_reopen_commit
= raw_reopen_commit
,
3238 .bdrv_reopen_abort
= raw_reopen_abort
,
3239 .bdrv_close
= raw_close
,
3240 .bdrv_co_create
= raw_co_create
,
3241 .bdrv_co_create_opts
= raw_co_create_opts
,
3242 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
3243 .bdrv_co_block_status
= raw_co_block_status
,
3244 .bdrv_co_invalidate_cache
= raw_co_invalidate_cache
,
3245 .bdrv_co_pwrite_zeroes
= raw_co_pwrite_zeroes
,
3246 .bdrv_co_delete_file
= raw_co_delete_file
,
3248 .bdrv_co_preadv
= raw_co_preadv
,
3249 .bdrv_co_pwritev
= raw_co_pwritev
,
3250 .bdrv_co_flush_to_disk
= raw_co_flush_to_disk
,
3251 .bdrv_co_pdiscard
= raw_co_pdiscard
,
3252 .bdrv_co_copy_range_from
= raw_co_copy_range_from
,
3253 .bdrv_co_copy_range_to
= raw_co_copy_range_to
,
3254 .bdrv_refresh_limits
= raw_refresh_limits
,
3255 .bdrv_io_plug
= raw_aio_plug
,
3256 .bdrv_io_unplug
= raw_aio_unplug
,
3257 .bdrv_attach_aio_context
= raw_aio_attach_aio_context
,
3259 .bdrv_co_truncate
= raw_co_truncate
,
3260 .bdrv_getlength
= raw_getlength
,
3261 .bdrv_get_info
= raw_get_info
,
3262 .bdrv_get_allocated_file_size
3263 = raw_get_allocated_file_size
,
3264 .bdrv_get_specific_stats
= raw_get_specific_stats
,
3265 .bdrv_check_perm
= raw_check_perm
,
3266 .bdrv_set_perm
= raw_set_perm
,
3267 .bdrv_abort_perm_update
= raw_abort_perm_update
,
3268 .create_opts
= &raw_create_opts
,
3269 .mutable_opts
= mutable_opts
,
3272 /***********************************************/
3275 #if defined(HAVE_HOST_BLOCK_DEVICE)
3277 #if defined(__APPLE__) && defined(__MACH__)
3278 static kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
3279 CFIndex maxPathSize
, int flags
);
3280 static char *FindEjectableOpticalMedia(io_iterator_t
*mediaIterator
)
3282 kern_return_t kernResult
= KERN_FAILURE
;
3283 mach_port_t masterPort
;
3284 CFMutableDictionaryRef classesToMatch
;
3285 const char *matching_array
[] = {kIODVDMediaClass
, kIOCDMediaClass
};
3286 char *mediaType
= NULL
;
3288 kernResult
= IOMasterPort( MACH_PORT_NULL
, &masterPort
);
3289 if ( KERN_SUCCESS
!= kernResult
) {
3290 printf( "IOMasterPort returned %d\n", kernResult
);
3294 for (index
= 0; index
< ARRAY_SIZE(matching_array
); index
++) {
3295 classesToMatch
= IOServiceMatching(matching_array
[index
]);
3296 if (classesToMatch
== NULL
) {
3297 error_report("IOServiceMatching returned NULL for %s",
3298 matching_array
[index
]);
3301 CFDictionarySetValue(classesToMatch
, CFSTR(kIOMediaEjectableKey
),
3303 kernResult
= IOServiceGetMatchingServices(masterPort
, classesToMatch
,
3305 if (kernResult
!= KERN_SUCCESS
) {
3306 error_report("Note: IOServiceGetMatchingServices returned %d",
3311 /* If a match was found, leave the loop */
3312 if (*mediaIterator
!= 0) {
3313 trace_file_FindEjectableOpticalMedia(matching_array
[index
]);
3314 mediaType
= g_strdup(matching_array
[index
]);
3321 kern_return_t
GetBSDPath(io_iterator_t mediaIterator
, char *bsdPath
,
3322 CFIndex maxPathSize
, int flags
)
3324 io_object_t nextMedia
;
3325 kern_return_t kernResult
= KERN_FAILURE
;
3327 nextMedia
= IOIteratorNext( mediaIterator
);
3330 CFTypeRef bsdPathAsCFString
;
3331 bsdPathAsCFString
= IORegistryEntryCreateCFProperty( nextMedia
, CFSTR( kIOBSDNameKey
), kCFAllocatorDefault
, 0 );
3332 if ( bsdPathAsCFString
) {
3333 size_t devPathLength
;
3334 strcpy( bsdPath
, _PATH_DEV
);
3335 if (flags
& BDRV_O_NOCACHE
) {
3336 strcat(bsdPath
, "r");
3338 devPathLength
= strlen( bsdPath
);
3339 if ( CFStringGetCString( bsdPathAsCFString
, bsdPath
+ devPathLength
, maxPathSize
- devPathLength
, kCFStringEncodingASCII
) ) {
3340 kernResult
= KERN_SUCCESS
;
3342 CFRelease( bsdPathAsCFString
);
3344 IOObjectRelease( nextMedia
);
3350 /* Sets up a real cdrom for use in QEMU */
3351 static bool setup_cdrom(char *bsd_path
, Error
**errp
)
3353 int index
, num_of_test_partitions
= 2, fd
;
3354 char test_partition
[MAXPATHLEN
];
3355 bool partition_found
= false;
3357 /* look for a working partition */
3358 for (index
= 0; index
< num_of_test_partitions
; index
++) {
3359 snprintf(test_partition
, sizeof(test_partition
), "%ss%d", bsd_path
,
3361 fd
= qemu_open(test_partition
, O_RDONLY
| O_BINARY
| O_LARGEFILE
, NULL
);
3363 partition_found
= true;
3369 /* if a working partition on the device was not found */
3370 if (partition_found
== false) {
3371 error_setg(errp
, "Failed to find a working partition on disc");
3373 trace_file_setup_cdrom(test_partition
);
3374 pstrcpy(bsd_path
, MAXPATHLEN
, test_partition
);
3376 return partition_found
;
3379 /* Prints directions on mounting and unmounting a device */
3380 static void print_unmounting_directions(const char *file_name
)
3382 error_report("If device %s is mounted on the desktop, unmount"
3383 " it first before using it in QEMU", file_name
);
3384 error_report("Command to unmount device: diskutil unmountDisk %s",
3386 error_report("Command to mount device: diskutil mountDisk %s", file_name
);
3389 #endif /* defined(__APPLE__) && defined(__MACH__) */
3391 static int hdev_probe_device(const char *filename
)
3395 /* allow a dedicated CD-ROM driver to match with a higher priority */
3396 if (strstart(filename
, "/dev/cdrom", NULL
))
3399 if (stat(filename
, &st
) >= 0 &&
3400 (S_ISCHR(st
.st_mode
) || S_ISBLK(st
.st_mode
))) {
3407 static void hdev_parse_filename(const char *filename
, QDict
*options
,
3410 bdrv_parse_filename_strip_prefix(filename
, "host_device:", options
);
3413 static bool hdev_is_sg(BlockDriverState
*bs
)
3416 #if defined(__linux__)
3418 BDRVRawState
*s
= bs
->opaque
;
3420 struct sg_scsi_id scsiid
;
3424 if (stat(bs
->filename
, &st
) < 0 || !S_ISCHR(st
.st_mode
)) {
3428 ret
= ioctl(s
->fd
, SG_GET_VERSION_NUM
, &sg_version
);
3433 ret
= ioctl(s
->fd
, SG_GET_SCSI_ID
, &scsiid
);
3435 trace_file_hdev_is_sg(scsiid
.scsi_type
, sg_version
);
3444 static int hdev_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
3447 BDRVRawState
*s
= bs
->opaque
;
3450 #if defined(__APPLE__) && defined(__MACH__)
3452 * Caution: while qdict_get_str() is fine, getting non-string types
3453 * would require more care. When @options come from -blockdev or
3454 * blockdev_add, its members are typed according to the QAPI
3455 * schema, but when they come from -drive, they're all QString.
3457 const char *filename
= qdict_get_str(options
, "filename");
3458 char bsd_path
[MAXPATHLEN
] = "";
3459 bool error_occurred
= false;
3461 /* If using a real cdrom */
3462 if (strcmp(filename
, "/dev/cdrom") == 0) {
3463 char *mediaType
= NULL
;
3464 kern_return_t ret_val
;
3465 io_iterator_t mediaIterator
= 0;
3467 mediaType
= FindEjectableOpticalMedia(&mediaIterator
);
3468 if (mediaType
== NULL
) {
3469 error_setg(errp
, "Please make sure your CD/DVD is in the optical"
3471 error_occurred
= true;
3472 goto hdev_open_Mac_error
;
3475 ret_val
= GetBSDPath(mediaIterator
, bsd_path
, sizeof(bsd_path
), flags
);
3476 if (ret_val
!= KERN_SUCCESS
) {
3477 error_setg(errp
, "Could not get BSD path for optical drive");
3478 error_occurred
= true;
3479 goto hdev_open_Mac_error
;
3482 /* If a real optical drive was not found */
3483 if (bsd_path
[0] == '\0') {
3484 error_setg(errp
, "Failed to obtain bsd path for optical drive");
3485 error_occurred
= true;
3486 goto hdev_open_Mac_error
;
3489 /* If using a cdrom disc and finding a partition on the disc failed */
3490 if (strncmp(mediaType
, kIOCDMediaClass
, 9) == 0 &&
3491 setup_cdrom(bsd_path
, errp
) == false) {
3492 print_unmounting_directions(bsd_path
);
3493 error_occurred
= true;
3494 goto hdev_open_Mac_error
;
3497 qdict_put_str(options
, "filename", bsd_path
);
3499 hdev_open_Mac_error
:
3501 if (mediaIterator
) {
3502 IOObjectRelease(mediaIterator
);
3504 if (error_occurred
) {
3508 #endif /* defined(__APPLE__) && defined(__MACH__) */
3510 s
->type
= FTYPE_FILE
;
3512 ret
= raw_open_common(bs
, options
, flags
, 0, true, errp
);
3514 #if defined(__APPLE__) && defined(__MACH__)
3516 filename
= bsd_path
;
3518 /* if a physical device experienced an error while being opened */
3519 if (strncmp(filename
, "/dev/", 5) == 0) {
3520 print_unmounting_directions(filename
);
3522 #endif /* defined(__APPLE__) && defined(__MACH__) */
3526 /* Since this does ioctl the device must be already opened */
3527 bs
->sg
= hdev_is_sg(bs
);
3532 #if defined(__linux__)
3533 static int coroutine_fn
3534 hdev_co_ioctl(BlockDriverState
*bs
, unsigned long int req
, void *buf
)
3536 BDRVRawState
*s
= bs
->opaque
;
3537 RawPosixAIOData acb
;
3545 if (req
== SG_IO
&& s
->pr_mgr
) {
3546 struct sg_io_hdr
*io_hdr
= buf
;
3547 if (io_hdr
->cmdp
[0] == PERSISTENT_RESERVE_OUT
||
3548 io_hdr
->cmdp
[0] == PERSISTENT_RESERVE_IN
) {
3549 return pr_manager_execute(s
->pr_mgr
, bdrv_get_aio_context(bs
),
3554 acb
= (RawPosixAIOData
) {
3556 .aio_type
= QEMU_AIO_IOCTL
,
3557 .aio_fildes
= s
->fd
,
3565 return raw_thread_pool_submit(bs
, handle_aiocb_ioctl
, &acb
);
3569 static coroutine_fn
int
3570 hdev_co_pdiscard(BlockDriverState
*bs
, int64_t offset
, int bytes
)
3572 BDRVRawState
*s
= bs
->opaque
;
3577 raw_account_discard(s
, bytes
, ret
);
3580 return raw_do_pdiscard(bs
, offset
, bytes
, true);
3583 static coroutine_fn
int hdev_co_pwrite_zeroes(BlockDriverState
*bs
,
3584 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
3593 return raw_do_pwrite_zeroes(bs
, offset
, bytes
, flags
, true);
3596 static BlockDriver bdrv_host_device
= {
3597 .format_name
= "host_device",
3598 .protocol_name
= "host_device",
3599 .instance_size
= sizeof(BDRVRawState
),
3600 .bdrv_needs_filename
= true,
3601 .bdrv_probe_device
= hdev_probe_device
,
3602 .bdrv_parse_filename
= hdev_parse_filename
,
3603 .bdrv_file_open
= hdev_open
,
3604 .bdrv_close
= raw_close
,
3605 .bdrv_reopen_prepare
= raw_reopen_prepare
,
3606 .bdrv_reopen_commit
= raw_reopen_commit
,
3607 .bdrv_reopen_abort
= raw_reopen_abort
,
3608 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
3609 .create_opts
= &bdrv_create_opts_simple
,
3610 .mutable_opts
= mutable_opts
,
3611 .bdrv_co_invalidate_cache
= raw_co_invalidate_cache
,
3612 .bdrv_co_pwrite_zeroes
= hdev_co_pwrite_zeroes
,
3614 .bdrv_co_preadv
= raw_co_preadv
,
3615 .bdrv_co_pwritev
= raw_co_pwritev
,
3616 .bdrv_co_flush_to_disk
= raw_co_flush_to_disk
,
3617 .bdrv_co_pdiscard
= hdev_co_pdiscard
,
3618 .bdrv_co_copy_range_from
= raw_co_copy_range_from
,
3619 .bdrv_co_copy_range_to
= raw_co_copy_range_to
,
3620 .bdrv_refresh_limits
= raw_refresh_limits
,
3621 .bdrv_io_plug
= raw_aio_plug
,
3622 .bdrv_io_unplug
= raw_aio_unplug
,
3623 .bdrv_attach_aio_context
= raw_aio_attach_aio_context
,
3625 .bdrv_co_truncate
= raw_co_truncate
,
3626 .bdrv_getlength
= raw_getlength
,
3627 .bdrv_get_info
= raw_get_info
,
3628 .bdrv_get_allocated_file_size
3629 = raw_get_allocated_file_size
,
3630 .bdrv_get_specific_stats
= hdev_get_specific_stats
,
3631 .bdrv_check_perm
= raw_check_perm
,
3632 .bdrv_set_perm
= raw_set_perm
,
3633 .bdrv_abort_perm_update
= raw_abort_perm_update
,
3634 .bdrv_probe_blocksizes
= hdev_probe_blocksizes
,
3635 .bdrv_probe_geometry
= hdev_probe_geometry
,
3637 /* generic scsi device */
3639 .bdrv_co_ioctl
= hdev_co_ioctl
,
3643 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3644 static void cdrom_parse_filename(const char *filename
, QDict
*options
,
3647 bdrv_parse_filename_strip_prefix(filename
, "host_cdrom:", options
);
3652 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
3655 BDRVRawState
*s
= bs
->opaque
;
3659 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
3660 return raw_open_common(bs
, options
, flags
, O_NONBLOCK
, true, errp
);
3663 static int cdrom_probe_device(const char *filename
)
3669 fd
= qemu_open(filename
, O_RDONLY
| O_NONBLOCK
, NULL
);
3673 ret
= fstat(fd
, &st
);
3674 if (ret
== -1 || !S_ISBLK(st
.st_mode
)) {
3678 /* Attempt to detect via a CDROM specific ioctl */
3679 ret
= ioctl(fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
3689 static bool cdrom_is_inserted(BlockDriverState
*bs
)
3691 BDRVRawState
*s
= bs
->opaque
;
3694 ret
= ioctl(s
->fd
, CDROM_DRIVE_STATUS
, CDSL_CURRENT
);
3695 return ret
== CDS_DISC_OK
;
3698 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
3700 BDRVRawState
*s
= bs
->opaque
;
3703 if (ioctl(s
->fd
, CDROMEJECT
, NULL
) < 0)
3704 perror("CDROMEJECT");
3706 if (ioctl(s
->fd
, CDROMCLOSETRAY
, NULL
) < 0)
3707 perror("CDROMEJECT");
3711 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
3713 BDRVRawState
*s
= bs
->opaque
;
3715 if (ioctl(s
->fd
, CDROM_LOCKDOOR
, locked
) < 0) {
3717 * Note: an error can happen if the distribution automatically
3720 /* perror("CDROM_LOCKDOOR"); */
3724 static BlockDriver bdrv_host_cdrom
= {
3725 .format_name
= "host_cdrom",
3726 .protocol_name
= "host_cdrom",
3727 .instance_size
= sizeof(BDRVRawState
),
3728 .bdrv_needs_filename
= true,
3729 .bdrv_probe_device
= cdrom_probe_device
,
3730 .bdrv_parse_filename
= cdrom_parse_filename
,
3731 .bdrv_file_open
= cdrom_open
,
3732 .bdrv_close
= raw_close
,
3733 .bdrv_reopen_prepare
= raw_reopen_prepare
,
3734 .bdrv_reopen_commit
= raw_reopen_commit
,
3735 .bdrv_reopen_abort
= raw_reopen_abort
,
3736 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
3737 .create_opts
= &bdrv_create_opts_simple
,
3738 .mutable_opts
= mutable_opts
,
3739 .bdrv_co_invalidate_cache
= raw_co_invalidate_cache
,
3741 .bdrv_co_preadv
= raw_co_preadv
,
3742 .bdrv_co_pwritev
= raw_co_pwritev
,
3743 .bdrv_co_flush_to_disk
= raw_co_flush_to_disk
,
3744 .bdrv_refresh_limits
= raw_refresh_limits
,
3745 .bdrv_io_plug
= raw_aio_plug
,
3746 .bdrv_io_unplug
= raw_aio_unplug
,
3747 .bdrv_attach_aio_context
= raw_aio_attach_aio_context
,
3749 .bdrv_co_truncate
= raw_co_truncate
,
3750 .bdrv_getlength
= raw_getlength
,
3751 .has_variable_length
= true,
3752 .bdrv_get_allocated_file_size
3753 = raw_get_allocated_file_size
,
3755 /* removable device support */
3756 .bdrv_is_inserted
= cdrom_is_inserted
,
3757 .bdrv_eject
= cdrom_eject
,
3758 .bdrv_lock_medium
= cdrom_lock_medium
,
3760 /* generic scsi device */
3761 .bdrv_co_ioctl
= hdev_co_ioctl
,
3763 #endif /* __linux__ */
3765 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
3766 static int cdrom_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
3769 BDRVRawState
*s
= bs
->opaque
;
3774 ret
= raw_open_common(bs
, options
, flags
, 0, true, errp
);
3779 /* make sure the door isn't locked at this time */
3780 ioctl(s
->fd
, CDIOCALLOW
);
3784 static int cdrom_probe_device(const char *filename
)
3786 if (strstart(filename
, "/dev/cd", NULL
) ||
3787 strstart(filename
, "/dev/acd", NULL
))
3792 static int cdrom_reopen(BlockDriverState
*bs
)
3794 BDRVRawState
*s
= bs
->opaque
;
3798 * Force reread of possibly changed/newly loaded disc,
3799 * FreeBSD seems to not notice sometimes...
3803 fd
= qemu_open(bs
->filename
, s
->open_flags
, NULL
);
3810 /* make sure the door isn't locked at this time */
3811 ioctl(s
->fd
, CDIOCALLOW
);
3815 static bool cdrom_is_inserted(BlockDriverState
*bs
)
3817 return raw_getlength(bs
) > 0;
3820 static void cdrom_eject(BlockDriverState
*bs
, bool eject_flag
)
3822 BDRVRawState
*s
= bs
->opaque
;
3827 (void) ioctl(s
->fd
, CDIOCALLOW
);
3830 if (ioctl(s
->fd
, CDIOCEJECT
) < 0)
3831 perror("CDIOCEJECT");
3833 if (ioctl(s
->fd
, CDIOCCLOSE
) < 0)
3834 perror("CDIOCCLOSE");
3840 static void cdrom_lock_medium(BlockDriverState
*bs
, bool locked
)
3842 BDRVRawState
*s
= bs
->opaque
;
3846 if (ioctl(s
->fd
, (locked
? CDIOCPREVENT
: CDIOCALLOW
)) < 0) {
3848 * Note: an error can happen if the distribution automatically
3851 /* perror("CDROM_LOCKDOOR"); */
3855 static BlockDriver bdrv_host_cdrom
= {
3856 .format_name
= "host_cdrom",
3857 .protocol_name
= "host_cdrom",
3858 .instance_size
= sizeof(BDRVRawState
),
3859 .bdrv_needs_filename
= true,
3860 .bdrv_probe_device
= cdrom_probe_device
,
3861 .bdrv_parse_filename
= cdrom_parse_filename
,
3862 .bdrv_file_open
= cdrom_open
,
3863 .bdrv_close
= raw_close
,
3864 .bdrv_reopen_prepare
= raw_reopen_prepare
,
3865 .bdrv_reopen_commit
= raw_reopen_commit
,
3866 .bdrv_reopen_abort
= raw_reopen_abort
,
3867 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
3868 .create_opts
= &bdrv_create_opts_simple
,
3869 .mutable_opts
= mutable_opts
,
3871 .bdrv_co_preadv
= raw_co_preadv
,
3872 .bdrv_co_pwritev
= raw_co_pwritev
,
3873 .bdrv_co_flush_to_disk
= raw_co_flush_to_disk
,
3874 .bdrv_refresh_limits
= raw_refresh_limits
,
3875 .bdrv_io_plug
= raw_aio_plug
,
3876 .bdrv_io_unplug
= raw_aio_unplug
,
3877 .bdrv_attach_aio_context
= raw_aio_attach_aio_context
,
3879 .bdrv_co_truncate
= raw_co_truncate
,
3880 .bdrv_getlength
= raw_getlength
,
3881 .has_variable_length
= true,
3882 .bdrv_get_allocated_file_size
3883 = raw_get_allocated_file_size
,
3885 /* removable device support */
3886 .bdrv_is_inserted
= cdrom_is_inserted
,
3887 .bdrv_eject
= cdrom_eject
,
3888 .bdrv_lock_medium
= cdrom_lock_medium
,
3890 #endif /* __FreeBSD__ */
3892 #endif /* HAVE_HOST_BLOCK_DEVICE */
3894 static void bdrv_file_init(void)
3897 * Register all the drivers. Note that order is important, the driver
3898 * registered last will get probed first.
3900 bdrv_register(&bdrv_file
);
3901 #if defined(HAVE_HOST_BLOCK_DEVICE)
3902 bdrv_register(&bdrv_host_device
);
3904 bdrv_register(&bdrv_host_cdrom
);
3906 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
3907 bdrv_register(&bdrv_host_cdrom
);
3909 #endif /* HAVE_HOST_BLOCK_DEVICE */
3912 block_init(bdrv_file_init
);