Merge tag 'v9.0.0-rc3'
[qemu/ar7.git] / block / file-posix.c
blobb28192b8b6a38a0e349628c905c22c8cc15598f4
1 /*
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
22 * THE SOFTWARE.
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"
35 #include "trace.h"
36 #include "block/thread-pool.h"
37 #include "qemu/iov.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)
48 #include <paths.h>
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) */
60 #endif
62 #ifdef __sun__
63 #define _POSIX_PTHREAD_SEMANTICS 1
64 #include <sys/dkio.h>
65 #endif
66 #ifdef __linux__
67 #include <sys/ioctl.h>
68 #include <sys/param.h>
69 #include <sys/syscall.h>
70 #include <sys/vfs.h>
71 #if defined(CONFIG_BLKZONED)
72 #include <linux/blkzoned.h>
73 #endif
74 #include <linux/cdrom.h>
75 #include <linux/fd.h>
76 #include <linux/fs.h>
77 #include <linux/hdreg.h>
78 #include <linux/magic.h>
79 #include <scsi/sg.h>
80 #ifdef __s390__
81 #include <asm/dasd.h>
82 #endif
83 #ifndef FS_NOCOW_FL
84 #define FS_NOCOW_FL 0x00800000 /* Do not cow file */
85 #endif
86 #endif
87 #if defined(CONFIG_FALLOCATE_PUNCH_HOLE) || defined(CONFIG_FALLOCATE_ZERO_RANGE)
88 #include <linux/falloc.h>
89 #endif
90 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
91 #include <sys/disk.h>
92 #include <sys/cdio.h>
93 #endif
95 #ifdef __OpenBSD__
96 #include <sys/ioctl.h>
97 #include <sys/disklabel.h>
98 #include <sys/dkio.h>
99 #endif
101 #ifdef __NetBSD__
102 #include <sys/ioctl.h>
103 #include <sys/disklabel.h>
104 #include <sys/dkio.h>
105 #include <sys/disk.h>
106 #endif
108 #ifdef __DragonFly__
109 #include <sys/ioctl.h>
110 #include <sys/diskslice.h>
111 #endif
113 /* OS X does not have O_DSYNC */
114 #ifndef O_DSYNC
115 #ifdef O_SYNC
116 #define O_DSYNC O_SYNC
117 #elif defined(O_FSYNC)
118 #define O_DSYNC O_FSYNC
119 #endif
120 #endif
122 /* Approximate O_DIRECT with O_DSYNC if O_DIRECT isn't available */
123 #ifndef O_DIRECT
124 #define O_DIRECT O_DSYNC
125 #endif
127 #define FTYPE_FILE 0
128 #define FTYPE_CD 1
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 {
138 int fd;
139 bool use_lock;
140 int type;
141 int open_flags;
142 size_t buf_align;
144 /* The current permissions. */
145 uint64_t perm;
146 uint64_t shared_perm;
148 /* The perms bits whose corresponding bytes are already locked in
149 * s->fd. */
150 uint64_t locked_perm;
151 uint64_t locked_shared_perm;
153 uint64_t aio_max_batch;
155 int perm_change_fd;
156 int perm_change_flags;
157 BDRVReopenState *reopen_state;
159 bool has_discard:1;
160 bool has_write_zeroes:1;
161 bool use_linux_aio:1;
162 bool use_linux_io_uring:1;
163 int page_cache_inconsistent; /* errno from fdatasync failure */
164 bool has_fallocate;
165 bool needs_alignment;
166 bool force_alignment;
167 bool drop_cache;
168 bool check_cache_dropped;
169 struct {
170 uint64_t discard_nb_ok;
171 uint64_t discard_nb_failed;
172 uint64_t discard_bytes_ok;
173 } stats;
175 PRManager *pr_mgr;
176 } BDRVRawState;
178 typedef struct BDRVRawReopenState {
179 int open_flags;
180 bool drop_cache;
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) */
189 if (s->fd >= 0) {
190 return 0;
192 return -EIO;
195 static int64_t raw_getlength(BlockDriverState *bs);
197 typedef struct RawPosixAIOData {
198 BlockDriverState *bs;
199 int aio_type;
200 int aio_fildes;
202 off_t aio_offset;
203 uint64_t aio_nbytes;
205 union {
206 struct {
207 struct iovec *iov;
208 int niov;
209 } io;
210 struct {
211 uint64_t cmd;
212 void *buf;
213 } ioctl;
214 struct {
215 int aio_fd2;
216 off_t aio_offset2;
217 } copy_range;
218 struct {
219 PreallocMode prealloc;
220 Error **errp;
221 } truncate;
222 struct {
223 unsigned int *nr_zones;
224 BlockZoneDescriptor *zones;
225 } zone_report;
226 struct {
227 unsigned long op;
228 } zone_mgmt;
230 } RawPosixAIOData;
232 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
233 static int cdrom_reopen(BlockDriverState *bs);
234 #endif
237 * Elide EAGAIN and EACCES details when failing to lock, as this
238 * indicates that the specified file region is already locked by
239 * another process, which is considered a common scenario.
241 #define raw_lock_error_setg_errno(errp, err, fmt, ...) \
242 do { \
243 if ((err) == EAGAIN || (err) == EACCES) { \
244 error_setg((errp), (fmt), ## __VA_ARGS__); \
245 } else { \
246 error_setg_errno((errp), (err), (fmt), ## __VA_ARGS__); \
248 } while (0)
250 #if defined(__NetBSD__)
251 static int raw_normalize_devicepath(const char **filename, Error **errp)
253 static char namebuf[PATH_MAX];
254 const char *dp, *fname;
255 struct stat sb;
257 fname = *filename;
258 dp = strrchr(fname, '/');
259 if (lstat(fname, &sb) < 0) {
260 error_setg_file_open(errp, errno, fname);
261 return -errno;
264 if (!S_ISBLK(sb.st_mode)) {
265 return 0;
268 if (dp == NULL) {
269 snprintf(namebuf, PATH_MAX, "r%s", fname);
270 } else {
271 snprintf(namebuf, PATH_MAX, "%.*s/r%s",
272 (int)(dp - fname), fname, dp + 1);
274 *filename = namebuf;
275 warn_report("%s is a block device, using %s", fname, *filename);
277 return 0;
279 #else
280 static int raw_normalize_devicepath(const char **filename, Error **errp)
282 return 0;
284 #endif
287 * Get logical block size via ioctl. On success store it in @sector_size_p.
289 static int probe_logical_blocksize(int fd, unsigned int *sector_size_p)
291 unsigned int sector_size;
292 bool success = false;
293 int i;
295 errno = ENOTSUP;
296 static const unsigned long ioctl_list[] = {
297 #ifdef BLKSSZGET
298 BLKSSZGET,
299 #endif
300 #ifdef DKIOCGETBLOCKSIZE
301 DKIOCGETBLOCKSIZE,
302 #endif
303 #ifdef DIOCGSECTORSIZE
304 DIOCGSECTORSIZE,
305 #endif
308 /* Try a few ioctls to get the right size */
309 for (i = 0; i < (int)ARRAY_SIZE(ioctl_list); i++) {
310 if (ioctl(fd, ioctl_list[i], &sector_size) >= 0) {
311 *sector_size_p = sector_size;
312 success = true;
316 return success ? 0 : -errno;
320 * Get physical block size of @fd.
321 * On success, store it in @blk_size and return 0.
322 * On failure, return -errno.
324 static int probe_physical_blocksize(int fd, unsigned int *blk_size)
326 #ifdef BLKPBSZGET
327 if (ioctl(fd, BLKPBSZGET, blk_size) < 0) {
328 return -errno;
330 return 0;
331 #else
332 return -ENOTSUP;
333 #endif
337 * Returns true if no alignment restrictions are necessary even for files
338 * opened with O_DIRECT.
340 * raw_probe_alignment() probes the required alignment and assume that 1 means
341 * the probing failed, so it falls back to a safe default of 4k. This can be
342 * avoided if we know that byte alignment is okay for the file.
344 static bool dio_byte_aligned(int fd)
346 #ifdef __linux__
347 struct statfs buf;
348 int ret;
350 ret = fstatfs(fd, &buf);
351 if (ret == 0 && buf.f_type == NFS_SUPER_MAGIC) {
352 return true;
354 #endif
355 return false;
358 static bool raw_needs_alignment(BlockDriverState *bs)
360 BDRVRawState *s = bs->opaque;
362 if ((bs->open_flags & BDRV_O_NOCACHE) != 0 && !dio_byte_aligned(s->fd)) {
363 return true;
366 return s->force_alignment;
369 /* Check if read is allowed with given memory buffer and length.
371 * This function is used to check O_DIRECT memory buffer and request alignment.
373 static bool raw_is_io_aligned(int fd, void *buf, size_t len)
375 ssize_t ret = pread(fd, buf, len, 0);
377 if (ret >= 0) {
378 return true;
381 #ifdef __linux__
382 /* The Linux kernel returns EINVAL for misaligned O_DIRECT reads. Ignore
383 * other errors (e.g. real I/O error), which could happen on a failed
384 * drive, since we only care about probing alignment.
386 if (errno != EINVAL) {
387 return true;
389 #endif
391 return false;
394 static void raw_probe_alignment(BlockDriverState *bs, int fd, Error **errp)
396 BDRVRawState *s = bs->opaque;
397 char *buf;
398 size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size());
399 size_t alignments[] = {1, 512, 1024, 2048, 4096};
401 /* For SCSI generic devices the alignment is not really used.
402 With buffered I/O, we don't have any restrictions. */
403 if (bdrv_is_sg(bs) || !s->needs_alignment) {
404 bs->bl.request_alignment = 1;
405 s->buf_align = 1;
406 return;
409 bs->bl.request_alignment = 0;
410 s->buf_align = 0;
411 /* Let's try to use the logical blocksize for the alignment. */
412 if (probe_logical_blocksize(fd, &bs->bl.request_alignment) < 0) {
413 bs->bl.request_alignment = 0;
416 #ifdef __linux__
418 * The XFS ioctl definitions are shipped in extra packages that might
419 * not always be available. Since we just need the XFS_IOC_DIOINFO ioctl
420 * here, we simply use our own definition instead:
422 struct xfs_dioattr {
423 uint32_t d_mem;
424 uint32_t d_miniosz;
425 uint32_t d_maxiosz;
426 } da;
427 if (ioctl(fd, _IOR('X', 30, struct xfs_dioattr), &da) >= 0) {
428 bs->bl.request_alignment = da.d_miniosz;
429 /* The kernel returns wrong information for d_mem */
430 /* s->buf_align = da.d_mem; */
432 #endif
435 * If we could not get the sizes so far, we can only guess them. First try
436 * to detect request alignment, since it is more likely to succeed. Then
437 * try to detect buf_align, which cannot be detected in some cases (e.g.
438 * Gluster). If buf_align cannot be detected, we fallback to the value of
439 * request_alignment.
442 if (!bs->bl.request_alignment) {
443 int i;
444 size_t align;
445 buf = qemu_memalign(max_align, max_align);
446 for (i = 0; i < ARRAY_SIZE(alignments); i++) {
447 align = alignments[i];
448 if (raw_is_io_aligned(fd, buf, align)) {
449 /* Fallback to safe value. */
450 bs->bl.request_alignment = (align != 1) ? align : max_align;
451 break;
454 qemu_vfree(buf);
457 if (!s->buf_align) {
458 int i;
459 size_t align;
460 buf = qemu_memalign(max_align, 2 * max_align);
461 for (i = 0; i < ARRAY_SIZE(alignments); i++) {
462 align = alignments[i];
463 if (raw_is_io_aligned(fd, buf + align, max_align)) {
464 /* Fallback to request_alignment. */
465 s->buf_align = (align != 1) ? align : bs->bl.request_alignment;
466 break;
469 qemu_vfree(buf);
472 if (!s->buf_align || !bs->bl.request_alignment) {
473 error_setg(errp, "Could not find working O_DIRECT alignment");
474 error_append_hint(errp, "Try cache.direct=off\n");
478 static int check_hdev_writable(int fd)
480 #if defined(BLKROGET)
481 /* Linux block devices can be configured "read-only" using blockdev(8).
482 * This is independent of device node permissions and therefore open(2)
483 * with O_RDWR succeeds. Actual writes fail with EPERM.
485 * bdrv_open() is supposed to fail if the disk is read-only. Explicitly
486 * check for read-only block devices so that Linux block devices behave
487 * properly.
489 struct stat st;
490 int readonly = 0;
492 if (fstat(fd, &st)) {
493 return -errno;
496 if (!S_ISBLK(st.st_mode)) {
497 return 0;
500 if (ioctl(fd, BLKROGET, &readonly) < 0) {
501 return -errno;
504 if (readonly) {
505 return -EACCES;
507 #endif /* defined(BLKROGET) */
508 return 0;
511 static void raw_parse_flags(int bdrv_flags, int *open_flags, bool has_writers)
513 bool read_write = false;
514 assert(open_flags != NULL);
516 *open_flags |= O_BINARY;
517 *open_flags &= ~O_ACCMODE;
519 if (bdrv_flags & BDRV_O_AUTO_RDONLY) {
520 read_write = has_writers;
521 } else if (bdrv_flags & BDRV_O_RDWR) {
522 read_write = true;
525 if (read_write) {
526 *open_flags |= O_RDWR;
527 } else {
528 *open_flags |= O_RDONLY;
531 /* Use O_DSYNC for write-through caching, no flags for write-back caching,
532 * and O_DIRECT for no caching. */
533 if ((bdrv_flags & BDRV_O_NOCACHE)) {
534 *open_flags |= O_DIRECT;
538 static void raw_parse_filename(const char *filename, QDict *options,
539 Error **errp)
541 bdrv_parse_filename_strip_prefix(filename, "file:", options);
544 static QemuOptsList raw_runtime_opts = {
545 .name = "raw",
546 .head = QTAILQ_HEAD_INITIALIZER(raw_runtime_opts.head),
547 .desc = {
549 .name = "filename",
550 .type = QEMU_OPT_STRING,
551 .help = "File name of the image",
554 .name = "aio",
555 .type = QEMU_OPT_STRING,
556 .help = "host AIO implementation (threads, native, io_uring)",
559 .name = "aio-max-batch",
560 .type = QEMU_OPT_NUMBER,
561 .help = "AIO max batch size (0 = auto handled by AIO backend, default: 0)",
564 .name = "locking",
565 .type = QEMU_OPT_STRING,
566 .help = "file locking mode (on/off/auto, default: auto)",
569 .name = "pr-manager",
570 .type = QEMU_OPT_STRING,
571 .help = "id of persistent reservation manager object (default: none)",
573 #if defined(__linux__)
575 .name = "drop-cache",
576 .type = QEMU_OPT_BOOL,
577 .help = "invalidate page cache during live migration (default: on)",
579 #endif
581 .name = "x-check-cache-dropped",
582 .type = QEMU_OPT_BOOL,
583 .help = "check that page cache was dropped on live migration (default: off)"
585 { /* end of list */ }
589 static const char *const mutable_opts[] = { "x-check-cache-dropped", NULL };
591 static int raw_open_common(BlockDriverState *bs, QDict *options,
592 int bdrv_flags, int open_flags,
593 bool device, Error **errp)
595 BDRVRawState *s = bs->opaque;
596 QemuOpts *opts;
597 Error *local_err = NULL;
598 const char *filename = NULL;
599 const char *str;
600 BlockdevAioOptions aio, aio_default;
601 int fd, ret;
602 struct stat st;
603 OnOffAuto locking;
605 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
606 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
607 ret = -EINVAL;
608 goto fail;
611 filename = qemu_opt_get(opts, "filename");
613 ret = raw_normalize_devicepath(&filename, errp);
614 if (ret != 0) {
615 goto fail;
618 if (bdrv_flags & BDRV_O_NATIVE_AIO) {
619 aio_default = BLOCKDEV_AIO_OPTIONS_NATIVE;
620 #ifdef CONFIG_LINUX_IO_URING
621 } else if (bdrv_flags & BDRV_O_IO_URING) {
622 aio_default = BLOCKDEV_AIO_OPTIONS_IO_URING;
623 #endif
624 } else {
625 aio_default = BLOCKDEV_AIO_OPTIONS_THREADS;
628 aio = qapi_enum_parse(&BlockdevAioOptions_lookup,
629 qemu_opt_get(opts, "aio"),
630 aio_default, &local_err);
631 if (local_err) {
632 error_propagate(errp, local_err);
633 ret = -EINVAL;
634 goto fail;
637 s->use_linux_aio = (aio == BLOCKDEV_AIO_OPTIONS_NATIVE);
638 #ifdef CONFIG_LINUX_IO_URING
639 s->use_linux_io_uring = (aio == BLOCKDEV_AIO_OPTIONS_IO_URING);
640 #endif
642 s->aio_max_batch = qemu_opt_get_number(opts, "aio-max-batch", 0);
644 locking = qapi_enum_parse(&OnOffAuto_lookup,
645 qemu_opt_get(opts, "locking"),
646 ON_OFF_AUTO_AUTO, &local_err);
647 if (local_err) {
648 error_propagate(errp, local_err);
649 ret = -EINVAL;
650 goto fail;
652 switch (locking) {
653 case ON_OFF_AUTO_ON:
654 s->use_lock = true;
655 if (!qemu_has_ofd_lock()) {
656 warn_report("File lock requested but OFD locking syscall is "
657 "unavailable, falling back to POSIX file locks");
658 error_printf("Due to the implementation, locks can be lost "
659 "unexpectedly.\n");
661 break;
662 case ON_OFF_AUTO_OFF:
663 s->use_lock = false;
664 break;
665 case ON_OFF_AUTO_AUTO:
666 s->use_lock = qemu_has_ofd_lock();
667 break;
668 default:
669 abort();
672 str = qemu_opt_get(opts, "pr-manager");
673 if (str) {
674 s->pr_mgr = pr_manager_lookup(str, &local_err);
675 if (local_err) {
676 error_propagate(errp, local_err);
677 ret = -EINVAL;
678 goto fail;
682 s->drop_cache = qemu_opt_get_bool(opts, "drop-cache", true);
683 s->check_cache_dropped = qemu_opt_get_bool(opts, "x-check-cache-dropped",
684 false);
686 s->open_flags = open_flags;
687 raw_parse_flags(bdrv_flags, &s->open_flags, false);
689 s->fd = -1;
690 fd = qemu_open(filename, s->open_flags, errp);
691 ret = fd < 0 ? -errno : 0;
693 if (ret < 0) {
694 if (ret == -EROFS) {
695 ret = -EACCES;
697 goto fail;
699 s->fd = fd;
701 /* Check s->open_flags rather than bdrv_flags due to auto-read-only */
702 if (s->open_flags & O_RDWR) {
703 ret = check_hdev_writable(s->fd);
704 if (ret < 0) {
705 error_setg_errno(errp, -ret, "The device is not writable");
706 goto fail;
710 s->perm = 0;
711 s->shared_perm = BLK_PERM_ALL;
713 #ifdef CONFIG_LINUX_AIO
714 /* Currently Linux does AIO only for files opened with O_DIRECT */
715 if (s->use_linux_aio && !(s->open_flags & O_DIRECT)) {
716 error_setg(errp, "aio=native was specified, but it requires "
717 "cache.direct=on, which was not specified.");
718 ret = -EINVAL;
719 goto fail;
721 #else
722 if (s->use_linux_aio) {
723 error_setg(errp, "aio=native was specified, but is not supported "
724 "in this build.");
725 ret = -EINVAL;
726 goto fail;
728 #endif /* !defined(CONFIG_LINUX_AIO) */
730 #ifndef CONFIG_LINUX_IO_URING
731 if (s->use_linux_io_uring) {
732 error_setg(errp, "aio=io_uring was specified, but is not supported "
733 "in this build.");
734 ret = -EINVAL;
735 goto fail;
737 #endif /* !defined(CONFIG_LINUX_IO_URING) */
739 s->has_discard = true;
740 s->has_write_zeroes = true;
742 if (fstat(s->fd, &st) < 0) {
743 ret = -errno;
744 error_setg_errno(errp, errno, "Could not stat file");
745 goto fail;
748 if (!device) {
749 if (!S_ISREG(st.st_mode)) {
750 error_setg(errp, "'%s' driver requires '%s' to be a regular file",
751 bs->drv->format_name, bs->filename);
752 ret = -EINVAL;
753 goto fail;
754 } else {
755 s->has_fallocate = true;
757 } else {
758 if (!(S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
759 error_setg(errp, "'%s' driver requires '%s' to be either "
760 "a character or block device",
761 bs->drv->format_name, bs->filename);
762 ret = -EINVAL;
763 goto fail;
766 #ifdef CONFIG_BLKZONED
768 * The kernel page cache does not reliably work for writes to SWR zones
769 * of zoned block device because it can not guarantee the order of writes.
771 if ((bs->bl.zoned != BLK_Z_NONE) &&
772 (!(s->open_flags & O_DIRECT))) {
773 error_setg(errp, "The driver supports zoned devices, and it requires "
774 "cache.direct=on, which was not specified.");
775 return -EINVAL; /* No host kernel page cache */
777 #endif
779 if (S_ISBLK(st.st_mode)) {
780 #ifdef __linux__
781 /* On Linux 3.10, BLKDISCARD leaves stale data in the page cache. Do
782 * not rely on the contents of discarded blocks unless using O_DIRECT.
783 * Same for BLKZEROOUT.
785 if (!(bs->open_flags & BDRV_O_NOCACHE)) {
786 s->has_write_zeroes = false;
788 #endif
790 #ifdef __FreeBSD__
791 if (S_ISCHR(st.st_mode)) {
793 * The file is a char device (disk), which on FreeBSD isn't behind
794 * a pager, so force all requests to be aligned. This is needed
795 * so QEMU makes sure all IO operations on the device are aligned
796 * to sector size, or else FreeBSD will reject them with EINVAL.
798 s->force_alignment = true;
800 #endif
801 s->needs_alignment = raw_needs_alignment(bs);
803 bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK;
804 if (S_ISREG(st.st_mode)) {
805 /* When extending regular files, we get zeros from the OS */
806 bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
808 ret = 0;
809 fail:
810 if (ret < 0 && s->fd != -1) {
811 qemu_close(s->fd);
813 if (filename && (bdrv_flags & BDRV_O_TEMPORARY)) {
814 unlink(filename);
816 qemu_opts_del(opts);
817 return ret;
820 static int raw_open(BlockDriverState *bs, QDict *options, int flags,
821 Error **errp)
823 BDRVRawState *s = bs->opaque;
825 s->type = FTYPE_FILE;
826 return raw_open_common(bs, options, flags, 0, false, errp);
829 typedef enum {
830 RAW_PL_PREPARE,
831 RAW_PL_COMMIT,
832 RAW_PL_ABORT,
833 } RawPermLockOp;
835 #define PERM_FOREACH(i) \
836 for ((i) = 0; (1ULL << (i)) <= BLK_PERM_ALL; i++)
838 /* Lock bytes indicated by @perm_lock_bits and @shared_perm_lock_bits in the
839 * file; if @unlock == true, also unlock the unneeded bytes.
840 * @shared_perm_lock_bits is the mask of all permissions that are NOT shared.
842 static int raw_apply_lock_bytes(BDRVRawState *s, int fd,
843 uint64_t perm_lock_bits,
844 uint64_t shared_perm_lock_bits,
845 bool unlock, Error **errp)
847 int ret;
848 int i;
849 uint64_t locked_perm, locked_shared_perm;
851 if (s) {
852 locked_perm = s->locked_perm;
853 locked_shared_perm = s->locked_shared_perm;
854 } else {
856 * We don't have the previous bits, just lock/unlock for each of the
857 * requested bits.
859 if (unlock) {
860 locked_perm = BLK_PERM_ALL;
861 locked_shared_perm = BLK_PERM_ALL;
862 } else {
863 locked_perm = 0;
864 locked_shared_perm = 0;
868 PERM_FOREACH(i) {
869 int off = RAW_LOCK_PERM_BASE + i;
870 uint64_t bit = (1ULL << i);
871 if ((perm_lock_bits & bit) && !(locked_perm & bit)) {
872 ret = qemu_lock_fd(fd, off, 1, false);
873 if (ret) {
874 raw_lock_error_setg_errno(errp, -ret, "Failed to lock byte %d",
875 off);
876 return ret;
877 } else if (s) {
878 s->locked_perm |= bit;
880 } else if (unlock && (locked_perm & bit) && !(perm_lock_bits & bit)) {
881 ret = qemu_unlock_fd(fd, off, 1);
882 if (ret) {
883 error_setg_errno(errp, -ret, "Failed to unlock byte %d", off);
884 return ret;
885 } else if (s) {
886 s->locked_perm &= ~bit;
890 PERM_FOREACH(i) {
891 int off = RAW_LOCK_SHARED_BASE + i;
892 uint64_t bit = (1ULL << i);
893 if ((shared_perm_lock_bits & bit) && !(locked_shared_perm & bit)) {
894 ret = qemu_lock_fd(fd, off, 1, false);
895 if (ret) {
896 raw_lock_error_setg_errno(errp, -ret, "Failed to lock byte %d",
897 off);
898 return ret;
899 } else if (s) {
900 s->locked_shared_perm |= bit;
902 } else if (unlock && (locked_shared_perm & bit) &&
903 !(shared_perm_lock_bits & bit)) {
904 ret = qemu_unlock_fd(fd, off, 1);
905 if (ret) {
906 error_setg_errno(errp, -ret, "Failed to unlock byte %d", off);
907 return ret;
908 } else if (s) {
909 s->locked_shared_perm &= ~bit;
913 return 0;
916 /* Check "unshared" bytes implied by @perm and ~@shared_perm in the file. */
917 static int raw_check_lock_bytes(int fd, uint64_t perm, uint64_t shared_perm,
918 Error **errp)
920 int ret;
921 int i;
923 PERM_FOREACH(i) {
924 int off = RAW_LOCK_SHARED_BASE + i;
925 uint64_t p = 1ULL << i;
926 if (perm & p) {
927 ret = qemu_lock_fd_test(fd, off, 1, true);
928 if (ret) {
929 char *perm_name = bdrv_perm_names(p);
931 raw_lock_error_setg_errno(errp, -ret,
932 "Failed to get \"%s\" lock",
933 perm_name);
934 g_free(perm_name);
935 return ret;
939 PERM_FOREACH(i) {
940 int off = RAW_LOCK_PERM_BASE + i;
941 uint64_t p = 1ULL << i;
942 if (!(shared_perm & p)) {
943 ret = qemu_lock_fd_test(fd, off, 1, true);
944 if (ret) {
945 char *perm_name = bdrv_perm_names(p);
947 raw_lock_error_setg_errno(errp, -ret,
948 "Failed to get shared \"%s\" lock",
949 perm_name);
950 g_free(perm_name);
951 return ret;
955 return 0;
958 static int raw_handle_perm_lock(BlockDriverState *bs,
959 RawPermLockOp op,
960 uint64_t new_perm, uint64_t new_shared,
961 Error **errp)
963 BDRVRawState *s = bs->opaque;
964 int ret = 0;
965 Error *local_err = NULL;
967 if (!s->use_lock) {
968 return 0;
971 if (bdrv_get_flags(bs) & BDRV_O_INACTIVE) {
972 return 0;
975 switch (op) {
976 case RAW_PL_PREPARE:
977 if ((s->perm | new_perm) == s->perm &&
978 (s->shared_perm & new_shared) == s->shared_perm)
981 * We are going to unlock bytes, it should not fail. If it fail due
982 * to some fs-dependent permission-unrelated reasons (which occurs
983 * sometimes on NFS and leads to abort in bdrv_replace_child) we
984 * can't prevent such errors by any check here. And we ignore them
985 * anyway in ABORT and COMMIT.
987 return 0;
989 ret = raw_apply_lock_bytes(s, s->fd, s->perm | new_perm,
990 ~s->shared_perm | ~new_shared,
991 false, errp);
992 if (!ret) {
993 ret = raw_check_lock_bytes(s->fd, new_perm, new_shared, errp);
994 if (!ret) {
995 return 0;
997 error_append_hint(errp,
998 "Is another process using the image [%s]?\n",
999 bs->filename);
1001 /* fall through to unlock bytes. */
1002 case RAW_PL_ABORT:
1003 raw_apply_lock_bytes(s, s->fd, s->perm, ~s->shared_perm,
1004 true, &local_err);
1005 if (local_err) {
1006 /* Theoretically the above call only unlocks bytes and it cannot
1007 * fail. Something weird happened, report it.
1009 warn_report_err(local_err);
1011 break;
1012 case RAW_PL_COMMIT:
1013 raw_apply_lock_bytes(s, s->fd, new_perm, ~new_shared,
1014 true, &local_err);
1015 if (local_err) {
1016 /* Theoretically the above call only unlocks bytes and it cannot
1017 * fail. Something weird happened, report it.
1019 warn_report_err(local_err);
1021 break;
1023 return ret;
1026 /* Sets a specific flag */
1027 static int fcntl_setfl(int fd, int flag)
1029 int flags;
1031 flags = fcntl(fd, F_GETFL);
1032 if (flags == -1) {
1033 return -errno;
1035 if (fcntl(fd, F_SETFL, flags | flag) == -1) {
1036 return -errno;
1038 return 0;
1041 static int raw_reconfigure_getfd(BlockDriverState *bs, int flags,
1042 int *open_flags, uint64_t perm, bool force_dup,
1043 Error **errp)
1045 BDRVRawState *s = bs->opaque;
1046 int fd = -1;
1047 int ret;
1048 bool has_writers = perm &
1049 (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED | BLK_PERM_RESIZE);
1050 int fcntl_flags = O_APPEND | O_NONBLOCK;
1051 #ifdef O_NOATIME
1052 fcntl_flags |= O_NOATIME;
1053 #endif
1055 *open_flags = 0;
1056 if (s->type == FTYPE_CD) {
1057 *open_flags |= O_NONBLOCK;
1060 raw_parse_flags(flags, open_flags, has_writers);
1062 #ifdef O_ASYNC
1063 /* Not all operating systems have O_ASYNC, and those that don't
1064 * will not let us track the state into rs->open_flags (typically
1065 * you achieve the same effect with an ioctl, for example I_SETSIG
1066 * on Solaris). But we do not use O_ASYNC, so that's fine.
1068 assert((s->open_flags & O_ASYNC) == 0);
1069 #endif
1071 if (!force_dup && *open_flags == s->open_flags) {
1072 /* We're lucky, the existing fd is fine */
1073 return s->fd;
1076 if ((*open_flags & ~fcntl_flags) == (s->open_flags & ~fcntl_flags)) {
1077 /* dup the original fd */
1078 fd = qemu_dup(s->fd);
1079 if (fd >= 0) {
1080 ret = fcntl_setfl(fd, *open_flags);
1081 if (ret) {
1082 qemu_close(fd);
1083 fd = -1;
1088 /* If we cannot use fcntl, or fcntl failed, fall back to qemu_open() */
1089 if (fd == -1) {
1090 const char *normalized_filename = bs->filename;
1091 ret = raw_normalize_devicepath(&normalized_filename, errp);
1092 if (ret >= 0) {
1093 fd = qemu_open(normalized_filename, *open_flags, errp);
1094 if (fd == -1) {
1095 return -1;
1100 if (fd != -1 && (*open_flags & O_RDWR)) {
1101 ret = check_hdev_writable(fd);
1102 if (ret < 0) {
1103 qemu_close(fd);
1104 error_setg_errno(errp, -ret, "The device is not writable");
1105 return -1;
1109 return fd;
1112 static int raw_reopen_prepare(BDRVReopenState *state,
1113 BlockReopenQueue *queue, Error **errp)
1115 BDRVRawState *s;
1116 BDRVRawReopenState *rs;
1117 QemuOpts *opts;
1118 int ret;
1120 assert(state != NULL);
1121 assert(state->bs != NULL);
1123 s = state->bs->opaque;
1125 state->opaque = g_new0(BDRVRawReopenState, 1);
1126 rs = state->opaque;
1128 /* Handle options changes */
1129 opts = qemu_opts_create(&raw_runtime_opts, NULL, 0, &error_abort);
1130 if (!qemu_opts_absorb_qdict(opts, state->options, errp)) {
1131 ret = -EINVAL;
1132 goto out;
1135 rs->drop_cache = qemu_opt_get_bool_del(opts, "drop-cache", true);
1136 rs->check_cache_dropped =
1137 qemu_opt_get_bool_del(opts, "x-check-cache-dropped", false);
1139 /* This driver's reopen function doesn't currently allow changing
1140 * other options, so let's put them back in the original QDict and
1141 * bdrv_reopen_prepare() will detect changes and complain. */
1142 qemu_opts_to_qdict(opts, state->options);
1145 * As part of reopen prepare we also want to create new fd by
1146 * raw_reconfigure_getfd(). But it wants updated "perm", when in
1147 * bdrv_reopen_multiple() .bdrv_reopen_prepare() callback called prior to
1148 * permission update. Happily, permission update is always a part
1149 * (a separate stage) of bdrv_reopen_multiple() so we can rely on this
1150 * fact and reconfigure fd in raw_check_perm().
1153 s->reopen_state = state;
1154 ret = 0;
1156 out:
1157 qemu_opts_del(opts);
1158 return ret;
1161 static void raw_reopen_commit(BDRVReopenState *state)
1163 BDRVRawReopenState *rs = state->opaque;
1164 BDRVRawState *s = state->bs->opaque;
1166 s->drop_cache = rs->drop_cache;
1167 s->check_cache_dropped = rs->check_cache_dropped;
1168 s->open_flags = rs->open_flags;
1169 g_free(state->opaque);
1170 state->opaque = NULL;
1172 assert(s->reopen_state == state);
1173 s->reopen_state = NULL;
1177 static void raw_reopen_abort(BDRVReopenState *state)
1179 BDRVRawReopenState *rs = state->opaque;
1180 BDRVRawState *s = state->bs->opaque;
1182 /* nothing to do if NULL, we didn't get far enough */
1183 if (rs == NULL) {
1184 return;
1187 g_free(state->opaque);
1188 state->opaque = NULL;
1190 assert(s->reopen_state == state);
1191 s->reopen_state = NULL;
1194 static int hdev_get_max_hw_transfer(int fd, struct stat *st)
1196 #ifdef BLKSECTGET
1197 if (S_ISBLK(st->st_mode)) {
1198 unsigned short max_sectors = 0;
1199 if (ioctl(fd, BLKSECTGET, &max_sectors) == 0) {
1200 return max_sectors * 512;
1202 } else {
1203 int max_bytes = 0;
1204 if (ioctl(fd, BLKSECTGET, &max_bytes) == 0) {
1205 return max_bytes;
1208 return -errno;
1209 #else
1210 return -ENOSYS;
1211 #endif
1215 * Get a sysfs attribute value as character string.
1217 #ifdef CONFIG_LINUX
1218 static int get_sysfs_str_val(struct stat *st, const char *attribute,
1219 char **val) {
1220 g_autofree char *sysfspath = NULL;
1221 size_t len;
1223 if (!S_ISBLK(st->st_mode)) {
1224 return -ENOTSUP;
1227 sysfspath = g_strdup_printf("/sys/dev/block/%u:%u/queue/%s",
1228 major(st->st_rdev), minor(st->st_rdev),
1229 attribute);
1230 if (!g_file_get_contents(sysfspath, val, &len, NULL)) {
1231 return -ENOENT;
1234 /* The file is ended with '\n' */
1235 char *p;
1236 p = *val;
1237 if (*(p + len - 1) == '\n') {
1238 *(p + len - 1) = '\0';
1240 return 0;
1242 #endif
1244 #if defined(CONFIG_BLKZONED)
1245 static int get_sysfs_zoned_model(struct stat *st, BlockZoneModel *zoned)
1247 g_autofree char *val = NULL;
1248 int ret;
1250 ret = get_sysfs_str_val(st, "zoned", &val);
1251 if (ret < 0) {
1252 return ret;
1255 if (strcmp(val, "host-managed") == 0) {
1256 *zoned = BLK_Z_HM;
1257 } else if (strcmp(val, "host-aware") == 0) {
1258 *zoned = BLK_Z_HA;
1259 } else if (strcmp(val, "none") == 0) {
1260 *zoned = BLK_Z_NONE;
1261 } else {
1262 return -ENOTSUP;
1264 return 0;
1266 #endif /* defined(CONFIG_BLKZONED) */
1269 * Get a sysfs attribute value as a long integer.
1271 #ifdef CONFIG_LINUX
1272 static long get_sysfs_long_val(struct stat *st, const char *attribute)
1274 g_autofree char *str = NULL;
1275 const char *end;
1276 long val;
1277 int ret;
1279 ret = get_sysfs_str_val(st, attribute, &str);
1280 if (ret < 0) {
1281 return ret;
1284 /* The file is ended with '\n', pass 'end' to accept that. */
1285 ret = qemu_strtol(str, &end, 10, &val);
1286 if (ret == 0 && end && *end == '\0') {
1287 ret = val;
1289 return ret;
1291 #endif
1293 static int hdev_get_max_segments(int fd, struct stat *st)
1295 #ifdef CONFIG_LINUX
1296 int ret;
1298 if (S_ISCHR(st->st_mode)) {
1299 if (ioctl(fd, SG_GET_SG_TABLESIZE, &ret) == 0) {
1300 return ret;
1302 return -ENOTSUP;
1304 return get_sysfs_long_val(st, "max_segments");
1305 #else
1306 return -ENOTSUP;
1307 #endif
1310 #if defined(CONFIG_BLKZONED)
1312 * If the reset_all flag is true, then the wps of zone whose state is
1313 * not readonly or offline should be all reset to the start sector.
1314 * Else, take the real wp of the device.
1316 static int get_zones_wp(BlockDriverState *bs, int fd, int64_t offset,
1317 unsigned int nrz, bool reset_all)
1319 struct blk_zone *blkz;
1320 size_t rep_size;
1321 uint64_t sector = offset >> BDRV_SECTOR_BITS;
1322 BlockZoneWps *wps = bs->wps;
1323 unsigned int j = offset / bs->bl.zone_size;
1324 unsigned int n = 0, i = 0;
1325 int ret;
1326 rep_size = sizeof(struct blk_zone_report) + nrz * sizeof(struct blk_zone);
1327 g_autofree struct blk_zone_report *rep = NULL;
1329 rep = g_malloc(rep_size);
1330 blkz = (struct blk_zone *)(rep + 1);
1331 while (n < nrz) {
1332 memset(rep, 0, rep_size);
1333 rep->sector = sector;
1334 rep->nr_zones = nrz - n;
1336 do {
1337 ret = ioctl(fd, BLKREPORTZONE, rep);
1338 } while (ret != 0 && errno == EINTR);
1339 if (ret != 0) {
1340 error_report("%d: ioctl BLKREPORTZONE at %" PRId64 " failed %d",
1341 fd, offset, errno);
1342 return -errno;
1345 if (!rep->nr_zones) {
1346 break;
1349 for (i = 0; i < rep->nr_zones; ++i, ++n, ++j) {
1351 * The wp tracking cares only about sequential writes required and
1352 * sequential write preferred zones so that the wp can advance to
1353 * the right location.
1354 * Use the most significant bit of the wp location to indicate the
1355 * zone type: 0 for SWR/SWP zones and 1 for conventional zones.
1357 if (blkz[i].type == BLK_ZONE_TYPE_CONVENTIONAL) {
1358 wps->wp[j] |= 1ULL << 63;
1359 } else {
1360 switch(blkz[i].cond) {
1361 case BLK_ZONE_COND_FULL:
1362 case BLK_ZONE_COND_READONLY:
1363 /* Zone not writable */
1364 wps->wp[j] = (blkz[i].start + blkz[i].len) << BDRV_SECTOR_BITS;
1365 break;
1366 case BLK_ZONE_COND_OFFLINE:
1367 /* Zone not writable nor readable */
1368 wps->wp[j] = (blkz[i].start) << BDRV_SECTOR_BITS;
1369 break;
1370 default:
1371 if (reset_all) {
1372 wps->wp[j] = blkz[i].start << BDRV_SECTOR_BITS;
1373 } else {
1374 wps->wp[j] = blkz[i].wp << BDRV_SECTOR_BITS;
1376 break;
1380 sector = blkz[i - 1].start + blkz[i - 1].len;
1383 return 0;
1386 static void update_zones_wp(BlockDriverState *bs, int fd, int64_t offset,
1387 unsigned int nrz)
1389 if (get_zones_wp(bs, fd, offset, nrz, 0) < 0) {
1390 error_report("update zone wp failed");
1394 static void raw_refresh_zoned_limits(BlockDriverState *bs, struct stat *st,
1395 Error **errp)
1397 BDRVRawState *s = bs->opaque;
1398 BlockZoneModel zoned;
1399 int ret;
1401 ret = get_sysfs_zoned_model(st, &zoned);
1402 if (ret < 0 || zoned == BLK_Z_NONE) {
1403 goto no_zoned;
1405 bs->bl.zoned = zoned;
1407 ret = get_sysfs_long_val(st, "max_open_zones");
1408 if (ret >= 0) {
1409 bs->bl.max_open_zones = ret;
1412 ret = get_sysfs_long_val(st, "max_active_zones");
1413 if (ret >= 0) {
1414 bs->bl.max_active_zones = ret;
1418 * The zoned device must at least have zone size and nr_zones fields.
1420 ret = get_sysfs_long_val(st, "chunk_sectors");
1421 if (ret < 0) {
1422 error_setg_errno(errp, -ret, "Unable to read chunk_sectors "
1423 "sysfs attribute");
1424 goto no_zoned;
1425 } else if (!ret) {
1426 error_setg(errp, "Read 0 from chunk_sectors sysfs attribute");
1427 goto no_zoned;
1429 bs->bl.zone_size = ret << BDRV_SECTOR_BITS;
1431 ret = get_sysfs_long_val(st, "nr_zones");
1432 if (ret < 0) {
1433 error_setg_errno(errp, -ret, "Unable to read nr_zones "
1434 "sysfs attribute");
1435 goto no_zoned;
1436 } else if (!ret) {
1437 error_setg(errp, "Read 0 from nr_zones sysfs attribute");
1438 goto no_zoned;
1440 bs->bl.nr_zones = ret;
1442 ret = get_sysfs_long_val(st, "zone_append_max_bytes");
1443 if (ret > 0) {
1444 bs->bl.max_append_sectors = ret >> BDRV_SECTOR_BITS;
1447 ret = get_sysfs_long_val(st, "physical_block_size");
1448 if (ret >= 0) {
1449 bs->bl.write_granularity = ret;
1452 /* The refresh_limits() function can be called multiple times. */
1453 g_free(bs->wps);
1454 bs->wps = g_malloc(sizeof(BlockZoneWps) +
1455 sizeof(int64_t) * bs->bl.nr_zones);
1456 ret = get_zones_wp(bs, s->fd, 0, bs->bl.nr_zones, 0);
1457 if (ret < 0) {
1458 error_setg_errno(errp, -ret, "report wps failed");
1459 goto no_zoned;
1461 qemu_co_mutex_init(&bs->wps->colock);
1462 return;
1464 no_zoned:
1465 bs->bl.zoned = BLK_Z_NONE;
1466 g_free(bs->wps);
1467 bs->wps = NULL;
1469 #else /* !defined(CONFIG_BLKZONED) */
1470 static void raw_refresh_zoned_limits(BlockDriverState *bs, struct stat *st,
1471 Error **errp)
1473 bs->bl.zoned = BLK_Z_NONE;
1475 #endif /* !defined(CONFIG_BLKZONED) */
1477 static void raw_refresh_limits(BlockDriverState *bs, Error **errp)
1479 BDRVRawState *s = bs->opaque;
1480 struct stat st;
1482 s->needs_alignment = raw_needs_alignment(bs);
1483 raw_probe_alignment(bs, s->fd, errp);
1485 bs->bl.min_mem_alignment = s->buf_align;
1486 bs->bl.opt_mem_alignment = MAX(s->buf_align, qemu_real_host_page_size());
1489 * Maximum transfers are best effort, so it is okay to ignore any
1490 * errors. That said, based on the man page errors in fstat would be
1491 * very much unexpected; the only possible case seems to be ENOMEM.
1493 if (fstat(s->fd, &st)) {
1494 return;
1497 #if defined(__APPLE__) && (__MACH__)
1498 struct statfs buf;
1500 if (!fstatfs(s->fd, &buf)) {
1501 bs->bl.opt_transfer = buf.f_iosize;
1502 bs->bl.pdiscard_alignment = buf.f_bsize;
1504 #endif
1506 if (bdrv_is_sg(bs) || S_ISBLK(st.st_mode)) {
1507 int ret = hdev_get_max_hw_transfer(s->fd, &st);
1509 if (ret > 0 && ret <= BDRV_REQUEST_MAX_BYTES) {
1510 bs->bl.max_hw_transfer = ret;
1513 ret = hdev_get_max_segments(s->fd, &st);
1514 if (ret > 0) {
1515 bs->bl.max_hw_iov = ret;
1519 raw_refresh_zoned_limits(bs, &st, errp);
1522 static int check_for_dasd(int fd)
1524 #ifdef BIODASDINFO2
1525 struct dasd_information2_t info = {0};
1527 return ioctl(fd, BIODASDINFO2, &info);
1528 #else
1529 return -1;
1530 #endif
1534 * Try to get @bs's logical and physical block size.
1535 * On success, store them in @bsz and return zero.
1536 * On failure, return negative errno.
1538 static int hdev_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
1540 BDRVRawState *s = bs->opaque;
1541 int ret;
1543 /* If DASD or zoned devices, get blocksizes */
1544 if (check_for_dasd(s->fd) < 0) {
1545 /* zoned devices are not DASD */
1546 if (bs->bl.zoned == BLK_Z_NONE) {
1547 return -ENOTSUP;
1550 ret = probe_logical_blocksize(s->fd, &bsz->log);
1551 if (ret < 0) {
1552 return ret;
1554 return probe_physical_blocksize(s->fd, &bsz->phys);
1558 * Try to get @bs's geometry: cyls, heads, sectors.
1559 * On success, store them in @geo and return 0.
1560 * On failure return -errno.
1561 * (Allows block driver to assign default geometry values that guest sees)
1563 #ifdef __linux__
1564 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1566 BDRVRawState *s = bs->opaque;
1567 struct hd_geometry ioctl_geo = {0};
1569 /* If DASD, get its geometry */
1570 if (check_for_dasd(s->fd) < 0) {
1571 return -ENOTSUP;
1573 if (ioctl(s->fd, HDIO_GETGEO, &ioctl_geo) < 0) {
1574 return -errno;
1576 /* HDIO_GETGEO may return success even though geo contains zeros
1577 (e.g. certain multipath setups) */
1578 if (!ioctl_geo.heads || !ioctl_geo.sectors || !ioctl_geo.cylinders) {
1579 return -ENOTSUP;
1581 /* Do not return a geometry for partition */
1582 if (ioctl_geo.start != 0) {
1583 return -ENOTSUP;
1585 geo->heads = ioctl_geo.heads;
1586 geo->sectors = ioctl_geo.sectors;
1587 geo->cylinders = ioctl_geo.cylinders;
1589 return 0;
1591 #else /* __linux__ */
1592 static int hdev_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
1594 return -ENOTSUP;
1596 #endif
1598 #if defined(__linux__)
1599 static int handle_aiocb_ioctl(void *opaque)
1601 RawPosixAIOData *aiocb = opaque;
1602 int ret;
1604 ret = RETRY_ON_EINTR(
1605 ioctl(aiocb->aio_fildes, aiocb->ioctl.cmd, aiocb->ioctl.buf)
1607 if (ret == -1) {
1608 return -errno;
1611 return 0;
1613 #endif /* linux */
1615 static int handle_aiocb_flush(void *opaque)
1617 RawPosixAIOData *aiocb = opaque;
1618 BDRVRawState *s = aiocb->bs->opaque;
1619 int ret;
1621 if (s->page_cache_inconsistent) {
1622 return -s->page_cache_inconsistent;
1625 ret = qemu_fdatasync(aiocb->aio_fildes);
1626 if (ret == -1) {
1627 trace_file_flush_fdatasync_failed(errno);
1629 /* There is no clear definition of the semantics of a failing fsync(),
1630 * so we may have to assume the worst. The sad truth is that this
1631 * assumption is correct for Linux. Some pages are now probably marked
1632 * clean in the page cache even though they are inconsistent with the
1633 * on-disk contents. The next fdatasync() call would succeed, but no
1634 * further writeback attempt will be made. We can't get back to a state
1635 * in which we know what is on disk (we would have to rewrite
1636 * everything that was touched since the last fdatasync() at least), so
1637 * make bdrv_flush() fail permanently. Given that the behaviour isn't
1638 * really defined, I have little hope that other OSes are doing better.
1640 * Obviously, this doesn't affect O_DIRECT, which bypasses the page
1641 * cache. */
1642 if ((s->open_flags & O_DIRECT) == 0) {
1643 s->page_cache_inconsistent = errno;
1645 return -errno;
1647 return 0;
1650 #ifdef CONFIG_PREADV
1652 static bool preadv_present = true;
1654 static ssize_t
1655 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1657 return preadv(fd, iov, nr_iov, offset);
1660 static ssize_t
1661 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1663 return pwritev(fd, iov, nr_iov, offset);
1666 #else
1668 static bool preadv_present = false;
1670 static ssize_t
1671 qemu_preadv(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1673 return -ENOSYS;
1676 static ssize_t
1677 qemu_pwritev(int fd, const struct iovec *iov, int nr_iov, off_t offset)
1679 return -ENOSYS;
1682 #endif
1684 static ssize_t handle_aiocb_rw_vector(RawPosixAIOData *aiocb)
1686 ssize_t len;
1688 len = RETRY_ON_EINTR(
1689 (aiocb->aio_type & (QEMU_AIO_WRITE | QEMU_AIO_ZONE_APPEND)) ?
1690 qemu_pwritev(aiocb->aio_fildes,
1691 aiocb->io.iov,
1692 aiocb->io.niov,
1693 aiocb->aio_offset) :
1694 qemu_preadv(aiocb->aio_fildes,
1695 aiocb->io.iov,
1696 aiocb->io.niov,
1697 aiocb->aio_offset)
1700 if (len == -1) {
1701 return -errno;
1703 return len;
1707 * Read/writes the data to/from a given linear buffer.
1709 * Returns the number of bytes handles or -errno in case of an error. Short
1710 * reads are only returned if the end of the file is reached.
1712 static ssize_t handle_aiocb_rw_linear(RawPosixAIOData *aiocb, char *buf)
1714 ssize_t offset = 0;
1715 ssize_t len;
1717 while (offset < aiocb->aio_nbytes) {
1718 if (aiocb->aio_type & (QEMU_AIO_WRITE | QEMU_AIO_ZONE_APPEND)) {
1719 len = pwrite(aiocb->aio_fildes,
1720 (const char *)buf + offset,
1721 aiocb->aio_nbytes - offset,
1722 aiocb->aio_offset + offset);
1723 } else {
1724 len = pread(aiocb->aio_fildes,
1725 buf + offset,
1726 aiocb->aio_nbytes - offset,
1727 aiocb->aio_offset + offset);
1729 if (len == -1 && errno == EINTR) {
1730 continue;
1731 } else if (len == -1 && errno == EINVAL &&
1732 (aiocb->bs->open_flags & BDRV_O_NOCACHE) &&
1733 !(aiocb->aio_type & QEMU_AIO_WRITE) &&
1734 offset > 0) {
1735 /* O_DIRECT pread() may fail with EINVAL when offset is unaligned
1736 * after a short read. Assume that O_DIRECT short reads only occur
1737 * at EOF. Therefore this is a short read, not an I/O error.
1739 break;
1740 } else if (len == -1) {
1741 offset = -errno;
1742 break;
1743 } else if (len == 0) {
1744 break;
1746 offset += len;
1749 return offset;
1752 static int handle_aiocb_rw(void *opaque)
1754 RawPosixAIOData *aiocb = opaque;
1755 ssize_t nbytes;
1756 char *buf;
1758 if (!(aiocb->aio_type & QEMU_AIO_MISALIGNED)) {
1760 * If there is just a single buffer, and it is properly aligned
1761 * we can just use plain pread/pwrite without any problems.
1763 if (aiocb->io.niov == 1) {
1764 nbytes = handle_aiocb_rw_linear(aiocb, aiocb->io.iov->iov_base);
1765 goto out;
1768 * We have more than one iovec, and all are properly aligned.
1770 * Try preadv/pwritev first and fall back to linearizing the
1771 * buffer if it's not supported.
1773 if (preadv_present) {
1774 nbytes = handle_aiocb_rw_vector(aiocb);
1775 if (nbytes == aiocb->aio_nbytes ||
1776 (nbytes < 0 && nbytes != -ENOSYS)) {
1777 goto out;
1779 preadv_present = false;
1783 * XXX(hch): short read/write. no easy way to handle the reminder
1784 * using these interfaces. For now retry using plain
1785 * pread/pwrite?
1790 * Ok, we have to do it the hard way, copy all segments into
1791 * a single aligned buffer.
1793 buf = qemu_try_blockalign(aiocb->bs, aiocb->aio_nbytes);
1794 if (buf == NULL) {
1795 nbytes = -ENOMEM;
1796 goto out;
1799 if (aiocb->aio_type & QEMU_AIO_WRITE) {
1800 char *p = buf;
1801 int i;
1803 for (i = 0; i < aiocb->io.niov; ++i) {
1804 memcpy(p, aiocb->io.iov[i].iov_base, aiocb->io.iov[i].iov_len);
1805 p += aiocb->io.iov[i].iov_len;
1807 assert(p - buf == aiocb->aio_nbytes);
1810 nbytes = handle_aiocb_rw_linear(aiocb, buf);
1811 if (!(aiocb->aio_type & (QEMU_AIO_WRITE | QEMU_AIO_ZONE_APPEND))) {
1812 char *p = buf;
1813 size_t count = aiocb->aio_nbytes, copy;
1814 int i;
1816 for (i = 0; i < aiocb->io.niov && count; ++i) {
1817 copy = count;
1818 if (copy > aiocb->io.iov[i].iov_len) {
1819 copy = aiocb->io.iov[i].iov_len;
1821 memcpy(aiocb->io.iov[i].iov_base, p, copy);
1822 assert(count >= copy);
1823 p += copy;
1824 count -= copy;
1826 assert(count == 0);
1828 qemu_vfree(buf);
1830 out:
1831 if (nbytes == aiocb->aio_nbytes) {
1832 return 0;
1833 } else if (nbytes >= 0 && nbytes < aiocb->aio_nbytes) {
1834 if (aiocb->aio_type & QEMU_AIO_WRITE) {
1835 return -EINVAL;
1836 } else {
1837 iov_memset(aiocb->io.iov, aiocb->io.niov, nbytes,
1838 0, aiocb->aio_nbytes - nbytes);
1839 return 0;
1841 } else {
1842 assert(nbytes < 0);
1843 return nbytes;
1847 #if defined(CONFIG_FALLOCATE) || defined(BLKZEROOUT) || defined(BLKDISCARD)
1848 static int translate_err(int err)
1850 if (err == -ENODEV || err == -ENOSYS || err == -EOPNOTSUPP ||
1851 err == -ENOTTY) {
1852 err = -ENOTSUP;
1854 return err;
1856 #endif
1858 #ifdef CONFIG_FALLOCATE
1859 static int do_fallocate(int fd, int mode, off_t offset, off_t len)
1861 do {
1862 if (fallocate(fd, mode, offset, len) == 0) {
1863 return 0;
1865 } while (errno == EINTR);
1866 return translate_err(-errno);
1868 #endif
1870 static ssize_t handle_aiocb_write_zeroes_block(RawPosixAIOData *aiocb)
1872 int ret = -ENOTSUP;
1873 BDRVRawState *s = aiocb->bs->opaque;
1875 if (!s->has_write_zeroes) {
1876 return -ENOTSUP;
1879 #ifdef BLKZEROOUT
1880 /* The BLKZEROOUT implementation in the kernel doesn't set
1881 * BLKDEV_ZERO_NOFALLBACK, so we can't call this if we have to avoid slow
1882 * fallbacks. */
1883 if (!(aiocb->aio_type & QEMU_AIO_NO_FALLBACK)) {
1884 do {
1885 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
1886 if (ioctl(aiocb->aio_fildes, BLKZEROOUT, range) == 0) {
1887 return 0;
1889 } while (errno == EINTR);
1891 ret = translate_err(-errno);
1892 if (ret == -ENOTSUP) {
1893 s->has_write_zeroes = false;
1896 #endif
1898 return ret;
1901 static int handle_aiocb_write_zeroes(void *opaque)
1903 RawPosixAIOData *aiocb = opaque;
1904 #ifdef CONFIG_FALLOCATE
1905 BDRVRawState *s = aiocb->bs->opaque;
1906 int64_t len;
1907 #endif
1909 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
1910 return handle_aiocb_write_zeroes_block(aiocb);
1913 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1914 if (s->has_write_zeroes) {
1915 int ret = do_fallocate(s->fd, FALLOC_FL_ZERO_RANGE,
1916 aiocb->aio_offset, aiocb->aio_nbytes);
1917 if (ret == -ENOTSUP) {
1918 s->has_write_zeroes = false;
1919 } else if (ret == 0 || ret != -EINVAL) {
1920 return ret;
1923 * Note: Some file systems do not like unaligned byte ranges, and
1924 * return EINVAL in such a case, though they should not do it according
1925 * to the man-page of fallocate(). Thus we simply ignore this return
1926 * value and try the other fallbacks instead.
1929 #endif
1931 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1932 if (s->has_discard && s->has_fallocate) {
1933 int ret = do_fallocate(s->fd,
1934 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1935 aiocb->aio_offset, aiocb->aio_nbytes);
1936 if (ret == 0) {
1937 ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1938 if (ret == 0 || ret != -ENOTSUP) {
1939 return ret;
1941 s->has_fallocate = false;
1942 } else if (ret == -EINVAL) {
1944 * Some file systems like older versions of GPFS do not like un-
1945 * aligned byte ranges, and return EINVAL in such a case, though
1946 * they should not do it according to the man-page of fallocate().
1947 * Warn about the bad filesystem and try the final fallback instead.
1949 warn_report_once("Your file system is misbehaving: "
1950 "fallocate(FALLOC_FL_PUNCH_HOLE) returned EINVAL. "
1951 "Please report this bug to your file system "
1952 "vendor.");
1953 } else if (ret != -ENOTSUP) {
1954 return ret;
1955 } else {
1956 s->has_discard = false;
1959 #endif
1961 #ifdef CONFIG_FALLOCATE
1962 /* Last resort: we are trying to extend the file with zeroed data. This
1963 * can be done via fallocate(fd, 0) */
1964 len = raw_getlength(aiocb->bs);
1965 if (s->has_fallocate && len >= 0 && aiocb->aio_offset >= len) {
1966 int ret = do_fallocate(s->fd, 0, aiocb->aio_offset, aiocb->aio_nbytes);
1967 if (ret == 0 || ret != -ENOTSUP) {
1968 return ret;
1970 s->has_fallocate = false;
1972 #endif
1974 return -ENOTSUP;
1977 static int handle_aiocb_write_zeroes_unmap(void *opaque)
1979 RawPosixAIOData *aiocb = opaque;
1980 BDRVRawState *s G_GNUC_UNUSED = aiocb->bs->opaque;
1982 /* First try to write zeros and unmap at the same time */
1984 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1985 int ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1986 aiocb->aio_offset, aiocb->aio_nbytes);
1987 switch (ret) {
1988 case -ENOTSUP:
1989 case -EINVAL:
1990 case -EBUSY:
1991 break;
1992 default:
1993 return ret;
1995 #endif
1997 /* If we couldn't manage to unmap while guaranteed that the area reads as
1998 * all-zero afterwards, just write zeroes without unmapping */
1999 return handle_aiocb_write_zeroes(aiocb);
2002 #ifndef HAVE_COPY_FILE_RANGE
2004 /* Avoid conflict with system header file. */
2005 #define copy_file_range(a, b, c, d, e, f) local_copy_file_range(a, b, c, d, e, f)
2007 static off_t copy_file_range(int in_fd, off_t *in_off, int out_fd,
2008 off_t *out_off, size_t len, unsigned int flags)
2010 #ifdef __NR_copy_file_range
2011 return syscall(__NR_copy_file_range, in_fd, in_off, out_fd,
2012 out_off, len, flags);
2013 #else
2014 errno = ENOSYS;
2015 return -1;
2016 #endif
2018 #endif
2021 * parse_zone - Fill a zone descriptor
2023 #if defined(CONFIG_BLKZONED)
2024 static inline int parse_zone(struct BlockZoneDescriptor *zone,
2025 const struct blk_zone *blkz) {
2026 zone->start = blkz->start << BDRV_SECTOR_BITS;
2027 zone->length = blkz->len << BDRV_SECTOR_BITS;
2028 zone->wp = blkz->wp << BDRV_SECTOR_BITS;
2030 #ifdef HAVE_BLK_ZONE_REP_CAPACITY
2031 zone->cap = blkz->capacity << BDRV_SECTOR_BITS;
2032 #else
2033 zone->cap = blkz->len << BDRV_SECTOR_BITS;
2034 #endif
2036 switch (blkz->type) {
2037 case BLK_ZONE_TYPE_SEQWRITE_REQ:
2038 zone->type = BLK_ZT_SWR;
2039 break;
2040 case BLK_ZONE_TYPE_SEQWRITE_PREF:
2041 zone->type = BLK_ZT_SWP;
2042 break;
2043 case BLK_ZONE_TYPE_CONVENTIONAL:
2044 zone->type = BLK_ZT_CONV;
2045 break;
2046 default:
2047 error_report("Unsupported zone type: 0x%x", blkz->type);
2048 return -ENOTSUP;
2051 switch (blkz->cond) {
2052 case BLK_ZONE_COND_NOT_WP:
2053 zone->state = BLK_ZS_NOT_WP;
2054 break;
2055 case BLK_ZONE_COND_EMPTY:
2056 zone->state = BLK_ZS_EMPTY;
2057 break;
2058 case BLK_ZONE_COND_IMP_OPEN:
2059 zone->state = BLK_ZS_IOPEN;
2060 break;
2061 case BLK_ZONE_COND_EXP_OPEN:
2062 zone->state = BLK_ZS_EOPEN;
2063 break;
2064 case BLK_ZONE_COND_CLOSED:
2065 zone->state = BLK_ZS_CLOSED;
2066 break;
2067 case BLK_ZONE_COND_READONLY:
2068 zone->state = BLK_ZS_RDONLY;
2069 break;
2070 case BLK_ZONE_COND_FULL:
2071 zone->state = BLK_ZS_FULL;
2072 break;
2073 case BLK_ZONE_COND_OFFLINE:
2074 zone->state = BLK_ZS_OFFLINE;
2075 break;
2076 default:
2077 error_report("Unsupported zone state: 0x%x", blkz->cond);
2078 return -ENOTSUP;
2080 return 0;
2082 #endif
2084 #if defined(CONFIG_BLKZONED)
2085 static int handle_aiocb_zone_report(void *opaque)
2087 RawPosixAIOData *aiocb = opaque;
2088 int fd = aiocb->aio_fildes;
2089 unsigned int *nr_zones = aiocb->zone_report.nr_zones;
2090 BlockZoneDescriptor *zones = aiocb->zone_report.zones;
2091 /* zoned block devices use 512-byte sectors */
2092 uint64_t sector = aiocb->aio_offset / 512;
2094 struct blk_zone *blkz;
2095 size_t rep_size;
2096 unsigned int nrz;
2097 int ret;
2098 unsigned int n = 0, i = 0;
2100 nrz = *nr_zones;
2101 rep_size = sizeof(struct blk_zone_report) + nrz * sizeof(struct blk_zone);
2102 g_autofree struct blk_zone_report *rep = NULL;
2103 rep = g_malloc(rep_size);
2105 blkz = (struct blk_zone *)(rep + 1);
2106 while (n < nrz) {
2107 memset(rep, 0, rep_size);
2108 rep->sector = sector;
2109 rep->nr_zones = nrz - n;
2111 do {
2112 ret = ioctl(fd, BLKREPORTZONE, rep);
2113 } while (ret != 0 && errno == EINTR);
2114 if (ret != 0) {
2115 error_report("%d: ioctl BLKREPORTZONE at %" PRId64 " failed %d",
2116 fd, sector, errno);
2117 return -errno;
2120 if (!rep->nr_zones) {
2121 break;
2124 for (i = 0; i < rep->nr_zones; i++, n++) {
2125 ret = parse_zone(&zones[n], &blkz[i]);
2126 if (ret != 0) {
2127 return ret;
2130 /* The next report should start after the last zone reported */
2131 sector = blkz[i].start + blkz[i].len;
2135 *nr_zones = n;
2136 return 0;
2138 #endif
2140 #if defined(CONFIG_BLKZONED)
2141 static int handle_aiocb_zone_mgmt(void *opaque)
2143 RawPosixAIOData *aiocb = opaque;
2144 int fd = aiocb->aio_fildes;
2145 uint64_t sector = aiocb->aio_offset / 512;
2146 int64_t nr_sectors = aiocb->aio_nbytes / 512;
2147 struct blk_zone_range range;
2148 int ret;
2150 /* Execute the operation */
2151 range.sector = sector;
2152 range.nr_sectors = nr_sectors;
2153 do {
2154 ret = ioctl(fd, aiocb->zone_mgmt.op, &range);
2155 } while (ret != 0 && errno == EINTR);
2157 return ret < 0 ? -errno : ret;
2159 #endif
2161 static int handle_aiocb_copy_range(void *opaque)
2163 RawPosixAIOData *aiocb = opaque;
2164 uint64_t bytes = aiocb->aio_nbytes;
2165 off_t in_off = aiocb->aio_offset;
2166 off_t out_off = aiocb->copy_range.aio_offset2;
2168 while (bytes) {
2169 ssize_t ret = copy_file_range(aiocb->aio_fildes, &in_off,
2170 aiocb->copy_range.aio_fd2, &out_off,
2171 bytes, 0);
2172 trace_file_copy_file_range(aiocb->bs, aiocb->aio_fildes, in_off,
2173 aiocb->copy_range.aio_fd2, out_off, bytes,
2174 0, ret);
2175 if (ret == 0) {
2176 /* No progress (e.g. when beyond EOF), let the caller fall back to
2177 * buffer I/O. */
2178 return -ENOSPC;
2180 if (ret < 0) {
2181 switch (errno) {
2182 case ENOSYS:
2183 return -ENOTSUP;
2184 case EINTR:
2185 continue;
2186 default:
2187 return -errno;
2190 bytes -= ret;
2192 return 0;
2195 static int handle_aiocb_discard(void *opaque)
2197 RawPosixAIOData *aiocb = opaque;
2198 int ret = -ENOTSUP;
2199 BDRVRawState *s = aiocb->bs->opaque;
2201 if (!s->has_discard) {
2202 return -ENOTSUP;
2205 if (aiocb->aio_type & QEMU_AIO_BLKDEV) {
2206 #ifdef BLKDISCARD
2207 do {
2208 uint64_t range[2] = { aiocb->aio_offset, aiocb->aio_nbytes };
2209 if (ioctl(aiocb->aio_fildes, BLKDISCARD, range) == 0) {
2210 return 0;
2212 } while (errno == EINTR);
2214 ret = translate_err(-errno);
2215 #endif
2216 } else {
2217 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
2218 ret = do_fallocate(s->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
2219 aiocb->aio_offset, aiocb->aio_nbytes);
2220 ret = translate_err(ret);
2221 #elif defined(__APPLE__) && (__MACH__)
2222 fpunchhole_t fpunchhole;
2223 fpunchhole.fp_flags = 0;
2224 fpunchhole.reserved = 0;
2225 fpunchhole.fp_offset = aiocb->aio_offset;
2226 fpunchhole.fp_length = aiocb->aio_nbytes;
2227 if (fcntl(s->fd, F_PUNCHHOLE, &fpunchhole) == -1) {
2228 ret = errno == ENODEV ? -ENOTSUP : -errno;
2229 } else {
2230 ret = 0;
2232 #endif
2235 if (ret == -ENOTSUP) {
2236 s->has_discard = false;
2238 return ret;
2242 * Help alignment probing by allocating the first block.
2244 * When reading with direct I/O from unallocated area on Gluster backed by XFS,
2245 * reading succeeds regardless of request length. In this case we fallback to
2246 * safe alignment which is not optimal. Allocating the first block avoids this
2247 * fallback.
2249 * fd may be opened with O_DIRECT, but we don't know the buffer alignment or
2250 * request alignment, so we use safe values.
2252 * Returns: 0 on success, -errno on failure. Since this is an optimization,
2253 * caller may ignore failures.
2255 static int allocate_first_block(int fd, size_t max_size)
2257 size_t write_size = (max_size < MAX_BLOCKSIZE)
2258 ? BDRV_SECTOR_SIZE
2259 : MAX_BLOCKSIZE;
2260 size_t max_align = MAX(MAX_BLOCKSIZE, qemu_real_host_page_size());
2261 void *buf;
2262 ssize_t n;
2263 int ret;
2265 buf = qemu_memalign(max_align, write_size);
2266 memset(buf, 0, write_size);
2268 n = RETRY_ON_EINTR(pwrite(fd, buf, write_size, 0));
2270 ret = (n == -1) ? -errno : 0;
2272 qemu_vfree(buf);
2273 return ret;
2276 static int handle_aiocb_truncate(void *opaque)
2278 RawPosixAIOData *aiocb = opaque;
2279 int result = 0;
2280 int64_t current_length = 0;
2281 char *buf = NULL;
2282 struct stat st;
2283 int fd = aiocb->aio_fildes;
2284 int64_t offset = aiocb->aio_offset;
2285 PreallocMode prealloc = aiocb->truncate.prealloc;
2286 Error **errp = aiocb->truncate.errp;
2288 if (fstat(fd, &st) < 0) {
2289 result = -errno;
2290 error_setg_errno(errp, -result, "Could not stat file");
2291 return result;
2294 current_length = st.st_size;
2295 if (current_length > offset && prealloc != PREALLOC_MODE_OFF) {
2296 error_setg(errp, "Cannot use preallocation for shrinking files");
2297 return -ENOTSUP;
2300 switch (prealloc) {
2301 #ifdef CONFIG_POSIX_FALLOCATE
2302 case PREALLOC_MODE_FALLOC:
2304 * Truncating before posix_fallocate() makes it about twice slower on
2305 * file systems that do not support fallocate(), trying to check if a
2306 * block is allocated before allocating it, so don't do that here.
2308 if (offset != current_length) {
2309 result = -posix_fallocate(fd, current_length,
2310 offset - current_length);
2311 if (result != 0) {
2312 /* posix_fallocate() doesn't set errno. */
2313 error_setg_errno(errp, -result,
2314 "Could not preallocate new data");
2315 } else if (current_length == 0) {
2317 * posix_fallocate() uses fallocate() if the filesystem
2318 * supports it, or fallback to manually writing zeroes. If
2319 * fallocate() was used, unaligned reads from the fallocated
2320 * area in raw_probe_alignment() will succeed, hence we need to
2321 * allocate the first block.
2323 * Optimize future alignment probing; ignore failures.
2325 allocate_first_block(fd, offset);
2327 } else {
2328 result = 0;
2330 goto out;
2331 #endif
2332 case PREALLOC_MODE_FULL:
2334 int64_t num = 0, left = offset - current_length;
2335 off_t seek_result;
2338 * Knowing the final size from the beginning could allow the file
2339 * system driver to do less allocations and possibly avoid
2340 * fragmentation of the file.
2342 if (ftruncate(fd, offset) != 0) {
2343 result = -errno;
2344 error_setg_errno(errp, -result, "Could not resize file");
2345 goto out;
2348 buf = g_malloc0(65536);
2350 seek_result = lseek(fd, current_length, SEEK_SET);
2351 if (seek_result < 0) {
2352 result = -errno;
2353 error_setg_errno(errp, -result,
2354 "Failed to seek to the old end of file");
2355 goto out;
2358 while (left > 0) {
2359 num = MIN(left, 65536);
2360 result = write(fd, buf, num);
2361 if (result < 0) {
2362 if (errno == EINTR) {
2363 continue;
2365 result = -errno;
2366 error_setg_errno(errp, -result,
2367 "Could not write zeros for preallocation");
2368 goto out;
2370 left -= result;
2372 if (result >= 0) {
2373 result = fsync(fd);
2374 if (result < 0) {
2375 result = -errno;
2376 error_setg_errno(errp, -result,
2377 "Could not flush file to disk");
2378 goto out;
2381 goto out;
2383 case PREALLOC_MODE_OFF:
2384 if (ftruncate(fd, offset) != 0) {
2385 result = -errno;
2386 error_setg_errno(errp, -result, "Could not resize file");
2387 } else if (current_length == 0 && offset > current_length) {
2388 /* Optimize future alignment probing; ignore failures. */
2389 allocate_first_block(fd, offset);
2391 return result;
2392 default:
2393 result = -ENOTSUP;
2394 error_setg(errp, "Unsupported preallocation mode: %s",
2395 PreallocMode_str(prealloc));
2396 return result;
2399 out:
2400 if (result < 0) {
2401 if (ftruncate(fd, current_length) < 0) {
2402 error_report("Failed to restore old file length: %s",
2403 strerror(errno));
2407 g_free(buf);
2408 return result;
2411 static int coroutine_fn raw_thread_pool_submit(ThreadPoolFunc func, void *arg)
2413 return thread_pool_submit_co(func, arg);
2417 * Check if all memory in this vector is sector aligned.
2419 static bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2421 int i;
2422 size_t alignment = bdrv_min_mem_align(bs);
2423 size_t len = bs->bl.request_alignment;
2424 IO_CODE();
2426 for (i = 0; i < qiov->niov; i++) {
2427 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2428 return false;
2430 if (qiov->iov[i].iov_len % len) {
2431 return false;
2435 return true;
2438 #ifdef CONFIG_LINUX_IO_URING
2439 static inline bool raw_check_linux_io_uring(BDRVRawState *s)
2441 Error *local_err = NULL;
2442 AioContext *ctx;
2444 if (!s->use_linux_io_uring) {
2445 return false;
2448 ctx = qemu_get_current_aio_context();
2449 if (unlikely(!aio_setup_linux_io_uring(ctx, &local_err))) {
2450 error_reportf_err(local_err, "Unable to use linux io_uring, "
2451 "falling back to thread pool: ");
2452 s->use_linux_io_uring = false;
2453 return false;
2455 return true;
2457 #endif
2459 #ifdef CONFIG_LINUX_AIO
2460 static inline bool raw_check_linux_aio(BDRVRawState *s)
2462 Error *local_err = NULL;
2463 AioContext *ctx;
2465 if (!s->use_linux_aio) {
2466 return false;
2469 ctx = qemu_get_current_aio_context();
2470 if (unlikely(!aio_setup_linux_aio(ctx, &local_err))) {
2471 error_reportf_err(local_err, "Unable to use Linux AIO, "
2472 "falling back to thread pool: ");
2473 s->use_linux_aio = false;
2474 return false;
2476 return true;
2478 #endif
2480 static int coroutine_fn raw_co_prw(BlockDriverState *bs, int64_t *offset_ptr,
2481 uint64_t bytes, QEMUIOVector *qiov, int type)
2483 BDRVRawState *s = bs->opaque;
2484 RawPosixAIOData acb;
2485 int ret;
2486 uint64_t offset = *offset_ptr;
2488 if (fd_open(bs) < 0)
2489 return -EIO;
2490 #if defined(CONFIG_BLKZONED)
2491 if ((type & (QEMU_AIO_WRITE | QEMU_AIO_ZONE_APPEND)) &&
2492 bs->bl.zoned != BLK_Z_NONE) {
2493 qemu_co_mutex_lock(&bs->wps->colock);
2494 if (type & QEMU_AIO_ZONE_APPEND) {
2495 int index = offset / bs->bl.zone_size;
2496 offset = bs->wps->wp[index];
2499 #endif
2502 * When using O_DIRECT, the request must be aligned to be able to use
2503 * either libaio or io_uring interface. If not fail back to regular thread
2504 * pool read/write code which emulates this for us if we
2505 * set QEMU_AIO_MISALIGNED.
2507 if (s->needs_alignment && !bdrv_qiov_is_aligned(bs, qiov)) {
2508 type |= QEMU_AIO_MISALIGNED;
2509 #ifdef CONFIG_LINUX_IO_URING
2510 } else if (raw_check_linux_io_uring(s)) {
2511 assert(qiov->size == bytes);
2512 ret = luring_co_submit(bs, s->fd, offset, qiov, type);
2513 goto out;
2514 #endif
2515 #ifdef CONFIG_LINUX_AIO
2516 } else if (raw_check_linux_aio(s)) {
2517 assert(qiov->size == bytes);
2518 ret = laio_co_submit(s->fd, offset, qiov, type,
2519 s->aio_max_batch);
2520 goto out;
2521 #endif
2524 acb = (RawPosixAIOData) {
2525 .bs = bs,
2526 .aio_fildes = s->fd,
2527 .aio_type = type,
2528 .aio_offset = offset,
2529 .aio_nbytes = bytes,
2530 .io = {
2531 .iov = qiov->iov,
2532 .niov = qiov->niov,
2536 assert(qiov->size == bytes);
2537 ret = raw_thread_pool_submit(handle_aiocb_rw, &acb);
2538 goto out; /* Avoid the compiler err of unused label */
2540 out:
2541 #if defined(CONFIG_BLKZONED)
2542 if ((type & (QEMU_AIO_WRITE | QEMU_AIO_ZONE_APPEND)) &&
2543 bs->bl.zoned != BLK_Z_NONE) {
2544 BlockZoneWps *wps = bs->wps;
2545 if (ret == 0) {
2546 uint64_t *wp = &wps->wp[offset / bs->bl.zone_size];
2547 if (!BDRV_ZT_IS_CONV(*wp)) {
2548 if (type & QEMU_AIO_ZONE_APPEND) {
2549 *offset_ptr = *wp;
2550 trace_zbd_zone_append_complete(bs, *offset_ptr
2551 >> BDRV_SECTOR_BITS);
2553 /* Advance the wp if needed */
2554 if (offset + bytes > *wp) {
2555 *wp = offset + bytes;
2558 } else {
2560 * write and append write are not allowed to cross zone boundaries
2562 update_zones_wp(bs, s->fd, offset, 1);
2565 qemu_co_mutex_unlock(&wps->colock);
2567 #endif
2568 return ret;
2571 static int coroutine_fn raw_co_preadv(BlockDriverState *bs, int64_t offset,
2572 int64_t bytes, QEMUIOVector *qiov,
2573 BdrvRequestFlags flags)
2575 return raw_co_prw(bs, &offset, bytes, qiov, QEMU_AIO_READ);
2578 static int coroutine_fn raw_co_pwritev(BlockDriverState *bs, int64_t offset,
2579 int64_t bytes, QEMUIOVector *qiov,
2580 BdrvRequestFlags flags)
2582 return raw_co_prw(bs, &offset, bytes, qiov, QEMU_AIO_WRITE);
2585 static int coroutine_fn raw_co_flush_to_disk(BlockDriverState *bs)
2587 BDRVRawState *s = bs->opaque;
2588 RawPosixAIOData acb;
2589 int ret;
2591 ret = fd_open(bs);
2592 if (ret < 0) {
2593 return ret;
2596 acb = (RawPosixAIOData) {
2597 .bs = bs,
2598 .aio_fildes = s->fd,
2599 .aio_type = QEMU_AIO_FLUSH,
2602 #ifdef CONFIG_LINUX_IO_URING
2603 if (raw_check_linux_io_uring(s)) {
2604 return luring_co_submit(bs, s->fd, 0, NULL, QEMU_AIO_FLUSH);
2606 #endif
2607 return raw_thread_pool_submit(handle_aiocb_flush, &acb);
2610 static void raw_close(BlockDriverState *bs)
2612 BDRVRawState *s = bs->opaque;
2614 if (s->fd >= 0) {
2615 #if defined(CONFIG_BLKZONED)
2616 g_free(bs->wps);
2617 #endif
2618 qemu_close(s->fd);
2619 s->fd = -1;
2624 * Truncates the given regular file @fd to @offset and, when growing, fills the
2625 * new space according to @prealloc.
2627 * Returns: 0 on success, -errno on failure.
2629 static int coroutine_fn
2630 raw_regular_truncate(BlockDriverState *bs, int fd, int64_t offset,
2631 PreallocMode prealloc, Error **errp)
2633 RawPosixAIOData acb;
2635 acb = (RawPosixAIOData) {
2636 .bs = bs,
2637 .aio_fildes = fd,
2638 .aio_type = QEMU_AIO_TRUNCATE,
2639 .aio_offset = offset,
2640 .truncate = {
2641 .prealloc = prealloc,
2642 .errp = errp,
2646 return raw_thread_pool_submit(handle_aiocb_truncate, &acb);
2649 static int coroutine_fn raw_co_truncate(BlockDriverState *bs, int64_t offset,
2650 bool exact, PreallocMode prealloc,
2651 BdrvRequestFlags flags, Error **errp)
2653 BDRVRawState *s = bs->opaque;
2654 struct stat st;
2655 int ret;
2657 if (fstat(s->fd, &st)) {
2658 ret = -errno;
2659 error_setg_errno(errp, -ret, "Failed to fstat() the file");
2660 return ret;
2663 if (S_ISREG(st.st_mode)) {
2664 /* Always resizes to the exact @offset */
2665 return raw_regular_truncate(bs, s->fd, offset, prealloc, errp);
2668 if (prealloc != PREALLOC_MODE_OFF) {
2669 error_setg(errp, "Preallocation mode '%s' unsupported for this "
2670 "non-regular file", PreallocMode_str(prealloc));
2671 return -ENOTSUP;
2674 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2675 int64_t cur_length = raw_getlength(bs);
2677 if (offset != cur_length && exact) {
2678 error_setg(errp, "Cannot resize device files");
2679 return -ENOTSUP;
2680 } else if (offset > cur_length) {
2681 error_setg(errp, "Cannot grow device files");
2682 return -EINVAL;
2684 } else {
2685 error_setg(errp, "Resizing this file is not supported");
2686 return -ENOTSUP;
2689 return 0;
2692 #ifdef __OpenBSD__
2693 static int64_t raw_getlength(BlockDriverState *bs)
2695 BDRVRawState *s = bs->opaque;
2696 int fd = s->fd;
2697 struct stat st;
2699 if (fstat(fd, &st))
2700 return -errno;
2701 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2702 struct disklabel dl;
2704 if (ioctl(fd, DIOCGDINFO, &dl))
2705 return -errno;
2706 return (uint64_t)dl.d_secsize *
2707 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2708 } else
2709 return st.st_size;
2711 #elif defined(__NetBSD__)
2712 static int64_t raw_getlength(BlockDriverState *bs)
2714 BDRVRawState *s = bs->opaque;
2715 int fd = s->fd;
2716 struct stat st;
2718 if (fstat(fd, &st))
2719 return -errno;
2720 if (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) {
2721 struct dkwedge_info dkw;
2723 if (ioctl(fd, DIOCGWEDGEINFO, &dkw) != -1) {
2724 return dkw.dkw_size * 512;
2725 } else {
2726 struct disklabel dl;
2728 if (ioctl(fd, DIOCGDINFO, &dl))
2729 return -errno;
2730 return (uint64_t)dl.d_secsize *
2731 dl.d_partitions[DISKPART(st.st_rdev)].p_size;
2733 } else
2734 return st.st_size;
2736 #elif defined(__sun__)
2737 static int64_t raw_getlength(BlockDriverState *bs)
2739 BDRVRawState *s = bs->opaque;
2740 struct dk_minfo minfo;
2741 int ret;
2742 int64_t size;
2744 ret = fd_open(bs);
2745 if (ret < 0) {
2746 return ret;
2750 * Use the DKIOCGMEDIAINFO ioctl to read the size.
2752 ret = ioctl(s->fd, DKIOCGMEDIAINFO, &minfo);
2753 if (ret != -1) {
2754 return minfo.dki_lbsize * minfo.dki_capacity;
2758 * There are reports that lseek on some devices fails, but
2759 * irc discussion said that contingency on contingency was overkill.
2761 size = lseek(s->fd, 0, SEEK_END);
2762 if (size < 0) {
2763 return -errno;
2765 return size;
2767 #elif defined(CONFIG_BSD)
2768 static int64_t raw_getlength(BlockDriverState *bs)
2770 BDRVRawState *s = bs->opaque;
2771 int fd = s->fd;
2772 int64_t size;
2773 struct stat sb;
2774 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2775 int reopened = 0;
2776 #endif
2777 int ret;
2779 ret = fd_open(bs);
2780 if (ret < 0)
2781 return ret;
2783 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
2784 again:
2785 #endif
2786 if (!fstat(fd, &sb) && (S_IFCHR & sb.st_mode)) {
2787 size = 0;
2788 #ifdef DIOCGMEDIASIZE
2789 if (ioctl(fd, DIOCGMEDIASIZE, (off_t *)&size)) {
2790 size = 0;
2792 #endif
2793 #ifdef DIOCGPART
2794 if (size == 0) {
2795 struct partinfo pi;
2796 if (ioctl(fd, DIOCGPART, &pi) == 0) {
2797 size = pi.media_size;
2800 #endif
2801 #if defined(DKIOCGETBLOCKCOUNT) && defined(DKIOCGETBLOCKSIZE)
2802 if (size == 0) {
2803 uint64_t sectors = 0;
2804 uint32_t sector_size = 0;
2806 if (ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors) == 0
2807 && ioctl(fd, DKIOCGETBLOCKSIZE, &sector_size) == 0) {
2808 size = sectors * sector_size;
2811 #endif
2812 if (size == 0) {
2813 size = lseek(fd, 0LL, SEEK_END);
2815 if (size < 0) {
2816 return -errno;
2818 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
2819 switch(s->type) {
2820 case FTYPE_CD:
2821 /* XXX FreeBSD acd returns UINT_MAX sectors for an empty drive */
2822 if (size == 2048LL * (unsigned)-1)
2823 size = 0;
2824 /* XXX no disc? maybe we need to reopen... */
2825 if (size <= 0 && !reopened && cdrom_reopen(bs) >= 0) {
2826 reopened = 1;
2827 goto again;
2830 #endif
2831 } else {
2832 size = lseek(fd, 0, SEEK_END);
2833 if (size < 0) {
2834 return -errno;
2837 return size;
2839 #else
2840 static int64_t raw_getlength(BlockDriverState *bs)
2842 BDRVRawState *s = bs->opaque;
2843 int ret;
2844 int64_t size;
2846 ret = fd_open(bs);
2847 if (ret < 0) {
2848 return ret;
2851 size = lseek(s->fd, 0, SEEK_END);
2852 if (size < 0) {
2853 return -errno;
2855 return size;
2857 #endif
2859 static int64_t coroutine_fn raw_co_getlength(BlockDriverState *bs)
2861 return raw_getlength(bs);
2864 static int64_t coroutine_fn raw_co_get_allocated_file_size(BlockDriverState *bs)
2866 struct stat st;
2867 BDRVRawState *s = bs->opaque;
2869 if (fstat(s->fd, &st) < 0) {
2870 return -errno;
2872 return (int64_t)st.st_blocks * 512;
2875 static int coroutine_fn
2876 raw_co_create(BlockdevCreateOptions *options, Error **errp)
2878 BlockdevCreateOptionsFile *file_opts;
2879 Error *local_err = NULL;
2880 int fd;
2881 uint64_t perm, shared;
2882 int result = 0;
2884 /* Validate options and set default values */
2885 assert(options->driver == BLOCKDEV_DRIVER_FILE);
2886 file_opts = &options->u.file;
2888 if (!file_opts->has_nocow) {
2889 file_opts->nocow = false;
2891 if (!file_opts->has_preallocation) {
2892 file_opts->preallocation = PREALLOC_MODE_OFF;
2894 if (!file_opts->has_extent_size_hint) {
2895 file_opts->extent_size_hint = 1 * MiB;
2897 if (file_opts->extent_size_hint > UINT32_MAX) {
2898 result = -EINVAL;
2899 error_setg(errp, "Extent size hint is too large");
2900 goto out;
2903 /* Create file */
2904 fd = qemu_create(file_opts->filename, O_RDWR | O_BINARY, 0644, errp);
2905 if (fd < 0) {
2906 result = -errno;
2907 goto out;
2910 /* Take permissions: We want to discard everything, so we need
2911 * BLK_PERM_WRITE; and truncation to the desired size requires
2912 * BLK_PERM_RESIZE.
2913 * On the other hand, we cannot share the RESIZE permission
2914 * because we promise that after this function, the file has the
2915 * size given in the options. If someone else were to resize it
2916 * concurrently, we could not guarantee that.
2917 * Note that after this function, we can no longer guarantee that
2918 * the file is not touched by a third party, so it may be resized
2919 * then. */
2920 perm = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2921 shared = BLK_PERM_ALL & ~BLK_PERM_RESIZE;
2923 /* Step one: Take locks */
2924 result = raw_apply_lock_bytes(NULL, fd, perm, ~shared, false, errp);
2925 if (result < 0) {
2926 goto out_close;
2929 /* Step two: Check that nobody else has taken conflicting locks */
2930 result = raw_check_lock_bytes(fd, perm, shared, errp);
2931 if (result < 0) {
2932 error_append_hint(errp,
2933 "Is another process using the image [%s]?\n",
2934 file_opts->filename);
2935 goto out_unlock;
2938 /* Clear the file by truncating it to 0 */
2939 result = raw_regular_truncate(NULL, fd, 0, PREALLOC_MODE_OFF, errp);
2940 if (result < 0) {
2941 goto out_unlock;
2944 if (file_opts->nocow) {
2945 #ifdef __linux__
2946 /* Set NOCOW flag to solve performance issue on fs like btrfs.
2947 * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value
2948 * will be ignored since any failure of this operation should not
2949 * block the left work.
2951 int attr;
2952 if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {
2953 attr |= FS_NOCOW_FL;
2954 ioctl(fd, FS_IOC_SETFLAGS, &attr);
2956 #endif
2958 #ifdef FS_IOC_FSSETXATTR
2960 * Try to set the extent size hint. Failure is not fatal, and a warning is
2961 * only printed if the option was explicitly specified.
2964 struct fsxattr attr;
2965 result = ioctl(fd, FS_IOC_FSGETXATTR, &attr);
2966 if (result == 0) {
2967 attr.fsx_xflags |= FS_XFLAG_EXTSIZE;
2968 attr.fsx_extsize = file_opts->extent_size_hint;
2969 result = ioctl(fd, FS_IOC_FSSETXATTR, &attr);
2971 if (result < 0 && file_opts->has_extent_size_hint &&
2972 file_opts->extent_size_hint)
2974 warn_report("Failed to set extent size hint: %s",
2975 strerror(errno));
2978 #endif
2980 /* Resize and potentially preallocate the file to the desired
2981 * final size */
2982 result = raw_regular_truncate(NULL, fd, file_opts->size,
2983 file_opts->preallocation, errp);
2984 if (result < 0) {
2985 goto out_unlock;
2988 out_unlock:
2989 raw_apply_lock_bytes(NULL, fd, 0, 0, true, &local_err);
2990 if (local_err) {
2991 /* The above call should not fail, and if it does, that does
2992 * not mean the whole creation operation has failed. So
2993 * report it the user for their convenience, but do not report
2994 * it to the caller. */
2995 warn_report_err(local_err);
2998 out_close:
2999 if (qemu_close(fd) != 0 && result == 0) {
3000 result = -errno;
3001 error_setg_errno(errp, -result, "Could not close the new file");
3003 out:
3004 return result;
3007 static int coroutine_fn GRAPH_RDLOCK
3008 raw_co_create_opts(BlockDriver *drv, const char *filename,
3009 QemuOpts *opts, Error **errp)
3011 BlockdevCreateOptions options;
3012 int64_t total_size = 0;
3013 int64_t extent_size_hint = 0;
3014 bool has_extent_size_hint = false;
3015 bool nocow = false;
3016 PreallocMode prealloc;
3017 char *buf = NULL;
3018 Error *local_err = NULL;
3020 /* Skip file: protocol prefix */
3021 strstart(filename, "file:", &filename);
3023 /* Read out options */
3024 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
3025 BDRV_SECTOR_SIZE);
3026 if (qemu_opt_get(opts, BLOCK_OPT_EXTENT_SIZE_HINT)) {
3027 has_extent_size_hint = true;
3028 extent_size_hint =
3029 qemu_opt_get_size_del(opts, BLOCK_OPT_EXTENT_SIZE_HINT, -1);
3031 nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);
3032 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
3033 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
3034 PREALLOC_MODE_OFF, &local_err);
3035 g_free(buf);
3036 if (local_err) {
3037 error_propagate(errp, local_err);
3038 return -EINVAL;
3041 options = (BlockdevCreateOptions) {
3042 .driver = BLOCKDEV_DRIVER_FILE,
3043 .u.file = {
3044 .filename = (char *) filename,
3045 .size = total_size,
3046 .has_preallocation = true,
3047 .preallocation = prealloc,
3048 .has_nocow = true,
3049 .nocow = nocow,
3050 .has_extent_size_hint = has_extent_size_hint,
3051 .extent_size_hint = extent_size_hint,
3054 return raw_co_create(&options, errp);
3057 static int coroutine_fn raw_co_delete_file(BlockDriverState *bs,
3058 Error **errp)
3060 struct stat st;
3061 int ret;
3063 if (!(stat(bs->filename, &st) == 0) || !S_ISREG(st.st_mode)) {
3064 error_setg_errno(errp, ENOENT, "%s is not a regular file",
3065 bs->filename);
3066 return -ENOENT;
3069 ret = unlink(bs->filename);
3070 if (ret < 0) {
3071 ret = -errno;
3072 error_setg_errno(errp, -ret, "Error when deleting file %s",
3073 bs->filename);
3076 return ret;
3080 * Find allocation range in @bs around offset @start.
3081 * May change underlying file descriptor's file offset.
3082 * If @start is not in a hole, store @start in @data, and the
3083 * beginning of the next hole in @hole, and return 0.
3084 * If @start is in a non-trailing hole, store @start in @hole and the
3085 * beginning of the next non-hole in @data, and return 0.
3086 * If @start is in a trailing hole or beyond EOF, return -ENXIO.
3087 * If we can't find out, return a negative errno other than -ENXIO.
3089 static int find_allocation(BlockDriverState *bs, off_t start,
3090 off_t *data, off_t *hole)
3092 #if defined SEEK_HOLE && defined SEEK_DATA
3093 BDRVRawState *s = bs->opaque;
3094 off_t offs;
3097 * SEEK_DATA cases:
3098 * D1. offs == start: start is in data
3099 * D2. offs > start: start is in a hole, next data at offs
3100 * D3. offs < 0, errno = ENXIO: either start is in a trailing hole
3101 * or start is beyond EOF
3102 * If the latter happens, the file has been truncated behind
3103 * our back since we opened it. All bets are off then.
3104 * Treating like a trailing hole is simplest.
3105 * D4. offs < 0, errno != ENXIO: we learned nothing
3107 offs = lseek(s->fd, start, SEEK_DATA);
3108 if (offs < 0) {
3109 return -errno; /* D3 or D4 */
3112 if (offs < start) {
3113 /* This is not a valid return by lseek(). We are safe to just return
3114 * -EIO in this case, and we'll treat it like D4. */
3115 return -EIO;
3118 if (offs > start) {
3119 /* D2: in hole, next data at offs */
3120 *hole = start;
3121 *data = offs;
3122 return 0;
3125 /* D1: in data, end not yet known */
3128 * SEEK_HOLE cases:
3129 * H1. offs == start: start is in a hole
3130 * If this happens here, a hole has been dug behind our back
3131 * since the previous lseek().
3132 * H2. offs > start: either start is in data, next hole at offs,
3133 * or start is in trailing hole, EOF at offs
3134 * Linux treats trailing holes like any other hole: offs ==
3135 * start. Solaris seeks to EOF instead: offs > start (blech).
3136 * If that happens here, a hole has been dug behind our back
3137 * since the previous lseek().
3138 * H3. offs < 0, errno = ENXIO: start is beyond EOF
3139 * If this happens, the file has been truncated behind our
3140 * back since we opened it. Treat it like a trailing hole.
3141 * H4. offs < 0, errno != ENXIO: we learned nothing
3142 * Pretend we know nothing at all, i.e. "forget" about D1.
3144 offs = lseek(s->fd, start, SEEK_HOLE);
3145 if (offs < 0) {
3146 return -errno; /* D1 and (H3 or H4) */
3149 if (offs < start) {
3150 /* This is not a valid return by lseek(). We are safe to just return
3151 * -EIO in this case, and we'll treat it like H4. */
3152 return -EIO;
3155 if (offs > start) {
3157 * D1 and H2: either in data, next hole at offs, or it was in
3158 * data but is now in a trailing hole. In the latter case,
3159 * all bets are off. Treating it as if it there was data all
3160 * the way to EOF is safe, so simply do that.
3162 *data = start;
3163 *hole = offs;
3164 return 0;
3167 /* D1 and H1 */
3168 return -EBUSY;
3169 #else
3170 return -ENOTSUP;
3171 #endif
3175 * Returns the allocation status of the specified offset.
3177 * The block layer guarantees 'offset' and 'bytes' are within bounds.
3179 * 'pnum' is set to the number of bytes (including and immediately following
3180 * the specified offset) that are known to be in the same
3181 * allocated/unallocated state.
3183 * 'bytes' is a soft cap for 'pnum'. If the information is free, 'pnum' may
3184 * well exceed it.
3186 static int coroutine_fn raw_co_block_status(BlockDriverState *bs,
3187 bool want_zero,
3188 int64_t offset,
3189 int64_t bytes, int64_t *pnum,
3190 int64_t *map,
3191 BlockDriverState **file)
3193 off_t data = 0, hole = 0;
3194 int ret;
3196 assert(QEMU_IS_ALIGNED(offset | bytes, bs->bl.request_alignment));
3198 ret = fd_open(bs);
3199 if (ret < 0) {
3200 return ret;
3203 if (!want_zero) {
3204 *pnum = bytes;
3205 *map = offset;
3206 *file = bs;
3207 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
3210 ret = find_allocation(bs, offset, &data, &hole);
3211 if (ret == -ENXIO) {
3212 /* Trailing hole */
3213 *pnum = bytes;
3214 ret = BDRV_BLOCK_ZERO;
3215 } else if (ret < 0) {
3216 /* No info available, so pretend there are no holes */
3217 *pnum = bytes;
3218 ret = BDRV_BLOCK_DATA;
3219 } else if (data == offset) {
3220 /* On a data extent, compute bytes to the end of the extent,
3221 * possibly including a partial sector at EOF. */
3222 *pnum = hole - offset;
3225 * We are not allowed to return partial sectors, though, so
3226 * round up if necessary.
3228 if (!QEMU_IS_ALIGNED(*pnum, bs->bl.request_alignment)) {
3229 int64_t file_length = raw_getlength(bs);
3230 if (file_length > 0) {
3231 /* Ignore errors, this is just a safeguard */
3232 assert(hole == file_length);
3234 *pnum = ROUND_UP(*pnum, bs->bl.request_alignment);
3237 ret = BDRV_BLOCK_DATA;
3238 } else {
3239 /* On a hole, compute bytes to the beginning of the next extent. */
3240 assert(hole == offset);
3241 *pnum = data - offset;
3242 ret = BDRV_BLOCK_ZERO;
3244 *map = offset;
3245 *file = bs;
3246 return ret | BDRV_BLOCK_OFFSET_VALID;
3249 #if defined(__linux__)
3250 /* Verify that the file is not in the page cache */
3251 static void check_cache_dropped(BlockDriverState *bs, Error **errp)
3253 const size_t window_size = 128 * 1024 * 1024;
3254 BDRVRawState *s = bs->opaque;
3255 void *window = NULL;
3256 size_t length = 0;
3257 unsigned char *vec;
3258 size_t page_size;
3259 off_t offset;
3260 off_t end;
3262 /* mincore(2) page status information requires 1 byte per page */
3263 page_size = sysconf(_SC_PAGESIZE);
3264 vec = g_malloc(DIV_ROUND_UP(window_size, page_size));
3266 end = raw_getlength(bs);
3268 for (offset = 0; offset < end; offset += window_size) {
3269 void *new_window;
3270 size_t new_length;
3271 size_t vec_end;
3272 size_t i;
3273 int ret;
3275 /* Unmap previous window if size has changed */
3276 new_length = MIN(end - offset, window_size);
3277 if (new_length != length) {
3278 munmap(window, length);
3279 window = NULL;
3280 length = 0;
3283 new_window = mmap(window, new_length, PROT_NONE, MAP_PRIVATE,
3284 s->fd, offset);
3285 if (new_window == MAP_FAILED) {
3286 error_setg_errno(errp, errno, "mmap failed");
3287 break;
3290 window = new_window;
3291 length = new_length;
3293 ret = mincore(window, length, vec);
3294 if (ret < 0) {
3295 error_setg_errno(errp, errno, "mincore failed");
3296 break;
3299 vec_end = DIV_ROUND_UP(length, page_size);
3300 for (i = 0; i < vec_end; i++) {
3301 if (vec[i] & 0x1) {
3302 break;
3305 if (i < vec_end) {
3306 error_setg(errp, "page cache still in use!");
3307 break;
3311 if (window) {
3312 munmap(window, length);
3315 g_free(vec);
3317 #endif /* __linux__ */
3319 static void coroutine_fn GRAPH_RDLOCK
3320 raw_co_invalidate_cache(BlockDriverState *bs, Error **errp)
3322 BDRVRawState *s = bs->opaque;
3323 int ret;
3325 ret = fd_open(bs);
3326 if (ret < 0) {
3327 error_setg_errno(errp, -ret, "The file descriptor is not open");
3328 return;
3331 if (!s->drop_cache) {
3332 return;
3335 if (s->open_flags & O_DIRECT) {
3336 return; /* No host kernel page cache */
3339 #if defined(__linux__)
3340 /* This sets the scene for the next syscall... */
3341 ret = bdrv_co_flush(bs);
3342 if (ret < 0) {
3343 error_setg_errno(errp, -ret, "flush failed");
3344 return;
3347 /* Linux does not invalidate pages that are dirty, locked, or mmapped by a
3348 * process. These limitations are okay because we just fsynced the file,
3349 * we don't use mmap, and the file should not be in use by other processes.
3351 ret = posix_fadvise(s->fd, 0, 0, POSIX_FADV_DONTNEED);
3352 if (ret != 0) { /* the return value is a positive errno */
3353 error_setg_errno(errp, ret, "fadvise failed");
3354 return;
3357 if (s->check_cache_dropped) {
3358 check_cache_dropped(bs, errp);
3360 #else /* __linux__ */
3361 /* Do nothing. Live migration to a remote host with cache.direct=off is
3362 * unsupported on other host operating systems. Cache consistency issues
3363 * may occur but no error is reported here, partly because that's the
3364 * historical behavior and partly because it's hard to differentiate valid
3365 * configurations that should not cause errors.
3367 #endif /* !__linux__ */
3370 static void raw_account_discard(BDRVRawState *s, uint64_t nbytes, int ret)
3372 if (ret) {
3373 s->stats.discard_nb_failed++;
3374 } else {
3375 s->stats.discard_nb_ok++;
3376 s->stats.discard_bytes_ok += nbytes;
3381 * zone report - Get a zone block device's information in the form
3382 * of an array of zone descriptors.
3383 * zones is an array of zone descriptors to hold zone information on reply;
3384 * offset can be any byte within the entire size of the device;
3385 * nr_zones is the maximum number of sectors the command should operate on.
3387 #if defined(CONFIG_BLKZONED)
3388 static int coroutine_fn raw_co_zone_report(BlockDriverState *bs, int64_t offset,
3389 unsigned int *nr_zones,
3390 BlockZoneDescriptor *zones) {
3391 BDRVRawState *s = bs->opaque;
3392 RawPosixAIOData acb = (RawPosixAIOData) {
3393 .bs = bs,
3394 .aio_fildes = s->fd,
3395 .aio_type = QEMU_AIO_ZONE_REPORT,
3396 .aio_offset = offset,
3397 .zone_report = {
3398 .nr_zones = nr_zones,
3399 .zones = zones,
3403 trace_zbd_zone_report(bs, *nr_zones, offset >> BDRV_SECTOR_BITS);
3404 return raw_thread_pool_submit(handle_aiocb_zone_report, &acb);
3406 #endif
3409 * zone management operations - Execute an operation on a zone
3411 #if defined(CONFIG_BLKZONED)
3412 static int coroutine_fn raw_co_zone_mgmt(BlockDriverState *bs, BlockZoneOp op,
3413 int64_t offset, int64_t len) {
3414 BDRVRawState *s = bs->opaque;
3415 RawPosixAIOData acb;
3416 int64_t zone_size, zone_size_mask;
3417 const char *op_name;
3418 unsigned long zo;
3419 int ret;
3420 BlockZoneWps *wps = bs->wps;
3421 int64_t capacity = bs->total_sectors << BDRV_SECTOR_BITS;
3423 zone_size = bs->bl.zone_size;
3424 zone_size_mask = zone_size - 1;
3425 if (offset & zone_size_mask) {
3426 error_report("sector offset %" PRId64 " is not aligned to zone size "
3427 "%" PRId64 "", offset / 512, zone_size / 512);
3428 return -EINVAL;
3431 if (((offset + len) < capacity && len & zone_size_mask) ||
3432 offset + len > capacity) {
3433 error_report("number of sectors %" PRId64 " is not aligned to zone size"
3434 " %" PRId64 "", len / 512, zone_size / 512);
3435 return -EINVAL;
3438 uint32_t i = offset / bs->bl.zone_size;
3439 uint32_t nrz = len / bs->bl.zone_size;
3440 uint64_t *wp = &wps->wp[i];
3441 if (BDRV_ZT_IS_CONV(*wp) && len != capacity) {
3442 error_report("zone mgmt operations are not allowed for conventional zones");
3443 return -EIO;
3446 switch (op) {
3447 case BLK_ZO_OPEN:
3448 op_name = "BLKOPENZONE";
3449 zo = BLKOPENZONE;
3450 break;
3451 case BLK_ZO_CLOSE:
3452 op_name = "BLKCLOSEZONE";
3453 zo = BLKCLOSEZONE;
3454 break;
3455 case BLK_ZO_FINISH:
3456 op_name = "BLKFINISHZONE";
3457 zo = BLKFINISHZONE;
3458 break;
3459 case BLK_ZO_RESET:
3460 op_name = "BLKRESETZONE";
3461 zo = BLKRESETZONE;
3462 break;
3463 default:
3464 error_report("Unsupported zone op: 0x%x", op);
3465 return -ENOTSUP;
3468 acb = (RawPosixAIOData) {
3469 .bs = bs,
3470 .aio_fildes = s->fd,
3471 .aio_type = QEMU_AIO_ZONE_MGMT,
3472 .aio_offset = offset,
3473 .aio_nbytes = len,
3474 .zone_mgmt = {
3475 .op = zo,
3479 trace_zbd_zone_mgmt(bs, op_name, offset >> BDRV_SECTOR_BITS,
3480 len >> BDRV_SECTOR_BITS);
3481 ret = raw_thread_pool_submit(handle_aiocb_zone_mgmt, &acb);
3482 if (ret != 0) {
3483 update_zones_wp(bs, s->fd, offset, nrz);
3484 error_report("ioctl %s failed %d", op_name, ret);
3485 return ret;
3488 if (zo == BLKRESETZONE && len == capacity) {
3489 ret = get_zones_wp(bs, s->fd, 0, bs->bl.nr_zones, 1);
3490 if (ret < 0) {
3491 error_report("reporting single wp failed");
3492 return ret;
3494 } else if (zo == BLKRESETZONE) {
3495 for (unsigned int j = 0; j < nrz; ++j) {
3496 wp[j] = offset + j * zone_size;
3498 } else if (zo == BLKFINISHZONE) {
3499 for (unsigned int j = 0; j < nrz; ++j) {
3500 /* The zoned device allows the last zone smaller that the
3501 * zone size. */
3502 wp[j] = MIN(offset + (j + 1) * zone_size, offset + len);
3506 return ret;
3508 #endif
3510 #if defined(CONFIG_BLKZONED)
3511 static int coroutine_fn raw_co_zone_append(BlockDriverState *bs,
3512 int64_t *offset,
3513 QEMUIOVector *qiov,
3514 BdrvRequestFlags flags) {
3515 assert(flags == 0);
3516 int64_t zone_size_mask = bs->bl.zone_size - 1;
3517 int64_t iov_len = 0;
3518 int64_t len = 0;
3520 if (*offset & zone_size_mask) {
3521 error_report("sector offset %" PRId64 " is not aligned to zone size "
3522 "%" PRId32 "", *offset / 512, bs->bl.zone_size / 512);
3523 return -EINVAL;
3526 int64_t wg = bs->bl.write_granularity;
3527 int64_t wg_mask = wg - 1;
3528 for (int i = 0; i < qiov->niov; i++) {
3529 iov_len = qiov->iov[i].iov_len;
3530 if (iov_len & wg_mask) {
3531 error_report("len of IOVector[%d] %" PRId64 " is not aligned to "
3532 "block size %" PRId64 "", i, iov_len, wg);
3533 return -EINVAL;
3535 len += iov_len;
3538 trace_zbd_zone_append(bs, *offset >> BDRV_SECTOR_BITS);
3539 return raw_co_prw(bs, offset, len, qiov, QEMU_AIO_ZONE_APPEND);
3541 #endif
3543 static coroutine_fn int
3544 raw_do_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes,
3545 bool blkdev)
3547 BDRVRawState *s = bs->opaque;
3548 RawPosixAIOData acb;
3549 int ret;
3551 acb = (RawPosixAIOData) {
3552 .bs = bs,
3553 .aio_fildes = s->fd,
3554 .aio_type = QEMU_AIO_DISCARD,
3555 .aio_offset = offset,
3556 .aio_nbytes = bytes,
3559 if (blkdev) {
3560 acb.aio_type |= QEMU_AIO_BLKDEV;
3563 ret = raw_thread_pool_submit(handle_aiocb_discard, &acb);
3564 raw_account_discard(s, bytes, ret);
3565 return ret;
3568 static coroutine_fn int
3569 raw_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
3571 return raw_do_pdiscard(bs, offset, bytes, false);
3574 static int coroutine_fn
3575 raw_do_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
3576 BdrvRequestFlags flags, bool blkdev)
3578 BDRVRawState *s = bs->opaque;
3579 RawPosixAIOData acb;
3580 ThreadPoolFunc *handler;
3582 #ifdef CONFIG_FALLOCATE
3583 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3584 BdrvTrackedRequest *req;
3587 * This is a workaround for a bug in the Linux XFS driver,
3588 * where writes submitted through the AIO interface will be
3589 * discarded if they happen beyond a concurrently running
3590 * fallocate() that increases the file length (i.e., both the
3591 * write and the fallocate() happen beyond the EOF).
3593 * To work around it, we extend the tracked request for this
3594 * zero write until INT64_MAX (effectively infinity), and mark
3595 * it as serializing.
3597 * We have to enable this workaround for all filesystems and
3598 * AIO modes (not just XFS with aio=native), because for
3599 * remote filesystems we do not know the host configuration.
3602 req = bdrv_co_get_self_request(bs);
3603 assert(req);
3604 assert(req->type == BDRV_TRACKED_WRITE);
3605 assert(req->offset <= offset);
3606 assert(req->offset + req->bytes >= offset + bytes);
3608 req->bytes = BDRV_MAX_LENGTH - req->offset;
3610 bdrv_check_request(req->offset, req->bytes, &error_abort);
3612 bdrv_make_request_serialising(req, bs->bl.request_alignment);
3614 #endif
3616 acb = (RawPosixAIOData) {
3617 .bs = bs,
3618 .aio_fildes = s->fd,
3619 .aio_type = QEMU_AIO_WRITE_ZEROES,
3620 .aio_offset = offset,
3621 .aio_nbytes = bytes,
3624 if (blkdev) {
3625 acb.aio_type |= QEMU_AIO_BLKDEV;
3627 if (flags & BDRV_REQ_NO_FALLBACK) {
3628 acb.aio_type |= QEMU_AIO_NO_FALLBACK;
3631 if (flags & BDRV_REQ_MAY_UNMAP) {
3632 acb.aio_type |= QEMU_AIO_DISCARD;
3633 handler = handle_aiocb_write_zeroes_unmap;
3634 } else {
3635 handler = handle_aiocb_write_zeroes;
3638 return raw_thread_pool_submit(handler, &acb);
3641 static int coroutine_fn raw_co_pwrite_zeroes(
3642 BlockDriverState *bs, int64_t offset,
3643 int64_t bytes, BdrvRequestFlags flags)
3645 return raw_do_pwrite_zeroes(bs, offset, bytes, flags, false);
3648 static int coroutine_fn
3649 raw_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3651 return 0;
3654 static ImageInfoSpecific *raw_get_specific_info(BlockDriverState *bs,
3655 Error **errp)
3657 ImageInfoSpecificFile *file_info = g_new0(ImageInfoSpecificFile, 1);
3658 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
3660 *spec_info = (ImageInfoSpecific){
3661 .type = IMAGE_INFO_SPECIFIC_KIND_FILE,
3662 .u.file.data = file_info,
3665 #ifdef FS_IOC_FSGETXATTR
3667 BDRVRawState *s = bs->opaque;
3668 struct fsxattr attr;
3669 int ret;
3671 ret = ioctl(s->fd, FS_IOC_FSGETXATTR, &attr);
3672 if (!ret && attr.fsx_extsize != 0) {
3673 file_info->has_extent_size_hint = true;
3674 file_info->extent_size_hint = attr.fsx_extsize;
3677 #endif
3679 return spec_info;
3682 static BlockStatsSpecificFile get_blockstats_specific_file(BlockDriverState *bs)
3684 BDRVRawState *s = bs->opaque;
3685 return (BlockStatsSpecificFile) {
3686 .discard_nb_ok = s->stats.discard_nb_ok,
3687 .discard_nb_failed = s->stats.discard_nb_failed,
3688 .discard_bytes_ok = s->stats.discard_bytes_ok,
3692 static BlockStatsSpecific *raw_get_specific_stats(BlockDriverState *bs)
3694 BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
3696 stats->driver = BLOCKDEV_DRIVER_FILE;
3697 stats->u.file = get_blockstats_specific_file(bs);
3699 return stats;
3702 #if defined(HAVE_HOST_BLOCK_DEVICE)
3703 static BlockStatsSpecific *hdev_get_specific_stats(BlockDriverState *bs)
3705 BlockStatsSpecific *stats = g_new(BlockStatsSpecific, 1);
3707 stats->driver = BLOCKDEV_DRIVER_HOST_DEVICE;
3708 stats->u.host_device = get_blockstats_specific_file(bs);
3710 return stats;
3712 #endif /* HAVE_HOST_BLOCK_DEVICE */
3714 static QemuOptsList raw_create_opts = {
3715 .name = "raw-create-opts",
3716 .head = QTAILQ_HEAD_INITIALIZER(raw_create_opts.head),
3717 .desc = {
3719 .name = BLOCK_OPT_SIZE,
3720 .type = QEMU_OPT_SIZE,
3721 .help = "Virtual disk size"
3724 .name = BLOCK_OPT_NOCOW,
3725 .type = QEMU_OPT_BOOL,
3726 .help = "Turn off copy-on-write (valid only on btrfs)"
3729 .name = BLOCK_OPT_PREALLOC,
3730 .type = QEMU_OPT_STRING,
3731 .help = "Preallocation mode (allowed values: off"
3732 #ifdef CONFIG_POSIX_FALLOCATE
3733 ", falloc"
3734 #endif
3735 ", full)"
3738 .name = BLOCK_OPT_EXTENT_SIZE_HINT,
3739 .type = QEMU_OPT_SIZE,
3740 .help = "Extent size hint for the image file, 0 to disable"
3742 { /* end of list */ }
3746 static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
3747 Error **errp)
3749 BDRVRawState *s = bs->opaque;
3750 int input_flags = s->reopen_state ? s->reopen_state->flags : bs->open_flags;
3751 int open_flags;
3752 int ret;
3754 /* We may need a new fd if auto-read-only switches the mode */
3755 ret = raw_reconfigure_getfd(bs, input_flags, &open_flags, perm,
3756 false, errp);
3757 if (ret < 0) {
3758 return ret;
3759 } else if (ret != s->fd) {
3760 Error *local_err = NULL;
3763 * Fail already check_perm() if we can't get a working O_DIRECT
3764 * alignment with the new fd.
3766 raw_probe_alignment(bs, ret, &local_err);
3767 if (local_err) {
3768 error_propagate(errp, local_err);
3769 return -EINVAL;
3772 s->perm_change_fd = ret;
3773 s->perm_change_flags = open_flags;
3776 /* Prepare permissions on old fd to avoid conflicts between old and new,
3777 * but keep everything locked that new will need. */
3778 ret = raw_handle_perm_lock(bs, RAW_PL_PREPARE, perm, shared, errp);
3779 if (ret < 0) {
3780 goto fail;
3783 /* Copy locks to the new fd */
3784 if (s->perm_change_fd && s->use_lock) {
3785 ret = raw_apply_lock_bytes(NULL, s->perm_change_fd, perm, ~shared,
3786 false, errp);
3787 if (ret < 0) {
3788 raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
3789 goto fail;
3792 return 0;
3794 fail:
3795 if (s->perm_change_fd) {
3796 qemu_close(s->perm_change_fd);
3798 s->perm_change_fd = 0;
3799 return ret;
3802 static void raw_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared)
3804 BDRVRawState *s = bs->opaque;
3806 /* For reopen, we have already switched to the new fd (.bdrv_set_perm is
3807 * called after .bdrv_reopen_commit) */
3808 if (s->perm_change_fd && s->fd != s->perm_change_fd) {
3809 qemu_close(s->fd);
3810 s->fd = s->perm_change_fd;
3811 s->open_flags = s->perm_change_flags;
3813 s->perm_change_fd = 0;
3815 raw_handle_perm_lock(bs, RAW_PL_COMMIT, perm, shared, NULL);
3816 s->perm = perm;
3817 s->shared_perm = shared;
3820 static void raw_abort_perm_update(BlockDriverState *bs)
3822 BDRVRawState *s = bs->opaque;
3824 /* For reopen, .bdrv_reopen_abort is called afterwards and will close
3825 * the file descriptor. */
3826 if (s->perm_change_fd) {
3827 qemu_close(s->perm_change_fd);
3829 s->perm_change_fd = 0;
3831 raw_handle_perm_lock(bs, RAW_PL_ABORT, 0, 0, NULL);
3834 static int coroutine_fn GRAPH_RDLOCK raw_co_copy_range_from(
3835 BlockDriverState *bs, BdrvChild *src, int64_t src_offset,
3836 BdrvChild *dst, int64_t dst_offset, int64_t bytes,
3837 BdrvRequestFlags read_flags, BdrvRequestFlags write_flags)
3839 return bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3840 read_flags, write_flags);
3843 static int coroutine_fn GRAPH_RDLOCK
3844 raw_co_copy_range_to(BlockDriverState *bs,
3845 BdrvChild *src, int64_t src_offset,
3846 BdrvChild *dst, int64_t dst_offset,
3847 int64_t bytes, BdrvRequestFlags read_flags,
3848 BdrvRequestFlags write_flags)
3850 RawPosixAIOData acb;
3851 BDRVRawState *s = bs->opaque;
3852 BDRVRawState *src_s;
3854 assert(dst->bs == bs);
3855 if (src->bs->drv->bdrv_co_copy_range_to != raw_co_copy_range_to) {
3856 return -ENOTSUP;
3859 src_s = src->bs->opaque;
3860 if (fd_open(src->bs) < 0 || fd_open(dst->bs) < 0) {
3861 return -EIO;
3864 acb = (RawPosixAIOData) {
3865 .bs = bs,
3866 .aio_type = QEMU_AIO_COPY_RANGE,
3867 .aio_fildes = src_s->fd,
3868 .aio_offset = src_offset,
3869 .aio_nbytes = bytes,
3870 .copy_range = {
3871 .aio_fd2 = s->fd,
3872 .aio_offset2 = dst_offset,
3876 return raw_thread_pool_submit(handle_aiocb_copy_range, &acb);
3879 BlockDriver bdrv_file = {
3880 .format_name = "file",
3881 .protocol_name = "file",
3882 .instance_size = sizeof(BDRVRawState),
3883 .bdrv_needs_filename = true,
3884 .bdrv_probe = NULL, /* no probe for protocols */
3885 .bdrv_parse_filename = raw_parse_filename,
3886 .bdrv_file_open = raw_open,
3887 .bdrv_reopen_prepare = raw_reopen_prepare,
3888 .bdrv_reopen_commit = raw_reopen_commit,
3889 .bdrv_reopen_abort = raw_reopen_abort,
3890 .bdrv_close = raw_close,
3891 .bdrv_co_create = raw_co_create,
3892 .bdrv_co_create_opts = raw_co_create_opts,
3893 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3894 .bdrv_co_block_status = raw_co_block_status,
3895 .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
3896 .bdrv_co_pwrite_zeroes = raw_co_pwrite_zeroes,
3897 .bdrv_co_delete_file = raw_co_delete_file,
3899 .bdrv_co_preadv = raw_co_preadv,
3900 .bdrv_co_pwritev = raw_co_pwritev,
3901 .bdrv_co_flush_to_disk = raw_co_flush_to_disk,
3902 .bdrv_co_pdiscard = raw_co_pdiscard,
3903 .bdrv_co_copy_range_from = raw_co_copy_range_from,
3904 .bdrv_co_copy_range_to = raw_co_copy_range_to,
3905 .bdrv_refresh_limits = raw_refresh_limits,
3907 .bdrv_co_truncate = raw_co_truncate,
3908 .bdrv_co_getlength = raw_co_getlength,
3909 .bdrv_co_get_info = raw_co_get_info,
3910 .bdrv_get_specific_info = raw_get_specific_info,
3911 .bdrv_co_get_allocated_file_size = raw_co_get_allocated_file_size,
3912 .bdrv_get_specific_stats = raw_get_specific_stats,
3913 .bdrv_check_perm = raw_check_perm,
3914 .bdrv_set_perm = raw_set_perm,
3915 .bdrv_abort_perm_update = raw_abort_perm_update,
3916 .create_opts = &raw_create_opts,
3917 .mutable_opts = mutable_opts,
3920 /***********************************************/
3921 /* host device */
3923 #if defined(HAVE_HOST_BLOCK_DEVICE)
3925 #if defined(__APPLE__) && defined(__MACH__)
3926 static kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3927 CFIndex maxPathSize, int flags);
3929 #if !defined(MAC_OS_VERSION_12_0) \
3930 || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_12_0)
3931 #define IOMainPort IOMasterPort
3932 #endif
3934 static char *FindEjectableOpticalMedia(io_iterator_t *mediaIterator)
3936 kern_return_t kernResult = KERN_FAILURE;
3937 mach_port_t mainPort;
3938 CFMutableDictionaryRef classesToMatch;
3939 const char *matching_array[] = {kIODVDMediaClass, kIOCDMediaClass};
3940 char *mediaType = NULL;
3942 kernResult = IOMainPort(MACH_PORT_NULL, &mainPort);
3943 if ( KERN_SUCCESS != kernResult ) {
3944 printf("IOMainPort returned %d\n", kernResult);
3947 int index;
3948 for (index = 0; index < ARRAY_SIZE(matching_array); index++) {
3949 classesToMatch = IOServiceMatching(matching_array[index]);
3950 if (classesToMatch == NULL) {
3951 error_report("IOServiceMatching returned NULL for %s",
3952 matching_array[index]);
3953 continue;
3955 CFDictionarySetValue(classesToMatch, CFSTR(kIOMediaEjectableKey),
3956 kCFBooleanTrue);
3957 kernResult = IOServiceGetMatchingServices(mainPort, classesToMatch,
3958 mediaIterator);
3959 if (kernResult != KERN_SUCCESS) {
3960 error_report("Note: IOServiceGetMatchingServices returned %d",
3961 kernResult);
3962 continue;
3965 /* If a match was found, leave the loop */
3966 if (*mediaIterator != 0) {
3967 trace_file_FindEjectableOpticalMedia(matching_array[index]);
3968 mediaType = g_strdup(matching_array[index]);
3969 break;
3972 return mediaType;
3975 kern_return_t GetBSDPath(io_iterator_t mediaIterator, char *bsdPath,
3976 CFIndex maxPathSize, int flags)
3978 io_object_t nextMedia;
3979 kern_return_t kernResult = KERN_FAILURE;
3980 *bsdPath = '\0';
3981 nextMedia = IOIteratorNext( mediaIterator );
3982 if ( nextMedia )
3984 CFTypeRef bsdPathAsCFString;
3985 bsdPathAsCFString = IORegistryEntryCreateCFProperty( nextMedia, CFSTR( kIOBSDNameKey ), kCFAllocatorDefault, 0 );
3986 if ( bsdPathAsCFString ) {
3987 size_t devPathLength;
3988 strcpy( bsdPath, _PATH_DEV );
3989 if (flags & BDRV_O_NOCACHE) {
3990 strcat(bsdPath, "r");
3992 devPathLength = strlen( bsdPath );
3993 if ( CFStringGetCString( bsdPathAsCFString, bsdPath + devPathLength, maxPathSize - devPathLength, kCFStringEncodingASCII ) ) {
3994 kernResult = KERN_SUCCESS;
3996 CFRelease( bsdPathAsCFString );
3998 IOObjectRelease( nextMedia );
4001 return kernResult;
4004 /* Sets up a real cdrom for use in QEMU */
4005 static bool setup_cdrom(char *bsd_path, Error **errp)
4007 int index, num_of_test_partitions = 2, fd;
4008 char test_partition[MAXPATHLEN];
4009 bool partition_found = false;
4011 /* look for a working partition */
4012 for (index = 0; index < num_of_test_partitions; index++) {
4013 snprintf(test_partition, sizeof(test_partition), "%ss%d", bsd_path,
4014 index);
4015 fd = qemu_open(test_partition, O_RDONLY | O_BINARY | O_LARGEFILE, NULL);
4016 if (fd >= 0) {
4017 partition_found = true;
4018 qemu_close(fd);
4019 break;
4023 /* if a working partition on the device was not found */
4024 if (partition_found == false) {
4025 error_setg(errp, "Failed to find a working partition on disc");
4026 } else {
4027 trace_file_setup_cdrom(test_partition);
4028 pstrcpy(bsd_path, MAXPATHLEN, test_partition);
4030 return partition_found;
4033 /* Prints directions on mounting and unmounting a device */
4034 static void print_unmounting_directions(const char *file_name)
4036 error_report("If device %s is mounted on the desktop, unmount"
4037 " it first before using it in QEMU", file_name);
4038 error_report("Command to unmount device: diskutil unmountDisk %s",
4039 file_name);
4040 error_report("Command to mount device: diskutil mountDisk %s", file_name);
4043 #endif /* defined(__APPLE__) && defined(__MACH__) */
4045 static int hdev_probe_device(const char *filename)
4047 struct stat st;
4049 /* allow a dedicated CD-ROM driver to match with a higher priority */
4050 if (strstart(filename, "/dev/cdrom", NULL))
4051 return 50;
4053 if (stat(filename, &st) >= 0 &&
4054 (S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode))) {
4055 return 100;
4058 return 0;
4061 static void hdev_parse_filename(const char *filename, QDict *options,
4062 Error **errp)
4064 bdrv_parse_filename_strip_prefix(filename, "host_device:", options);
4067 static bool hdev_is_sg(BlockDriverState *bs)
4070 #if defined(__linux__)
4072 BDRVRawState *s = bs->opaque;
4073 struct stat st;
4074 struct sg_scsi_id scsiid;
4075 int sg_version;
4076 int ret;
4078 if (stat(bs->filename, &st) < 0 || !S_ISCHR(st.st_mode)) {
4079 return false;
4082 ret = ioctl(s->fd, SG_GET_VERSION_NUM, &sg_version);
4083 if (ret < 0) {
4084 return false;
4087 ret = ioctl(s->fd, SG_GET_SCSI_ID, &scsiid);
4088 if (ret >= 0) {
4089 trace_file_hdev_is_sg(scsiid.scsi_type, sg_version);
4090 return true;
4093 #endif
4095 return false;
4098 static int hdev_open(BlockDriverState *bs, QDict *options, int flags,
4099 Error **errp)
4101 BDRVRawState *s = bs->opaque;
4102 int ret;
4104 #if defined(__APPLE__) && defined(__MACH__)
4106 * Caution: while qdict_get_str() is fine, getting non-string types
4107 * would require more care. When @options come from -blockdev or
4108 * blockdev_add, its members are typed according to the QAPI
4109 * schema, but when they come from -drive, they're all QString.
4111 const char *filename = qdict_get_str(options, "filename");
4112 char bsd_path[MAXPATHLEN] = "";
4113 bool error_occurred = false;
4115 /* If using a real cdrom */
4116 if (strcmp(filename, "/dev/cdrom") == 0) {
4117 char *mediaType = NULL;
4118 kern_return_t ret_val;
4119 io_iterator_t mediaIterator = 0;
4121 mediaType = FindEjectableOpticalMedia(&mediaIterator);
4122 if (mediaType == NULL) {
4123 error_setg(errp, "Please make sure your CD/DVD is in the optical"
4124 " drive");
4125 error_occurred = true;
4126 goto hdev_open_Mac_error;
4129 ret_val = GetBSDPath(mediaIterator, bsd_path, sizeof(bsd_path), flags);
4130 if (ret_val != KERN_SUCCESS) {
4131 error_setg(errp, "Could not get BSD path for optical drive");
4132 error_occurred = true;
4133 goto hdev_open_Mac_error;
4136 /* If a real optical drive was not found */
4137 if (bsd_path[0] == '\0') {
4138 error_setg(errp, "Failed to obtain bsd path for optical drive");
4139 error_occurred = true;
4140 goto hdev_open_Mac_error;
4143 /* If using a cdrom disc and finding a partition on the disc failed */
4144 if (strncmp(mediaType, kIOCDMediaClass, 9) == 0 &&
4145 setup_cdrom(bsd_path, errp) == false) {
4146 print_unmounting_directions(bsd_path);
4147 error_occurred = true;
4148 goto hdev_open_Mac_error;
4151 qdict_put_str(options, "filename", bsd_path);
4153 hdev_open_Mac_error:
4154 g_free(mediaType);
4155 if (mediaIterator) {
4156 IOObjectRelease(mediaIterator);
4158 if (error_occurred) {
4159 return -ENOENT;
4162 #endif /* defined(__APPLE__) && defined(__MACH__) */
4164 s->type = FTYPE_FILE;
4166 ret = raw_open_common(bs, options, flags, 0, true, errp);
4167 if (ret < 0) {
4168 #if defined(__APPLE__) && defined(__MACH__)
4169 if (*bsd_path) {
4170 filename = bsd_path;
4172 /* if a physical device experienced an error while being opened */
4173 if (strncmp(filename, "/dev/", 5) == 0) {
4174 print_unmounting_directions(filename);
4176 #endif /* defined(__APPLE__) && defined(__MACH__) */
4177 return ret;
4180 /* Since this does ioctl the device must be already opened */
4181 bs->sg = hdev_is_sg(bs);
4183 return ret;
4186 #if defined(__linux__)
4187 static int coroutine_fn
4188 hdev_co_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
4190 BDRVRawState *s = bs->opaque;
4191 RawPosixAIOData acb;
4192 int ret;
4194 ret = fd_open(bs);
4195 if (ret < 0) {
4196 return ret;
4199 if (req == SG_IO && s->pr_mgr) {
4200 struct sg_io_hdr *io_hdr = buf;
4201 if (io_hdr->cmdp[0] == PERSISTENT_RESERVE_OUT ||
4202 io_hdr->cmdp[0] == PERSISTENT_RESERVE_IN) {
4203 return pr_manager_execute(s->pr_mgr, qemu_get_current_aio_context(),
4204 s->fd, io_hdr);
4208 acb = (RawPosixAIOData) {
4209 .bs = bs,
4210 .aio_type = QEMU_AIO_IOCTL,
4211 .aio_fildes = s->fd,
4212 .aio_offset = 0,
4213 .ioctl = {
4214 .buf = buf,
4215 .cmd = req,
4219 return raw_thread_pool_submit(handle_aiocb_ioctl, &acb);
4221 #endif /* linux */
4223 static coroutine_fn int
4224 hdev_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
4226 BDRVRawState *s = bs->opaque;
4227 int ret;
4229 ret = fd_open(bs);
4230 if (ret < 0) {
4231 raw_account_discard(s, bytes, ret);
4232 return ret;
4234 return raw_do_pdiscard(bs, offset, bytes, true);
4237 static coroutine_fn int hdev_co_pwrite_zeroes(BlockDriverState *bs,
4238 int64_t offset, int64_t bytes, BdrvRequestFlags flags)
4240 int rc;
4242 rc = fd_open(bs);
4243 if (rc < 0) {
4244 return rc;
4247 return raw_do_pwrite_zeroes(bs, offset, bytes, flags, true);
4250 static BlockDriver bdrv_host_device = {
4251 .format_name = "host_device",
4252 .protocol_name = "host_device",
4253 .instance_size = sizeof(BDRVRawState),
4254 .bdrv_needs_filename = true,
4255 .bdrv_probe_device = hdev_probe_device,
4256 .bdrv_parse_filename = hdev_parse_filename,
4257 .bdrv_file_open = hdev_open,
4258 .bdrv_close = raw_close,
4259 .bdrv_reopen_prepare = raw_reopen_prepare,
4260 .bdrv_reopen_commit = raw_reopen_commit,
4261 .bdrv_reopen_abort = raw_reopen_abort,
4262 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
4263 .create_opts = &bdrv_create_opts_simple,
4264 .mutable_opts = mutable_opts,
4265 .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
4266 .bdrv_co_pwrite_zeroes = hdev_co_pwrite_zeroes,
4268 .bdrv_co_preadv = raw_co_preadv,
4269 .bdrv_co_pwritev = raw_co_pwritev,
4270 .bdrv_co_flush_to_disk = raw_co_flush_to_disk,
4271 .bdrv_co_pdiscard = hdev_co_pdiscard,
4272 .bdrv_co_copy_range_from = raw_co_copy_range_from,
4273 .bdrv_co_copy_range_to = raw_co_copy_range_to,
4274 .bdrv_refresh_limits = raw_refresh_limits,
4276 .bdrv_co_truncate = raw_co_truncate,
4277 .bdrv_co_getlength = raw_co_getlength,
4278 .bdrv_co_get_info = raw_co_get_info,
4279 .bdrv_get_specific_info = raw_get_specific_info,
4280 .bdrv_co_get_allocated_file_size = raw_co_get_allocated_file_size,
4281 .bdrv_get_specific_stats = hdev_get_specific_stats,
4282 .bdrv_check_perm = raw_check_perm,
4283 .bdrv_set_perm = raw_set_perm,
4284 .bdrv_abort_perm_update = raw_abort_perm_update,
4285 .bdrv_probe_blocksizes = hdev_probe_blocksizes,
4286 .bdrv_probe_geometry = hdev_probe_geometry,
4288 /* generic scsi device */
4289 #ifdef __linux__
4290 .bdrv_co_ioctl = hdev_co_ioctl,
4291 #endif
4293 /* zoned device */
4294 #if defined(CONFIG_BLKZONED)
4295 /* zone management operations */
4296 .bdrv_co_zone_report = raw_co_zone_report,
4297 .bdrv_co_zone_mgmt = raw_co_zone_mgmt,
4298 .bdrv_co_zone_append = raw_co_zone_append,
4299 #endif
4302 #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
4303 static void cdrom_parse_filename(const char *filename, QDict *options,
4304 Error **errp)
4306 bdrv_parse_filename_strip_prefix(filename, "host_cdrom:", options);
4309 static void cdrom_refresh_limits(BlockDriverState *bs, Error **errp)
4311 bs->bl.has_variable_length = true;
4312 raw_refresh_limits(bs, errp);
4314 #endif
4316 #ifdef __linux__
4317 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
4318 Error **errp)
4320 BDRVRawState *s = bs->opaque;
4322 s->type = FTYPE_CD;
4324 /* open will not fail even if no CD is inserted, so add O_NONBLOCK */
4325 return raw_open_common(bs, options, flags, O_NONBLOCK, true, errp);
4328 static int cdrom_probe_device(const char *filename)
4330 int fd, ret;
4331 int prio = 0;
4332 struct stat st;
4334 fd = qemu_open(filename, O_RDONLY | O_NONBLOCK, NULL);
4335 if (fd < 0) {
4336 goto out;
4338 ret = fstat(fd, &st);
4339 if (ret == -1 || !S_ISBLK(st.st_mode)) {
4340 goto outc;
4343 /* Attempt to detect via a CDROM specific ioctl */
4344 ret = ioctl(fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
4345 if (ret >= 0)
4346 prio = 100;
4348 outc:
4349 qemu_close(fd);
4350 out:
4351 return prio;
4354 static bool coroutine_fn cdrom_co_is_inserted(BlockDriverState *bs)
4356 BDRVRawState *s = bs->opaque;
4357 int ret;
4359 ret = ioctl(s->fd, CDROM_DRIVE_STATUS, CDSL_CURRENT);
4360 return ret == CDS_DISC_OK;
4363 static void coroutine_fn cdrom_co_eject(BlockDriverState *bs, bool eject_flag)
4365 BDRVRawState *s = bs->opaque;
4367 if (eject_flag) {
4368 if (ioctl(s->fd, CDROMEJECT, NULL) < 0)
4369 perror("CDROMEJECT");
4370 } else {
4371 if (ioctl(s->fd, CDROMCLOSETRAY, NULL) < 0)
4372 perror("CDROMEJECT");
4376 static void coroutine_fn cdrom_co_lock_medium(BlockDriverState *bs, bool locked)
4378 BDRVRawState *s = bs->opaque;
4380 if (ioctl(s->fd, CDROM_LOCKDOOR, locked) < 0) {
4382 * Note: an error can happen if the distribution automatically
4383 * mounts the CD-ROM
4385 /* perror("CDROM_LOCKDOOR"); */
4389 static BlockDriver bdrv_host_cdrom = {
4390 .format_name = "host_cdrom",
4391 .protocol_name = "host_cdrom",
4392 .instance_size = sizeof(BDRVRawState),
4393 .bdrv_needs_filename = true,
4394 .bdrv_probe_device = cdrom_probe_device,
4395 .bdrv_parse_filename = cdrom_parse_filename,
4396 .bdrv_file_open = cdrom_open,
4397 .bdrv_close = raw_close,
4398 .bdrv_reopen_prepare = raw_reopen_prepare,
4399 .bdrv_reopen_commit = raw_reopen_commit,
4400 .bdrv_reopen_abort = raw_reopen_abort,
4401 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
4402 .create_opts = &bdrv_create_opts_simple,
4403 .mutable_opts = mutable_opts,
4404 .bdrv_co_invalidate_cache = raw_co_invalidate_cache,
4406 .bdrv_co_preadv = raw_co_preadv,
4407 .bdrv_co_pwritev = raw_co_pwritev,
4408 .bdrv_co_flush_to_disk = raw_co_flush_to_disk,
4409 .bdrv_refresh_limits = cdrom_refresh_limits,
4411 .bdrv_co_truncate = raw_co_truncate,
4412 .bdrv_co_getlength = raw_co_getlength,
4413 .bdrv_co_get_allocated_file_size = raw_co_get_allocated_file_size,
4415 /* removable device support */
4416 .bdrv_co_is_inserted = cdrom_co_is_inserted,
4417 .bdrv_co_eject = cdrom_co_eject,
4418 .bdrv_co_lock_medium = cdrom_co_lock_medium,
4420 /* generic scsi device */
4421 .bdrv_co_ioctl = hdev_co_ioctl,
4423 #endif /* __linux__ */
4425 #if defined (__FreeBSD__) || defined(__FreeBSD_kernel__)
4426 static int cdrom_open(BlockDriverState *bs, QDict *options, int flags,
4427 Error **errp)
4429 BDRVRawState *s = bs->opaque;
4430 int ret;
4432 s->type = FTYPE_CD;
4434 ret = raw_open_common(bs, options, flags, 0, true, errp);
4435 if (ret) {
4436 return ret;
4439 /* make sure the door isn't locked at this time */
4440 ioctl(s->fd, CDIOCALLOW);
4441 return 0;
4444 static int cdrom_probe_device(const char *filename)
4446 if (strstart(filename, "/dev/cd", NULL) ||
4447 strstart(filename, "/dev/acd", NULL))
4448 return 100;
4449 return 0;
4452 static int cdrom_reopen(BlockDriverState *bs)
4454 BDRVRawState *s = bs->opaque;
4455 int fd;
4458 * Force reread of possibly changed/newly loaded disc,
4459 * FreeBSD seems to not notice sometimes...
4461 if (s->fd >= 0)
4462 qemu_close(s->fd);
4463 fd = qemu_open(bs->filename, s->open_flags, NULL);
4464 if (fd < 0) {
4465 s->fd = -1;
4466 return -EIO;
4468 s->fd = fd;
4470 /* make sure the door isn't locked at this time */
4471 ioctl(s->fd, CDIOCALLOW);
4472 return 0;
4475 static bool coroutine_fn cdrom_co_is_inserted(BlockDriverState *bs)
4477 return raw_getlength(bs) > 0;
4480 static void coroutine_fn cdrom_co_eject(BlockDriverState *bs, bool eject_flag)
4482 BDRVRawState *s = bs->opaque;
4484 if (s->fd < 0)
4485 return;
4487 (void) ioctl(s->fd, CDIOCALLOW);
4489 if (eject_flag) {
4490 if (ioctl(s->fd, CDIOCEJECT) < 0)
4491 perror("CDIOCEJECT");
4492 } else {
4493 if (ioctl(s->fd, CDIOCCLOSE) < 0)
4494 perror("CDIOCCLOSE");
4497 cdrom_reopen(bs);
4500 static void coroutine_fn cdrom_co_lock_medium(BlockDriverState *bs, bool locked)
4502 BDRVRawState *s = bs->opaque;
4504 if (s->fd < 0)
4505 return;
4506 if (ioctl(s->fd, (locked ? CDIOCPREVENT : CDIOCALLOW)) < 0) {
4508 * Note: an error can happen if the distribution automatically
4509 * mounts the CD-ROM
4511 /* perror("CDROM_LOCKDOOR"); */
4515 static BlockDriver bdrv_host_cdrom = {
4516 .format_name = "host_cdrom",
4517 .protocol_name = "host_cdrom",
4518 .instance_size = sizeof(BDRVRawState),
4519 .bdrv_needs_filename = true,
4520 .bdrv_probe_device = cdrom_probe_device,
4521 .bdrv_parse_filename = cdrom_parse_filename,
4522 .bdrv_file_open = cdrom_open,
4523 .bdrv_close = raw_close,
4524 .bdrv_reopen_prepare = raw_reopen_prepare,
4525 .bdrv_reopen_commit = raw_reopen_commit,
4526 .bdrv_reopen_abort = raw_reopen_abort,
4527 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
4528 .create_opts = &bdrv_create_opts_simple,
4529 .mutable_opts = mutable_opts,
4531 .bdrv_co_preadv = raw_co_preadv,
4532 .bdrv_co_pwritev = raw_co_pwritev,
4533 .bdrv_co_flush_to_disk = raw_co_flush_to_disk,
4534 .bdrv_refresh_limits = cdrom_refresh_limits,
4536 .bdrv_co_truncate = raw_co_truncate,
4537 .bdrv_co_getlength = raw_co_getlength,
4538 .bdrv_co_get_allocated_file_size = raw_co_get_allocated_file_size,
4540 /* removable device support */
4541 .bdrv_co_is_inserted = cdrom_co_is_inserted,
4542 .bdrv_co_eject = cdrom_co_eject,
4543 .bdrv_co_lock_medium = cdrom_co_lock_medium,
4545 #endif /* __FreeBSD__ */
4547 #endif /* HAVE_HOST_BLOCK_DEVICE */
4549 static void bdrv_file_init(void)
4552 * Register all the drivers. Note that order is important, the driver
4553 * registered last will get probed first.
4555 bdrv_register(&bdrv_file);
4556 #if defined(HAVE_HOST_BLOCK_DEVICE)
4557 bdrv_register(&bdrv_host_device);
4558 #ifdef __linux__
4559 bdrv_register(&bdrv_host_cdrom);
4560 #endif
4561 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
4562 bdrv_register(&bdrv_host_cdrom);
4563 #endif
4564 #endif /* HAVE_HOST_BLOCK_DEVICE */
4567 block_init(bdrv_file_init);